我收到此异常,但无法弄清楚原因:无法将 NULL 值插入列“UserId”
这是我的代码:
<asp:TextBox ID="FirstNameBox" runat="server" />
<br />
<br />
<asp:TextBox ID="LastNameBox" runat="server" />
<asp:SqlDataSource
ID="InsertText"
runat="server"
ConnectionString="<%$ ConnectionStrings:DefaultConnection %>"
InsertCommand="INSERT INTO UserForm (UserId,FirstName,LastName) VALUES (@UserId,@FiName,@LaName)">
<InsertParameters>
<asp:ControlParameter Name="FiName" ControlID="FirstNameBox" PropertyName="Text" />
<asp:ControlParameter Name="LaName" ControlID="LastNameBox" PropertyName="Text" />
<asp:Parameter Name="UserId" />
</InsertParameters>
</asp:SqlDataSource>
这是我的代码隐藏文件中的内容:
public void button1_Click(object sender, System.EventArgs e)
{
InsertText.Insert();
}
最佳答案
目前您已经设置了表格,您必须为 UserId 提供一个值。如果这不是预期的行为,我建议将 SQL Server 中的列更改为自动递增...
例如,它应该看起来像这样:
[UserId] INT IDENTITY (1, 1) NOT NULL
根据评论进行编辑:
I set the UserId Column to be the primary and foreign key. I set the UserId to be the GUID. When I checked the table the UserId is already there. I just want to add a users first or last name.
不确定您的问题是什么,首先您正在谈论INSERT
,现在您正在谈论为现有记录设置值。如果您想更新
现有记录,您需要先获取id并相应更新值
示例 SQL 命令可能类似于以下内容:
UPDATE UserForm SET FirstName = @FirstName, LastName = @LastName WHERE UserId = @UserId
插入正如它所说的那样 - 将新记录插入到表中。
关于c# - 无法将 NULL 值插入列 'UserId',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15346608/