How do I check if a specified column allows null values or not?
I’m using the following code to print all the columns, but I also want to print if the column allows null values:
cnn = new SqlConnection(connetionString);
cnn.Open();
SqlCommand myCommand = new SqlCommand("select * from " + tableName, cnn);
SqlDataAdapter da = new SqlDataAdapter(myCommand);
DataSet ds = new DataSet();
da.Fill(ds, tableName);
foreach (DataColumn dc in ds.Tables[0].Columns)
{
// Print stuff here, dc.ColumnName is the column name
}
The DataColumn.allowDBnull property doesn’t seem to work when getting a predefined table, it’s always set to true, even in columns that doesn’t allow nulls.
Thanks for your time!
If you are only after column data I would do this from the system views, rather than relying on the data adapter. e.g.
This also means you can use parameterised queries properly and avoid the risks of SQL Injection. So your final code would be something like this: