为什么从DataColumn's
更改DataType
typeof(Object) -> typeof(MessageBoxButtons)
会更改diplay行为?
注意:如果列以typeof(MessageBoxButtons)
开头,则枚举显示为变量名称(不是整数)。
如果DataGridView
添加了Object列,但DataColumn's
DataType
更改为特定枚举,则添加行时,值显示为整数值
另外,如果DataColumn
以Type
MessageBoxButtons
开头,然后切换到typeof(Object)
,枚举仍会显示为变量名称,因此切换不是问题。< / p>
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 });
}
}
}