【问题标题】:insert null value into Database when textbox is empty当文本框为空时将空值插入数据库
【发布时间】:2013-09-04 07:41:10
【问题描述】:

我在我的 Asp.net 页面中使用 LINQ 访问 DB。

在用户看到表单之前,我有一个带有一些文本框和一个提交按钮的表单,所有文本框都使用此代码为空:

txtPName.Text =null;
txtPFamily.Text = null;
txtPUsername.Text = null;
txtPPassword.Text = null;

单击按钮后,值会插入数据库,但如果文本框为空,我希望 null 值在数据库中插入,但在数据库中插入空:

 Users u = new Users()
 {
      FirstName = txtPName.Text,
      LastName = txtPFamily.Text,
      Username = txtPUsername.Text,
      Password = txtPPassword.Text
 };

【问题讨论】:

  • 只是想知道,为什么你希望它是null?对我来说,null 表示从未设置,"" 表示已设置但故意留空。

标签: c# asp.net linq textbox


【解决方案1】:

您可以使用conditional operator。由于Text 属性永远不会返回null,您可以安全地检查它们的长度是否为0(文本为空):

Users u = new Users()
{
    FirstName = txtPName.Text.Length == 0 ? null : txtPName.Text,
    LastName = txtPFamily.Text.Length == 0 ? null : txtPFamily.Text,
    Username = txtPUsername.Text.Length == 0 ? null : txtPUsername.Text,
    Password = txtPPassword.Text.Length == 0 ? null : txtPPassword.Text
};

如果您还想将空格视为“空”,请使用String.IsNullOrWhiteSpace,例如:

FirstName = String.IsNullOrWhiteSpace(txtPName.Text) ? null : txtPName.Text

【讨论】:

  • string.IsNullOrWhiteSpace() 可能会更好,因为它会 null 空白条目。
  • @Oliver:我的答案中已经包含了string.IsNullOrWhiteSpace。
  • 为空白添加的检查很棒。这帮助我避免发布我的一个问题:)。赞成。
  • 假设是一切之母...... ;) 假设文本不为空感觉很不自然。我认为第二种方法是更好的做法。
  • 您始终可以使用 string.IsNullOrEmpty 或 string.IsNullOrWhiteSpace 代替。但是,在 ASP.NET 中,文本永远不会为空,这毫无价值(尤其是因为 OP 试图明确地将其设置为空)。模式总是返回 string.Empty 。这是缩短的来源(ILSpy,TextBox.Text-get):if (text != null) { return text; } return string.Empty;
【解决方案2】:

您可以使用 string.IsNullOrEmpty 或 string.IsNullOrWhiteSpace 方法来检查您的 TextBox 值。

//这会将您的文本框的字符串设置为一个值(如果有的话)或 null

string yourValueToPutIntoDatabase = (string.IsNullOrEmpty(yourTextBox.Text)) ? yourTextBox.Text : null;

如果你更舒服,你也可以在 if 语句中使用它:

string valueToPutInDatabase;
if(string.IsNullOrEmpty(yourTextBox.Text))
{
 //Your textbox was empty
 valueToPutInDatabase = null;
}
else
{
 valueToPutInDatabase = yourTextBox.Text;
}

试试这个..

【讨论】:

    【解决方案3】:

    试试这个

    if(txtPName.Text==""){
    u.FirstName =null;
    }
    if(txtPFamily.Text==""){
    u.LastName =null;
    }
    if(txtPUsername.Text==""){
    u.Username =null;
    }
    if(txtPPassword.Text==""){
    u.Password =null;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-10
      • 2014-09-10
      • 2019-04-29
      • 2017-09-25
      • 2011-05-05
      • 2019-04-29
      • 1970-01-01
      相关资源
      最近更新 更多