Row is not updating in gridview in asp.net - 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.

Related

access database wont update asp.net [duplicate]

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.

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.

Cannot read the row of the gridview

I am trying to read a gridview row. Here is my code:
protected void allStudents_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Approval")
{
// *** Retreive the DataGridRow
int row = -1;
int.TryParse(e.CommandArgument as string, out row);
GridViewRow gdrow = allStudents.Rows[row];
// *** Get the underlying data item - in this case a DataRow
DataRow dr = ((DataTable)this.allStudents.DataSource).Rows[gdrow.DataItemIndex];
// *** Retrieve our context
string courseCode = dr["CourseCode"].ToString();
string courseNumber = dr["CourseNumber"].ToString();
string term = dr["Term"].ToString();
SqlConnection con = new SqlConnection();
con.ConnectionString = Userfunctions.GetConnectionString();
con.Open();
SqlCommand cmd = new SqlCommand("SELECT RegisterTable.StudentID, StudentTable.Name, StudentTable.Surname FROM RegisterTable JOIN StudentTable ON RegisterTable.StudentID = StudentTable.ID WHERE RegisterTable.CourseCode = #courseCode AND RegisterTable.Term = #term AND RegisterTable.CourseNumber = #courseNumber", con);
cmd.Parameters.AddWithValue("#courseCode", courseCode);
cmd.Parameters.AddWithValue("#courseNumber", courseNumber);
cmd.Parameters.AddWithValue("#term", term);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
transcript.DataSource = dt;
transcript.DataBind();
Label1.Visible = true;
Label1.Text = "Students who are registered to " + courseCode + " " + courseNumber + " are listed below:";
}
}
But at the line starting with
DataRow dr = ((DataTable)this.allStudents.DataSource).Rows[gdrow.DataItemIndex];
i get an error saying that "Object reference not set to an instance of an object.". Can anyone tell the problem here?
Note: allStudents is the ID of my gridview
Thanks
That error means of the references in the line is null. That is, you're trying to fetch data from an object, but there is no instantiated object there.
Recommendation: insert a breakpoint at that line. Debug the code. Then, while debugging and on that line, pass the mouse cursor over every name in the line. The debugger will give you rich, detailed information about each and every variable. Once you find which one is null (could be either allStudents or DataSource), you'll be on the right track to solve your problem.
You have to find out whatever is triggering the error for being null, then making sure it's not null when you get to that point in your code.

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;

Finding the item in selecteditemchanging event

In listview im showing product information .On each row there is one select button on each row in itemTemplate .
if user click this button i want which bookid is clicked in selectedindexchanging event.
i bound listview like following
string str = "SELECT BookName,BookPrice, Description, bookid FROM productinfo Where Categoryid ='" + Request.QueryString["CategoryId"] + "'";
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand cmd = new SqlCommand(str, conn);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
lstvwShopItems.DataSource = dt;
lstvwShopItems.DataBind();
Please give solution?
in order to get a certain column when selecting a row you need to fill the property datakeynames with the property of your choice.
msdn
getting the value of the property:
void lstvwShopItems_SelectedIndexChanged(Object sender, EventArgs e)
{
string value = lstvwShopItems.SelectedValue;
}
don't forget to set the OnSelectedIndexChanged on your listview to this method in the codebehind..

Resources