繁体   English   中英

带有DataTableSource的DataGridView ComboBox列

[英]DataGridView ComboBox Column with DataTableSource

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

我有一个DataTable对象绑定到我的DataGridView。 表格的一列,下面示例中的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元素列具有“Col_4”标题?
  2. 如何使选定的ComboBox值正确存储在DataTable中?

这可能很简单,但我是C#的新手,我真的很困惑。

为你的第一个问题而已

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

暂无
暂无

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

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