The problem is I can access the value from a certain row only from the next row.
Here is the code:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int s = GridView1.EditIndex;
string constr = "con string";
string statment = "Select Name from tb1 Where [ID] = " + s;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand comm = new SqlCommand(statment, con))
{
con.Open();
Label2.Text = comm.ExecuteScalar().ToString();
con.Close();
}
}
}
For example:
ID Name
Edit Delete Select 1 JOhn
Edit Delete Select 2 SMith
- If I click edit and update on the first row I get this :
Object reference not set to an instance of an object.
- If I click edit and update on the second row , I get the value from
the first row.
Is there any way to fix this?
Change
int sd = GridView1.EditIndex;toint sd = GridView1.EditIndex + 1;A better method would be to use the datakeynames property of the gridview.
Setting
datakeyname="id"on the gridview will allow you to retrieve the Id withint Id = Convert.ToInt32(GridView1.DataKeys[Gridview1.EditIndex].Values[0])This will use less overhead than creating an object and setting it to a control in the row containing the id to retrieve it’s value. See link for further reading on implementing datakeynames.
I would also recommend using a
System.Data.SqlClient.SqlCommandfor the SQL method and adding the Id via a parameter. This would help guard against an injection attack.