更改DataType时DataGridView枚举ToString行为

时间:2015-10-24 02:42:57

标签: c# winforms datagridview datatable enums

为什么从DataColumn's更改DataType typeof(Object) -> typeof(MessageBoxButtons)会更改diplay行为? 注意:如果列以typeof(MessageBoxButtons)开头,则枚举显示为变量名称(不是整数)。

如果DataGridView添加了Object列,但DataColumn's DataType更改为特定枚举,则添加行时,值显示为整数值

另外,如果DataColumnType 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 });
        }
    }
}

0 个答案:

没有答案