Assign Null value to the Integer Column in the Dat

2020-06-07 07:32发布

I have a datatable with One ColumnName "CustomerID" with Integer DataType. Dynamically I want to add rows to the DataTable. For that, I had created one DataRow object like:

  DataTable dt = new DataTable();
  DataRow DR = dt.NewRow();
  DR["CustomerID"] = Convert.ToInt32(TextBox1.Text);

But if the TextBox contains empty string, it throws the error. In that case, I want to assign Null value to the CustomerID. How to do this?

11条回答
乱世女痞
2楼-- · 2020-06-07 08:13

When null is not allowed to be inserted into DR["CustomerID"], you could use (int?)null instead like this:

DR["CustomerID"] = string.IsNullOrEmpty(TextBox1.Text) ?
(int?) null : Convert.ToInt32(TextBox1.Text);
查看更多
成全新的幸福
3楼-- · 2020-06-07 08:14

You can use DBNull.

DR["CustomerID"] = (TextBox.Text.Length == 0) ? Convert.ToInt32(TextBox1.Text) : DBNull.Value;
查看更多
放荡不羁爱自由
4楼-- · 2020-06-07 08:16
DR["CustomerID"] = !string.IsNullOrEmpty(TextBox1.Text)
                   ? Convert.ToInt32(TextBox1.Text)
                   : DBNull.Value;

But you should check also that the value is a valid integer:

int value;
if(int.TryParse(TextBox1.Text, out value))
{
    DR["CustomerID"] = value;
}
else
{
    DR["CustomerID"] = DBNull.Value;
}
查看更多
放荡不羁爱自由
5楼-- · 2020-06-07 08:19

If you declare the Integer variable as int? it is automatically boxed by the C# compiler and you are able to assign null to that variable. For example:

int? custID = null;

I hope that helps

查看更多
SAY GOODBYE
6楼-- · 2020-06-07 08:20

you could do it like that:

DR["CustomerID"] = string.IsNullOrEmpty(TextBox1.Text) ?
    null : Convert.ToInt32(TextBox1.Text);
查看更多
孤傲高冷的网名
7楼-- · 2020-06-07 08:22

You need to check first

if (TextBox1.Text.Length > 0)
{
   DR["CustomerID"] = Convert.ToInt32(TextBox1.Text); 
}
else
{
  DR["CustomerID"] = null;  
}
查看更多
登录 后发表回答