为什么我在下面的代码中获得NULL EXCEPTION?
我得到NULLREFERENCEEXCEPTION
在gridview更新查询。为什么我在下面的代码中获得NULL EXCEPTION?
protected void GridView1_RowUpdating(Object sender, GridViewUpdateEventArgs e)
{
TextBox txtname = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtname1");
cmd.Connection = con;
cmd.CommandText = "update test1 set Name='" + txtname.Text + "' where Roll_No = '"
+ GridView1.DataKeys[e.RowIndex].Values[0].ToString() + "'";
con.Open();
int temp = cmd.ExecuteNonQuery();
if (temp == 1)
{
Label1.Text = "Record updated sucessfully";
}
GridView1.EditIndex = -1;
FillGrid();
con.Close();
}
有很多,但一些可能是
TextBox txtname = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtname1");
有行中没有文本框。由于某种原因。
GridView1.DataKeys[e.RowIndex].Values[0].ToString()
上面值为空。
另一个原因可能是,你可能会在page_load
结合它,而不是page_load (!Page.IsPostBack)
请确保您已经正确控制的名字和你的代码检查空
if(GridView1.Rows[e.RowIndex].FindControl("txtname1")!=null)
{
//your code
}
调试,看看它会产生异常。
使用它来调试它。
try{
TextBox txtname = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtname1");
cmd.Connection = con;
cmd.CommandText = "update test1 set Name='" + txtname.Text + "' where Roll_No = '" + GridView1.DataKeys[e.RowIndex].Values[0].ToString() + "'";
con.Open();
int temp = cmd.ExecuteNonQuery();
if (temp == 1)
{ Label1.Text = "Record updated sucessfully"; }
else{Label1.Text = "Updating failure";}
GridView1.EditIndex = -1;
FillGrid();
con.Close();
}
catch (Exception e)
{
e.printStackTrace();
}
尝试使用此方法验证的问题来源:
TextBox txtname = GridView1.Rows[e.RowIndex].FindControl("txtname1") as TestBox;
if(txtname is null)
{
Response.Write("Unable to find txtname");
return;
}
如果您的网格是在一个母版页的的ContentPlaceHolder,那么你的控件的ID会在运行时改变。您可以将文本框的“ClientIdMode”属性设置为“静态”,以便在运行时ID保持不变。
我收到了一个异常“无法找到txtname” – 2013-04-20 09:55:27
这是来自代码的消息。将文本框“txtname1”的“ClientIDMode”属性设置为“静态”,然后重试。 – 2013-04-20 09:57:12
没有使用母版页 – 2013-04-20 09:57:27
请使用调试器来确定哪个东西是空的。代码中有很多可能性,我们无法猜测。 – Mat 2013-04-20 09:35:30
什么样的调试器? – 2013-04-20 09:38:18
把你的gridview结构放在这里。 – 2013-04-20 09:39:29