Search code examples
c#asp.netuser-controlstypes

Assign Null value to the Integer Column in the DataTable


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?


Solution

  • 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);