如何找出DataTable中可列出哪些列? [英] How to find out which Columns are nullable in a DataTable?

查看:141
本文介绍了如何找出DataTable中可列出哪些列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法找出哪些列在DataTable中是可空的?
我知道有一个proprety:DataColumn.AllowDBNull,可以在DataSet的设计模式中设置为true或false,但是我想直接从数据库中获取这些信息。

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.

我有一个DGV填充了MySQL数据库中的值,并将DGV的DataSource绑定到一个DataTable。

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

推荐答案

作为解决方案,我决定检索数据库的列模式,并从中指定哪个Collumn的AllowDBNull:

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

这篇关于如何找出DataTable中可列出哪些列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆