C# 更改数据类型时DataGridView枚举ToString行为
为什么从C# 更改数据类型时DataGridView枚举ToString行为,c#,winforms,datagridview,datatable,enums,C#,Winforms,Datagridview,Datatable,Enums,为什么从typeof(Object)->typeof(MessageBoxButtons)更改DataColumn的DataType会改变diplay行为? 注意:如果列以typeof(MessageBoxButtons)开头,则枚举显示为变量名(而不是整数) 如果使用对象列添加了DataGridView,但是DataColumn的数据类型更改为特定枚举,则添加行时,值显示为整数值 此外,如果DataColumn以TypeMessageBoxButtons开头,则切换到typeof(Object
typeof(Object)->typeof(MessageBoxButtons)
更改DataColumn的
DataType
会改变diplay行为?
注意:如果列以typeof(MessageBoxButtons)
开头,则枚举显示为变量名(而不是整数)
如果使用对象列添加了DataGridView
,但是DataColumn的
数据类型
更改为特定枚举,则添加行时,值显示为整数值
此外,如果DataColumn
以Type
MessageBoxButtons
开头,则切换到typeof(Object)
枚举仍显示为变量名,因此切换不是问题
public class DataForm : Form {
Button btnAdd1 = new Button { Text = "Add DGV with Enum Column", Dock = DockStyle.Bottom };
Button btnAdd2 = new Button { Text = "Add DGV with Object Column", Dock = DockStyle.Bottom };
Button btnToggle = new Button { Text = "Toggle Column Data Type", Dock = DockStyle.Bottom, Enabled = false };
Button btnAddRows = new Button { Text = "Add Rows", Dock = DockStyle.Bottom, Enabled = false };
public DataForm() {
Controls.Add(btnAdd1);
Controls.Add(btnAdd2);
Controls.Add(btnToggle);
Controls.Add(btnAddRows);
foreach (Button b in new [] { btnAdd1, btnAdd2, btnToggle, btnAddRows })
b.Click += b_Click;
}
DataGridView dgv = null;
private void DisposeDGV() {
if (dgv != null) {
dgv.Parent.Controls.Remove(dgv);
dgv.Dispose();
}
}
void b_Click(object sender, EventArgs e) {
if (sender == btnAdd1) {
DisposeDGV();
dgv = new DataGridView { Dock = DockStyle.Fill };
DataTable table = new DataTable();
table.Columns.Add("Enum", typeof(MessageBoxButtons));
dgv.DataSource = table;
Controls.Add(dgv);
btnToggle.Enabled = true;
btnAddRows.Enabled = true;
}
else if (sender == btnAdd2) {
DisposeDGV();
dgv = new DataGridView { Dock = DockStyle.Fill };
DataTable table = new DataTable();
table.Columns.Add("Object", typeof(Object));
dgv.DataSource = table;
Controls.Add(dgv);
btnToggle.Enabled = true;
btnAddRows.Enabled = true;
}
else if (sender == btnToggle) {
DataTable table = (DataTable) dgv.DataSource;
DataColumn col = table.Columns[0];
Type ty = col.DataType;
if (ty == typeof(Object))
col.DataType = typeof(MessageBoxButtons);
else
col.DataType = typeof(Object);
}
else if (sender == btnAddRows) {
btnToggle.Enabled = false;
DataTable table = (DataTable) dgv.DataSource;
foreach (var o in Enum.GetValues(typeof(MessageBoxButtons)))
table.Rows.Add(new Object[] { o });
}
}
}