【问题标题】:DataGridView ComboBox Column with DataTableSource带有 DataTableSource 的 DataGridView 组合框列
【发布时间】:2014-08-15 20:00:45
【问题描述】:

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

我有一个绑定到我的 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 元素的列具有“Col_4”标题?
  2. 如何使选定的 ComboBox 值正确存储在 DataTable 中?

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

【问题讨论】:

    标签: c# datagridview combobox datatable


    【解决方案1】:

    你的第一个问题只是

    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
    

    【讨论】:

    • 感谢您的关注,我已对您的问题投票。如果你愿意,请投票给我的答案。
    猜你喜欢
    • 1970-01-01
    • 2013-09-10
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-27
    相关资源
    最近更新 更多