插入和更新代码在 ASP.NET 中不起作用
本文关键字:NET 不起作用 ASP 更新 代码 插入 | 更新日期: 2023-09-27 18:32:07
我在从 gridview 将数据插入/更新到 sql Server 数据库中时收到"对象引用未设置为对象的实例"错误。任何人请帮忙.
protected void GridAllStore_RowCommand(object sender, GridViewCommandEventArgs e)
{
storelocatorDataSetTableAdapters.storedbTableAdapter tastoreInsert = new storelocatorDataSetTableAdapters.storedbTableAdapter();
if (e.CommandName.Equals("Insert"))
{
TextBox txtNewName = new TextBox();
TextBox txtNewContact = new TextBox();
TextBox txtNewAddress = new TextBox();
txtNewName = (TextBox)GridAllStore.FooterRow.FindControl("txtNewName");
txtNewContact = (TextBox)GridAllStore.FooterRow.FindControl("txtNewContact");
txtNewAddress = (TextBox)GridAllStore.FooterRow.FindControl("txtNewAddress");
tastore.Insert(txtNewName.Text, txtNewContact.Text, txtNewAddress.Text);
FillGrid();
}
}
以下是错误消息:
对象引用未设置为对象的实例。
说明:执行当前 Web 请求期间发生未经处理的异常。请查看堆栈跟踪,了解有关错误及其在代码中起源位置的详细信息。
异常详细信息:System.NullReferenceException:对象引用未设置为对象的实例。
源错误:
第 107 行:txtNewContact = (TextBox)GridAllStore.FooterRow.FindControl("txtNewContact");
第 108 行:txtNewAddress = (TextBox)GridAllStore.FooterRow.FindControl("txtNewAddress");
109路:塔斯托尔。Insert(txtNewName.Text, txtNewContact.Text, txtNewAddress.Text);
第 110 行:填充网格();
第 111 行:}源文件:C:''Users''DELL''Documents''Visual Studio 2010''Projects''WebApplication1''WebApplication1''AdminPanel.aspx.cs行:109
FindControl 可以返回 null,当你访问 Text 属性时,空对象会抛出异常。 您可以在访问文本属性之前检查 null。
var txtNewNameTb = (TextBox)GridAllStore.FooterRow.FindControl("txtNewName");
var txtNewContactTb = (TextBox)GridAllStore.FooterRow.FindControl("txtNewContact");
var txtNewAddressTb = (TextBox)GridAllStore.FooterRow.FindControl("txtNewAddress");
if (txtNewNameTb == null || txtNewContactTb == null || txtNewAddressTb == null) { return; }
if(tastore == null) { return; }
tastore.Insert(txtNewNameTb.Text, txtNewContactTb.Text, txtNewAddressTb.Text);
FillGrid();
在您的ASPX页脚模板中,应该有一个3个文本框,如下所示。
<FooterTemplate>
<asp:TextBox ID="txtNewName" runat="server" >
</asp:TextBox>
<asp:TextBox ID="txtNewContact" runat="server" >
</asp:TextBox>
<asp:TextBox ID="txtNewAddress" runat="server" >
</asp:TextBox>
</FooterTemplate>
错误消息表示tastore
在第 109 行中null
,因此需要初始化tastore
。通过在函数标头中写入tastoreInsert
并在正文中写入tastore.Insert
,您使自己感到困惑。
编辑:抱歉,这也可能意味着三个文本框中的任何一个都不存在。如果未找到控件,则 FindControl 返回 null,因此您也需要查看这些控件。调试!
使用Convert.ToString(txtNewNameTb.Text)
它会自动将NULL
转换为空字符串。
尝试像:-
tastore.Insert(Convert.ToString(txtNewName.Text),Convert.ToString( txtNewContact.Text), Convert.ToString(txtNewAddress.Text));