Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign Null value to the Integer Column in the DataTable

Tags:

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?

like image 377
thevan Avatar asked Jun 15 '11 12:06

thevan


2 Answers

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);
like image 101
Marc Gravell Avatar answered Oct 21 '22 17:10

Marc Gravell


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;
}
like image 20
manji Avatar answered Oct 21 '22 16:10

manji