Assign Null value to the Integer Column in the DataTable

后端 未结 11 1055
旧巷少年郎
旧巷少年郎 2021-02-12 13:17

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:

相关标签:
11条回答
  • 2021-02-12 14:01
    Int32 Temp = 0;
    if !(Int32.TryParse(TextBox1.Text,Temp))
        DR["CustomerID"] = DBNull.Value
    else
        DR["CustomerID"] = Temp
    
    0 讨论(0)
  • 2021-02-12 14:03

    You can use DBNull.

    DR["CustomerID"] = (TextBox.Text.Length == 0) ? Convert.ToInt32(TextBox1.Text) : DBNull.Value;
    
    0 讨论(0)
  • 2021-02-12 14:03

    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

    0 讨论(0)
  • 2021-02-12 14:05

    You need to check first

    if (TextBox1.Text.Length > 0)
    {
       DR["CustomerID"] = Convert.ToInt32(TextBox1.Text); 
    }
    else
    {
      DR["CustomerID"] = null;  
    }
    
    0 讨论(0)
  • 2021-02-12 14:08

    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);
    
    0 讨论(0)
提交回复
热议问题