Search code examples
c#sqldatatabledatacolumn

C# - How to tell if DataColumn supports nulls?


I have a datatable that comes from an SQL request. While I am really working against a table using OLEDB, even if I get the table from my SQL server, I have the same problem.

If I fill 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 otherwise.

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 can't seem to figure out where to get the length of a string field.

This makes it a little difficult to implement some simple client side error checking before I try to upload data.

If I were only dealing with SQL server based tables, I could use Microsoft.SqlServer.Management.Sdk and Microsoft.SqlServer.Management.Smo. Since I am not, that's out.


Solution

  • Try

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

    See if that gives you the level of schema detail you need.