Asp.net 为什么在下面的代码中会出现NULL异常?
我在gridview中获得更新查询的Asp.net 为什么在下面的代码中会出现NULL异常?,asp.net,gridview,Asp.net,Gridview,我在gridview中获得更新查询的NULLREFERENCEEXCEPTION protected void GridView1_RowUpdating(Object sender, GridViewUpdateEventArgs e) { TextBox txtname = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtname1"); cmd.Connection = con; cmd.CommandText =
NULLREFERENCEEXCEPTION
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\u load
而不是page\u load(!page.IsPostBack)
确保控件名称正确并检查是否为null
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将在运行时更改。您可以将textbox的“ClientIdMode”属性设置为“static”,以便ID在运行时保持不变。请使用调试器查明哪一项是空的。你的代码中有很多可能性,我们无法猜测。什么类型的调试器?将你的gridview结构放在这里。MSDN关于调试asp.net的文章:我遇到一个异常“找不到txtname”这是来自代码的消息。将文本框“txtname1”的“ClientIDMode”属性设置为“Static”,然后重试。