access database wont update asp.net [duplicate] - asp.net

my access database wont update with this code. what seems to be the problem?
i have tried a lot of methods for updating my access database with no sucsess
please guys some help.
protected void Btnupdate_Click(object sender, EventArgs e)
{
foreach (RepeaterItem RI in rptEdit.Items)
{
Label id = RI.FindControl("Pid") as Label;
TextBox prdname = RI.FindControl("prdname") as TextBox;
TextBox prdprice = RI.FindControl("prdprice") as TextBox;
TextBox prdshortdesc = RI.FindControl("prdshortdesc") as TextBox;
TextBox prdtype = RI.FindControl("prdtype") as TextBox;
TextBox prdbrand = RI.FindControl("prdbrand") as TextBox;
int updated;
string connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Table.accdb";
using (var conn = new OleDbConnection(connection))
{
conn.Open();
string updSql = #"UPDATE ProductList SET
Pname = '" + prdname.Text + "' WHERE Pid = ?";
using (var cmd = new OleDbCommand(updSql, conn))
{
cmd.Parameters.Add("#Pname", OleDbType.VarChar).Value = prdname.Text;
updated = cmd.ExecuteNonQuery();
conn.Dispose();
conn.Close();
}
}
}
}

Just use the ? style parameters in your SQL.
string sql = #"UPDATE ProductList SET Pname = ? WHERE Pid = ?";
Then just make sure you add your parameters in the same order in your code that they appear in the SQL.
cmd.Parameters.Add(prdName.Text);
cmd.Parameters.Add(int.Parse(id.Text));
You need to make sure the type of the variable being added in C# matches the type in the DB (in terms of text or number). Then it can be properly quoted or not as needed.

Related

My MS Access database won't update asp.net

I'm trying to update my database without success. This is how my table looks:
https://i.stack.imgur.com/Q6EDk.png
After opening the modal its look like this:
https://i.stack.imgur.com/JusUp.png
and all the table works with a repeater, this is my code.
protected void Btnupdate_Click(object sender, EventArgs e)
{
try
{
foreach (RepeaterItem RI in rptEdit.Items)
{
Label id = RI.FindControl("Pid") as Label;
TextBox prdname = RI.FindControl("prdname") as TextBox;
TextBox prdprice = RI.FindControl("prdprice") as TextBox;
TextBox prdshortdesc = RI.FindControl("prdshortdesc") as TextBox;
TextBox prdtype = RI.FindControl("prdtype") as TextBox;
TextBox prdbrand = RI.FindControl("prdbrand") as TextBox;
Literal ltl = RI.FindControl("ltlmsg") as Literal;
string ConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Table.accdb";
string SqlString = "UPDATE ProductList SET Pname = ?";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("Pname", prdname.Text);
conn.Open();
cmd.ExecuteNonQuery();
ltl.Text = "<br/>Done.";
}
}
}
}
catch (OleDbException ex)
{
foreach (RepeaterItem RI in rptEdit.Items)
{
Literal ltl = RI.FindControl("ltlmsg") as Literal;
ltl.Text = ex.Message;
}
}
}
When I click the update button, it's refreshing but nothing happens.
Please help.
you just check your update query:
string SqlString = "UPDATE ProductList SET Pname = ?";
change to this:
string SqlString = "UPDATE ProductList SET Pname =#Pname ";
and change command parameter to pass scaler variable:
cmd.Parameters.AddWithValue("#Pname", prdname.Text);

Can't update access database threw asp.net

my access database wont update with this code. what seems to be the problem?
i have tried a lot of methods for updating my access database with no sucsess
please guys some help.
protected void Btnupdate_Click(object sender, EventArgs e)
{
foreach (RepeaterItem RI in rptEdit.Items)
{
Label id = RI.FindControl("Pid") as Label;
TextBox prdname = RI.FindControl("prdname") as TextBox;
TextBox prdprice = RI.FindControl("prdprice") as TextBox;
TextBox prdshortdesc = RI.FindControl("prdshortdesc") as TextBox;
TextBox prdtype = RI.FindControl("prdtype") as TextBox;
TextBox prdbrand = RI.FindControl("prdbrand") as TextBox;
int updated;
string connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Table.accdb";
using (var conn = new OleDbConnection(connection))
{
conn.Open();
string updSql = #"UPDATE ProductList SET
Pname = '" + prdname.Text + "' WHERE Pid = ?";
using (var cmd = new OleDbCommand(updSql, conn))
{
cmd.Parameters.Add("#Pname", OleDbType.VarChar).Value = prdname.Text;
updated = cmd.ExecuteNonQuery();
conn.Dispose();
conn.Close();
}
}
}
}
Just use the ? style parameters in your SQL.
string sql = #"UPDATE ProductList SET Pname = ? WHERE Pid = ?";
Then just make sure you add your parameters in the same order in your code that they appear in the SQL.
cmd.Parameters.Add(prdName.Text);
cmd.Parameters.Add(int.Parse(id.Text));
You need to make sure the type of the variable being added in C# matches the type in the DB (in terms of text or number). Then it can be properly quoted or not as needed.

Displaying Windows Active Directory thumbnailPhoto in asp:net Search App

I've set up a WebApplication to search the Active Directory of our organization. The Query (dynamic SQL wrapping OpenQuery) returns also the hexadecimal data for the thumpnailPhoto.
When I'm displaying the image I get a 40% success on all pictures displayed. The "bad" ones are usually fine in the first 15% starting from the top and then stop with black stripes. Sometimes there is picture data repeated in stripes... Some profile pictures are not displayed at all, while others are perfect. There must be different image formats, but not having access to the storage positions of these images I do not get any further.
This is what I do:
I bind the data from the query to a GridView.
protected void FillGrid(Object sender, EventArgs e)
{
SqlConnection objConn = new SqlConnection("Data Source=XXXXXXXXXX");
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand objCommand = new SqlCommand(#"declare #SQL nvarchar(4000)
declare #Asterisc nvarchar(1)
declare #Sub nvarchar(12)
set #SearchName = CASE WHEN #SearchName = '' THEN '*' ELSE #SearchName END
set #SearchSurename = CASE WHEN #SearchSurename = '' THEN '*' ELSE #SearchSurename END
set #Asterisc = '*'
set #Sub = CASE WHEN #Subsidiary = '*' THEN '' ELSE (#Subsidiary+', OU=') END
set #SQL ='SELECT TOP (100) PERCENT samAccountName AS UserAccount, givenName AS FirstName, sn AS LastName, department, title AS Position,
physicaldeliveryofficename AS Office, extensionAttribute1 AS PersonnelID, initials, mail AS email, telephonenumber AS Phone, extensionattribute5 AS Extension,
mobile, extensionattribute3 AS MobileExt, thumbnailPhoto
FROM OPENQUERY(ADSI, ''SELECT samAccountName, givenName, sn, legacyExchangeDN, department, title, physicaldeliveryofficename, extensionAttribute1, distinguishedName, initials,
mail, telephonenumber, extensionattribute5, mobile, extensionattribute3, thumbnailPhoto
FROM ''''LDAP://OU=' + #Sub + 'XXXX, DC=XXXX,DC=XXXX,DC=XXXX''''
WHERE objectClass=''''Person'''' AND objectClass = ''''User'''' AND givenName = ''''' + #SearchName + ''''' AND samAccountName = ''''' + #SearchSurename + ''''' AND extensionAttribute1 = ''''' + #Asterisc + ''''' '') AS AD_Users
ORDER BY UserAccount'
exec (#SQL)", objConn);
objCommand.Parameters.Add("#SearchName", SqlDbType.NVarChar).Value = TextBoxSearchName.Text;
objCommand.Parameters.Add("#SearchSurename", SqlDbType.NVarChar).Value = TextBoxSearchSureName.Text;
objCommand.Parameters.Add("#Subsidiary", SqlDbType.NVarChar).Value = DDSubsidiary.Text;
DataTable t = new DataTable();
adapter.SelectCommand = objCommand;
objConn.Open();
adapter.Fill(t);
objConn.Close();
GridView.DataSource = t;
GridView.DataBind();
}
Then during the RowDataBound event I encode the data like this and bind that data to an asp:image control:
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView dr = (DataRowView)e.Row.DataItem;
if(!String.IsNullOrEmpty(Convert.ToString(dr["thumbnailPhoto"])))
{
string imageUrl = "data:image/jpg;base64," + Convert.ToBase64String((byte[])dr["thumbnailPhoto"]);
(e.Row.FindControl("Image1") as Image).ImageUrl = imageUrl;
}
}
}
What problem am I facing here and how to deal with it?
I just discovered that those pictures that are displayed partially or with stripes are all pictures that are stored in a bigger 600x600 format, while the good ones have a 96x96 format. That leads me to my suspicion that something is going wrong when retrieving the thumbprintPhoto in it's hexacecimal format through SQL.
As Gabriel suggested, I tried to use the DirectorySearcher. The thumbprintPhoto was displayed correctly but it took me more than 10 seconds to retrieve 44 AD entries: Here is my code
protected void SearchAD(object sender, EventArgs e)
{
string Name = TextBoxSearchFirstName.Text;
Name = Name.Replace("*", "") + "*";
DirectorySearcher dsSearcher = new DirectorySearcher();
dsSearcher.Filter = "(&(objectClass=user) (sn=" + Name + "))";
results = dsSearcher.FindAll();
DataTable t = new DataTable("ActiveDir");
t.Columns.Add(new DataColumn("SecondName", System.Type.GetType("System.String")));
t.Columns.Add(new DataColumn("FirstName", System.Type.GetType("System.String")));
t.Columns.Add(new DataColumn("UserID", System.Type.GetType("System.String")));
t.Columns.Add(new DataColumn("data", System.Type.GetType("System.Byte[]")));
if (results != null)
{
foreach (SearchResult searchResult in results)
{
DataRow myRow;
myRow = t.NewRow();
myRow[0] = searchResult.GetDirectoryEntry().Properties["sn"].Value;
myRow[1] = searchResult.GetDirectoryEntry().Properties["givenName"].Value;
myRow[2] = searchResult.GetDirectoryEntry().Properties["samAccountName"].Value;
myRow[3] = searchResult.GetDirectoryEntry().Properties["thumbnailPhoto"].Value;
t.Rows.Add(myRow);
}
}
GridView1.DataSource = t;
GridView1.DataBind();
}
Solved: Gabriel tuned the AD Search code and now it's faster than the SQL Query.
In order to display the AD Thumnail Profil pictures without using a handler do the decoding during the GridViews OnRowDataBound Event:
protected void OnRowDataBoundAdUser(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView dr = (DataRowView)e.Row.DataItem;
if (!String.IsNullOrEmpty(Convert.ToString(dr["data"])))
{
byte[] data = dr["data"] as byte[];
MemoryStream s = new MemoryStream(data);
byte[] imageBytes = s.ToArray();
string base64String = Convert.ToBase64String(imageBytes);
string imageUrl = "data:image/jpg;base64," + base64String;
(e.Row.FindControl("Image1") as System.Web.UI.WebControls.Image).ImageUrl = imageUrl;
}
}
}
I see why it's taking so long. DirectorySearcher and DirectoryEntry can be a little sneaky with how many times it reaches out to AD. You have a lot more network requests going on there than you need.
In your code, you're going out to AD once for the search. Then for each result, you're using GetDirectoryEntry(). Then DirectoryEntry is going out to AD again the first time you use Properties. Worse still, as soon as you use Properties, it downloads every single attribute that has a value, even though you're only actually using 4 of them. That's a whole lot of useless network traffic.
You can avoid this by using Properties collection in the search results, which already has all the attributes (by default it gets every attribute that has a value).
But you can do even better: If you set the PropertiesToLoad property of DirectorySearcher then it will only return the values you want to use. This way, you have one network request for everything you want, and only what you want.
protected void SearchAD(object sender, EventArgs e)
{
string Name = TextBoxSearchFirstName.Text;
Name = Name.Replace("*", "") + "*";
var dsSearcher = new DirectorySearcher {
Filter = "(&(objectClass=user) (sn=" + Name + "))"
};
dsSearcher.PropertiesToLoad.Add("sn");
dsSearcher.PropertiesToLoad.Add("givenName");
dsSearcher.PropertiesToLoad.Add("samAccountName");
dsSearcher.PropertiesToLoad.Add("thumbnailPhoto");
using (var results = dsSearcher.FindAll()) {
var t = new DataTable("ActiveDir");
t.Columns.Add(new DataColumn("SecondName", typeof(string)));
t.Columns.Add(new DataColumn("FirstName", typeof(string)));
t.Columns.Add(new DataColumn("UserID", typeof(string)));
t.Columns.Add(new DataColumn("data", typeof(byte[])));
foreach (SearchResult searchResult in results) {
var myRow = t.NewRow();
myRow[0] = searchResult.Properties.Contains("sn") ? searchResult.Properties["sn"][0] : null;
myRow[1] = searchResult.Properties.Contains("givenName") ? searchResult.Properties["givenName"][0] : null;
myRow[2] = searchResult.Properties.Contains("samAccountName") ? searchResult.Properties["samAccountName"][0] : null;
myRow[3] = searchResult.Properties.Contains("thumbnailPhoto") ? searchResult.Properties["thumbnailPhoto"][0] : null;
t.Rows.Add(myRow);
}
}
GridView1.DataSource = t;
GridView1.DataBind();
}
A few notes:
The calls to Contains are needed because if the attribute is empty, then it doesn't exist in the Properties collection at all.
The search results returns everything as an array, regardless of whether it is or not in AD. Thus, the [0] is needed for every attribute.
You'll notice I put a using statement around the search results. This is needed to prevent memory leaks, according to the documentation of FindAll().

Row is not updating in gridview in asp.net

I am using update commandField in Gridview. the Textbox used in gridview returning old value. the code for this.
string id = ((Label)GridView1.Rows[e.RowIndex].FindControl("Label6")).Text;
string name = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox1")).Text;
string number = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox2")).Text;
string mail = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox3")).Text;
string address = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox4")).Text;
string s = "update contacts set c_name='"+name+"', c_number='"+number+"', c_mail = '"+mail+"', c_address = '"+address+"' where contact_id = "+id+"";
getsqlConnection();
dbConnection.Open();
MySqlCommand cmd = new MySqlCommand(s, dbConnection);
cmd.ExecuteNonQuery();
GridView1.EditIndex = -1;
loadcontacts();
Please Help...
if (!IsPostBack)
{
}
This code at Page Load solved my problem.

Update in GridView "No value given for one or more parameters"

I have this code (below) and I am getting the following error:
No value given for one or more parameters
But when it is run again, values are shown updated for 'RateCenterName', 'QuantityThreshold', 'RateCenterID' but not for 'Province'
The code:
string updateSql = "UPDATE RateCenters SET RateCenterName = ?, Province=?, QuantityThreshold = ?" + " WHERE RateCenterID= ?";
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
DropDownList ddl = (DropDownList)row.FindControl("DropDownList2"); // assigning the dropdownlist item to 'ddl'
TextBox rateCenterName = (TextBox)row.FindControl("txtRateCenterName"); // assigning textbox input item
TextBox quantityThreshold = (TextBox)row.FindControl("txtQuantityThreshold"); // assigning textbox input item
Label ratecenterid = (Label)row.FindControl("Label1"); // assigning the label value
//OleDbConnection conn = new OleDbConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ToString());
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\arjun.giridhar\My Documents\Visual Studio 2010\Projects\BillingApplicationNew\BillingApplicationNew\App_Data\db1.mdb;Persist Security Info=False");
OleDbCommand cmd = null;
try
{
cmd = new OleDbCommand(updateSql, conn);
cmd.Parameters.Add("#RateCenterName", OleDbType.VarChar).Value = rateCenterName.Text;
cmd.Parameters.Add("#Province", OleDbType.VarChar).Value = ddl.SelectedItem.Text;
cmd.Parameters.Add("#QuantityThreshold", OleDbType.Integer).Value = Convert.ToUInt32(quantityThreshold.Text);
cmd.Parameters.Add("#RateCenterID", OleDbType.Integer).Value = Convert.ToInt32(ratecenterid.Text);
conn.Open();
cmd.Connection = conn;
cmd.ExecuteNonQuery();
//GridView1.EditIndex = -1; //refreshing
//GridView1.DataBind();
}
catch (OleDbException ex)
{
throw (ex);
}
finally
{
conn.Close();
conn.Dispose();
}
}
Can anyone see what's wrong?
Moderator edit:
He solved the problem, but his solution is deep inside one of the comment threads:
I got it, i removed the Row updating event and just tried it once
again without adding that event.
I think he means: he took this code out of the RowUpdating event handler and put it elsewhere.
there might be Problem in your code because you are trying to edit access database and you are writing code of sqldatabase....
You Update Statement code
string updateSql = "UPDATE RateCenters SET RateCenterName =?, Province=? ,
QuantityThreshold = ? WHERE RateCenterID= ?";
using (OleDbConnection con = new OleDbConnection(scon))
{
using (OleDbCommand cmd = new OleDbCommand(str, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("RateCenterName", str2);
cmd.Parameters.AddWithValue("Province", str3);
cmd.Parameters.AddWithValue("QuantityThreshold ", str4);
cmd.Parameters.AddWithValue("RateCenterID", str5);
con.Open();
cmd.ExecuteNonQuery();
}
}
You have a missing space before WHERE when you are building your SQL.
Line 2 in your sample code.
"WHERE RateCenterID= #RateCenterID"; // this the error. you need to provide space before where
you need to add space before Where .
this you should try
string updateSql = "UPDATE RateCenters SET RateCenterName = #RateCenterName, Province=
#Province, QuantityThreshold = #QuantityThreshold" + " WHERE RateCenterID= #RateCenterID";
The most likely problem is passing a null value to either RateCenterName or Province.
What happens when you try this:
cmd.Parameters.Add("#RateCenterName", OleDbType.VarChar).Value = "rateCenter";
cmd.Parameters.Add("#Province", OleDbType.VarChar).Value = "ddl";
cmd.Parameters.Add("#QuantityThreshold", OleDbType.Integer).Value = 0;
cmd.Parameters.Add("#RateCenterID", OleDbType.Integer).Value = 1;

Resources