【问题标题】:How to find the DataBase type of a bound DataGridView column如何查找绑定的 DataGridView 列的数据库类型
【发布时间】:2014-06-16 21:59:18
【问题描述】:

我需要知道 DataGridView 中每一列的原始类型。

它与动态 SQL 选择绑定,例如 "SELECT * FROM artists;"

我想在网格上方添加数据的表单视图,并以编程方式创建标签和文本框,然后创建一些来保存字段。我将它们添加到 FlowLayoutPanel,但我想调整大小,尤其是多行属性和高度,以适应 200-500 个字符的长注释和描述字段。

我在查看文本列时发现的只是数据类型string

我知道我可以通过查询 systables 来查找列,但最好能找到比这更接近一点的原始数据类型;我也在使用 MYSQL atm,并且不需要查询数据库的解决方案也有望独立于 DBMS。

编辑 1

我在 DGV 中装满了没有什么花哨的东西:

DBDA = new MySqlDataAdapter(sql, DBC);
MySqlCommandBuilder cb = new MySqlCommandBuilder(DBDA);
DBDS = new DataSet(ddlb_tables.Text);
DBDA.FillSchema(DBDS, SchemaType.Mapped);  //<- This was the missing piece of code!!
DBDA.Fill(DBDS, ddlb_tables.Text);
dataGridView1.DataSource = DBDS;
dataGridView1.DataMember = ddlb_tables.Text;

编辑 2

在接受的答案 (DBDA.MissingSchemaAction) 的帮助下,我可以解决我的问题。这是第一个原始版本的结果函数:

public int getColumnSize(DataGridViewColumn dc)
{
  try
  {
    DataGridView DGV = dc.DataGridView;
    DataSet DS = (DataSet)DGV.DataSource;
    DataTable DT = DS.Tables[0];
    DataColumn DC = DT.Columns[dc.Name];
    return DC.MaxLength;
  } catch { }
  return -1;
}

没有得到原始类型不是问题,只要我知道字段的长度即可。

【问题讨论】:

  • 如何填写DataGridView
  • @lomed 查看已编辑的问题!

标签: c# sql winforms datagridview sqldatatypes


【解决方案1】:

使用 DataSet 代替 DataGrid:

foreach (DataColumn col in DBDS[ddlb_tables.Text].Text.Columns)
{
    if (col.DataType == typeof(string))
    {
        var len = col.MaxLenght;
        ...
    }
}

编辑:

您可能需要在填写之前添加以下行:

   DBDA.MissingSchemaAction = MissingSchemaAction.AddWithKey;

来源:The DataAdapter.Fill method does not set all of the properties of the DataTable and DataColumn objects

编辑 2:

或者对于没有键的结果集:

   DBDA.FillSchema(DBDS, SchemaType.Source);

或者:

   DBDA.FillSchema(DBDS, SchemaType.Mapped);

【讨论】:

  • 这对我有什么帮助?我需要知道列的最大长度。我已经使用调试器深入研究了 DataTable,但所有 varchar 等数据类型都已映射到字符串。
  • 你填写后检查?您确定数据库限制了列的长度吗? MSDN:If the column has no maximum length, the value is -1 (default).
  • 是的,是的。我在填充了所有 2223 行后检查了所有 varchar 和 char 列在 MYSQL 中的 CHARACTER_MAXIMUM_LENGTH 设置为各自的大小。 (这会自动发生。)
  • 只要结果集有一个键就可以工作,但是对于例如无钥匙view 它崩溃了。我冒昧地添加了一个替代但安全的解决方案,以便接受的答案包含所需的所有信息,好吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-17
  • 2011-11-23
  • 2018-03-29
  • 1970-01-01
  • 2016-11-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多