带有DataTableSource的DataGridView ComboBox列

时间:2014-08-15 20:00:46

标签: c# datagridview combobox datatable

我一直试图解决这个问题大约一天,但没有运气。希望有人可以提供帮助。

我有一个绑定到DataGridView的DataTable对象。表格的一列,下面示例中的Col_4需要保存来自枚举类型的值。在这种情况下,我使用了颜色。我需要表格的Col_4是一个ComboBox元素列,允许我选择所需的颜色。然后,颜色选择将存储在绑定到DataGridView的DataTable中。

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        enum MyColors {Red, Green, Blue, Yellow, Orange, White};
        List<MyColors> colors = Enum.GetValues(typeof(MyColors)).Cast<MyColors>().ToList();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {                      
            DataTable table = new DataTable("theData");
            table.Columns.Add("Col_1");
            table.Columns.Add("Col_2");
            table.Columns.Add("Col_3");
            table.Columns.Add("Col_4");

            DataGridViewComboBoxColumn comboCol = new DataGridViewComboBoxColumn();
            comboCol.ValueType = typeof(MyColors);
            comboCol.DataSource = colors;
            comboCol.DataPropertyName = "Col_4";

            DataRow row = table.NewRow();
            row["Col_1"] = 1;
            row["Col_2"] = 2;
            row["Col_3"] = 3;
            row["Col_4"] = 4;

            table.Rows.Add(row);

            dataGridView1.DataSource = table;
            dataGridView1.Columns.Add(comboCol);
            dataGridView1.AllowUserToAddRows = false;

            Console.WriteLine(dataGridView1.Rows[0].State.ToString());
        }

    }
}

我遇到两个问题:

  1. 如何让ComboBox元素列具有&#34; Col_4&#34;头?
  2. 如何使选定的ComboBox值正确存储在DataTable中?
  3. 这可能很简单,但我是C#的新手,我真的很困惑。

1 个答案:

答案 0 :(得分:0)

仅针对您的第一个问题

comboCol.Header="Test";
comboCol.ValueMember="ColorId"; //that color id is the value of color class to be sorted in database 

使用以下代码解决第二个问题:

BindingSource bs=new BindingSource();
bs.DataSource=table;
datagridview1.DataSource=bs;

以及何时想要在db

中保存数据
int columnvalueColorId=Convert.ToInt32((bs.current as DataRowView).Row["Col_4"].ToString());//if colum