Assign Null value to the Integer Column in the DataTable

后端 未结 11 1037
旧巷少年郎
旧巷少年郎 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 13:47

    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);
    
    0 讨论(0)
  • 2021-02-12 13:49
     if (TextBox1.Text.Trim() == String.Empty)
        {
            DR["CustomerID"] = null;
        }
        else
        {
            DR["CustomerID"] = Convert.ToInt32(TextBox1.Text);
        }
    
    0 讨论(0)
  • 2021-02-12 13:50

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

    And then, set it to DBNull.Value

    0 讨论(0)
  • 2021-02-12 13:51
    DataTable dt = new DataTable();
    DataRow DR = dt.NewRow();
    
    if (String.IsNullOrEmpty(TextBox1.Text))
        DR["CustomerID"] = DBNull.Value;
    else
        DR["CustomerID"] = Convert.ToInt32(TextBox1.Text);
    
    0 讨论(0)
  • 2021-02-12 13:53
    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;
    }
    
    0 讨论(0)
  • 2021-02-12 13:55

    you could do it like that:

    DR["CustomerID"] = string.IsNullOrEmpty(TextBox1.Text) ?
        null : Convert.ToInt32(TextBox1.Text);
    
    0 讨论(0)
提交回复
热议问题