How to find out which Columns are nullable in a Da

2019-07-27 01:12发布

问题:

Is there a way to find out which columns are nullable in a DataTable? I know that there is a proprety: DataColumn.AllowDBNull, which can be set to true or false in the design mode of the DataSet, but I would like to have this information directly from the database.

I am having a DGV populated with values from a MySQL database and have bound the DataSource of the DGV to a DataTable.

回答1:

As a solution I decided to retrieve the Columns Schema of the Database and from there assign which Collumns AllowDBNull:

     DataTable dbColumnsSchema;
     using (MySqlConnection connection = new MySqlConnection(ConnectionString))
        {
            connection.Open();
        dbColumnsSchema = connection.GetSchema("Columns");
            connection.Close();

        }

        AssignMandatoryColumns(dbColumnsSchema);

    }

    private void AssignMandatoryColumns(DataTable table)
    {
      foreach (DataRow row in table.Rows)
            if (row["TABLE_NAME"].ToString()==myTableName)
                if(row["IS_NULLABLE"].ToString()=="NO")
                {  string columnName = row["COLUMN_NAME"].ToString();
                    myDataSet.Tables[myTableName].Columns[columnName].
                        AllowDBNull = false;
                }
    }


回答2:

You can use the following to determine which DataColumns in a DataTable are nullable (have AllowDBNull set to true):

var nullableDataColumns = dataTable.Columns.Cast<DataColumn>().Where(c => c.AllowDBNull);
foreach (var col in nullableDataColumns) {
    Console.WriteLine(col.ColumnName);
}