How to find out which Columns are nullable in a DataTable?

懵懂的女人 提交于 2019-12-11 07:08:25

问题


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);
}


来源:https://stackoverflow.com/questions/12711971/how-to-find-out-which-columns-are-nullable-in-a-datatable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!