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?
When
null
is not allowed to be inserted intoDR["CustomerID"]
, you could use(int?)null
instead like this:You can use DBNull.
But you should check also that the value is a valid integer:
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:
I hope that helps
you could do it like that:
You need to check first