c# - 无法将 NULL 值插入列 'UserId'

标签 c# sql-insert sqldatasource

我收到此异常,但无法弄清楚原因:无法将 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/

相关文章:

Mysql 多个同时插入查询

生产中 Pod 的 Kubernetes 持久卷

c# - SMTP 中的传递通知

php - 当我的 php 代码没有错误时,为什么我的表是空的?

c# - 将 char 隐式转换为整数有什么好处?

php - MySQL INSERT 将 BIT 插入到 1 而不是 0

c# - 跳过WebForm中SqlDataSource中sql参数的设置值

mysql - 我无法将 MySql 数据提供程序添加到 Visual Studio 2012

c# - 函数中的参数类型验证 - 二进制模块与脚本模块

c# - 通过 TCP 共享 COM 端口