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:23
 if (TextBox1.Text.Trim() == String.Empty)
    {
        DR["CustomerID"] = null;
    }
    else
    {
        DR["CustomerID"] = Convert.ToInt32(TextBox1.Text);
    }
查看更多
SAY GOODBYE
3楼-- · 2020-06-07 08:26
Int32 Temp = 0;
if !(Int32.TryParse(TextBox1.Text,Temp))
    DR["CustomerID"] = DBNull.Value
else
    DR["CustomerID"] = Temp
查看更多
爷、活的狠高调
4楼-- · 2020-06-07 08:28

A null/empty string is in the wrong format; you would need to detect that scenario and compensate:

    DR["CustomerID"] = string.IsNullOrWhiteSpace(text)
        ? DBNull.Value : (object)Convert.ToInt32(text);
查看更多
疯言疯语
5楼-- · 2020-06-07 08:33

First of all, of course, the field needs to be set as nullable in the DB.

And then, set it to DBNull.Value

查看更多
男人必须洒脱
6楼-- · 2020-06-07 08:36
DataTable dt = new DataTable();
DataRow DR = dt.NewRow();

if (String.IsNullOrEmpty(TextBox1.Text))
    DR["CustomerID"] = DBNull.Value;
else
    DR["CustomerID"] = Convert.ToInt32(TextBox1.Text);
查看更多
登录 后发表回答