Nitin Sharma

Nitin Sharma

  • NA
  • 154
  • 61.7k

how to edit row in gridview in asp.net

Apr 23 2015 5:56 AM

?
I m using this code to update a value in gridview .

my design code is :

<asp:GridView ID="GridView1" runat="server" AutoGenerateEditButton="True"

DataKeyNames="id" onrowcancelingedit="GridView1_RowCancelingEdit1"

onrowediting="GridView1_RowEditing1"

onrowupdating="GridView1_RowUpdating1">

</asp:GridView>

 

and my source code:

protected void GridView1_RowUpdating1(object sender, GridViewUpdateEventArgs e)

{

con.Open();

int id = 0;

string status = "";

string query = "Select id,status from book";

SqlCommand cmd = new SqlCommand(query, con);

SqlDataReader dr = cmd.ExecuteReader();

while (dr.Read())

{

id =(int) dr[0];

status = dr[1].ToString();

}

id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0].ToString());

status= Convert.ToString(((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEmployeeCode")).Text);

SqlDataAdapter da = new SqlDataAdapter("update book set status='" + status + "' where id='" + Convert.ToInt32(id) + "'", con);

DataSet ds = new DataSet();

da.Fill(ds);

GridView1.EditIndex = -1;

display();

con.Close();

Response.Write("Ho Gaya");

}

but this code show error that

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 61:         } Line 62:         id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0].ToString()); Line 63:         status= Convert.ToString(((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEmployeeCode")).Text); Line 64:         SqlDataAdapter da = new SqlDataAdapter("update book set status='" + status + "' where id='" + Convert.ToInt32(id) + "'", con); Line 65:         DataSet ds = new DataSet();


Source File: d:\Education\Project\Air India\WebSite3\Bstatus.aspx.cs Line: 63
please help me to solve code . 


Answers (2)