C # - How to determine if a DataColumn supports null values?

I have a datatable that comes from an SQL query. Although I actually work against the table using OLEDB, even if I get the table from my SQL server, I have the same problem.

If I populate the datatable and then query the DataColumns - they all say AllowDBNull == true and allowNull == true. But if I look at the table in SSMS, it states differently.

string selectStmt= "Select  * from foobar; "
DataSet NewData = new DataSet();
using (SqlConnection DataConn = new SqlConnection(MyConnectionString))
{   
    SqlDataAdapter DataAdapter = new SqlDataAdapter(selectStmt, DataConn );
    var Results = DataAdapter.Fill(NewData, tableName);
}
DataColumn Col = NewData.Tables[0].Columns[0];
// Col.AllowDBNull is always true as is Col.AllowNull

I also cannot figure out where to get the length of the row field.

This makes it difficult to implement some simple client-side validation before I try to load the data.

If I were only dealing with tables on an SQL server, I could use Microsoft.SqlServer.Management.Sdk and Microsoft.SqlServer.Management.Smo. Since I do not do this.

+4
2

Try

var Results = DataAdapter.FillSchema(NewData, SchemaType.Source, tableName);

, , .

+2

ResultSet , , , , , / . - EF . , , - ( ).

DbNull, :

if ( dataRow[colNameOrIndex].Value == DbNull.Value){
    //null
}
+1

All Articles