Gridbox内部的更新未完成。异常处理错误

时间:2016-05-25 08:38:12

标签: c# asp.net .net gridview

我在网格框中进行了编辑/更新/删除/取消。所有的功能都很好。除了更新。

当我点击时,我收到错误说明,

NullReferenceException was unhandled by the user code.
Object Reference not set to an instance of an object

以下是更新数据的代码

protected void Show_Grid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    int id = int.Parse(Show_Grid.DataKeys[e.RowIndex].Value.ToString());
    TextBox title_txt = (TextBox)Show_Grid.Rows[e.RowIndex].FindControl("Title");
    TextBox Desc_Txt = (TextBox)Show_Grid.Rows[e.RowIndex].FindControl("Description");
    DropDownList Prior_Drop = (DropDownList)Show_Grid.Rows[e.RowIndex].FindControl("Priority");

    Update_todo(id, title_txt.Text, Desc_Txt.Text, Prior_Drop.SelectedValue);
    Show_Grid.EditIndex = -1;
    BindData();
}
private void Update_todo(int id, string title, string desc, string prior)
{
    string source = "Data Source=.\\SQLEXPRESS;AttachDbFilename=...//...//..//..//tododb.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
    SqlConnection dbconnect = new SqlConnection(source);
    string query = "UPDATE todolist SET Title='" + title + "', Description='" + desc + "', Priority='" + prior + "' WHERE id =" + id + " ";
    SqlCommand cmd = new SqlCommand(query, dbconnect);
    dbconnect.Open();
    cmd.ExecuteNonQuery();
}

在Gridbox中,在编辑时,我为TextBox提供了SingleLine for Title,TextBox with Multiline for Description& DropDown for Priority。 我在这一行得到了错误

Update_todo(id, title_txt.Text, Desc_Txt.Text, Prior_Drop.SelectedValue);

网格视图标记

<asp:TemplateField HeaderText="Description">
<EditItemTemplate>
<asp:TextBox ID="Desc_Txt" runat="server" Text='<%# Eval("Description") %>'
TextMode="MultiLine"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("Description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Priority">
<EditItemTemplate>
<asp:DropDownList ID="Prior_Drop" runat="server"
SelectedValue='<%# Eval("Priority") %>'>
<asp:ListItem></asp:ListItem>
<asp:ListItem>High</asp:ListItem>
<asp:ListItem>Medium</asp:ListItem>
<asp:ListItem>Low</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("Priority") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Operation" ShowDeleteButton="True"
ShowEditButton="True" />
</Columns>
</asp:GridView>

1 个答案:

答案 0 :(得分:1)

您要么未获得一个或所有控件Realm.getInstance()title_txtDesc_Txt

在访问之前检查它们是否为空

您可以在调用此类更新之前进行检查,但是您必须确保它不会以任何方式破坏您的功能

Prior_Drop

<强>更新

您正在做的错误是,您正在使用错误的ID访问控件,使用它并且它将起作用

if(title_txt!=null && Desc_Text!=null && Prior_Drop!=null)
{
   Update_todo(id, title_txt.Text, Desc_Txt.Text, Prior_Drop.SelectedValue);
   Show_Grid.EditIndex = -1;
   BindData();
}