How to find out which Columns are nullable in a Da

2019-07-27 01:01发布

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.

2条回答
何必那么认真
2楼-- · 2019-07-27 01:40

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);
}
查看更多
smile是对你的礼貌
3楼-- · 2019-07-27 01:41

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;
                }
    }
查看更多
登录 后发表回答