简体   繁体   English

列 c# winform 上具有 1 种以上类型数据的数据表

[英]Datatable with more than 1 type of data on a column c# winform

I`m trying to dynamically generate a table based on a treeview node i click.我正在尝试基于单击的 treeview 节点动态生成表。 I want it to look like this [2 rows of a table where on the 2nd row i can use either bool or int][1]我希望它看起来像这样[表格的 2 行,在第 2 行我可以使用 bool 或 int][1]

if (ModelIerarhic.SelectedNode.Text == "1")
{
  DataTable dtdiag = new DataTable();
  dtdiag.Columns.Add("Config Options", typeof(string));
  dtdiag.Columns.Add(e.Node.Parent.Name, typeof(bool | string)); //this is where i need to change so the below lines will work
  dtdiag.Rows.Add(new object[] { "a", "abc" });
  dtdiag.Rows.Add(new object[] { "a", true });
  dataGridView1.DataSource = dtdiag;
}

from what i read i cannot change the datatable column type after i put one value in a row.根据我读到的内容,在我将一个值放入一行后,我无法更改数据表列类型。 [1]: https://i.stack.imgur.com/Z1uFo.png [1]: https://i.stack.imgur.com/Z1uFo.png

All cells of a column need to have the same data type.一列的所有单元格都需要具有相同的数据类型。 You can declare the column to be of type object .您可以将列声明为object类型。 This is the base type that all .NET types share:这是所有 .NET 类型共享的基本类型:

dtdiag.Columns.Add(e.Node.Parent.Name, typeof(object));

Be aware, that this is a very loose declaration;请注意,这是一个非常松散的声明; you can put any data, not only strings and boolean values into this column.您可以将任何数据(不仅是字符串和 boolean 值)放入此列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM