C# 用DataGridView(Winforms)的组合框替换数据表中的int列

C# 用DataGridView(Winforms)的组合框替换数据表中的int列,c#,winforms,datagridview,C#,Winforms,Datagridview,我有一个带有一些整数值的数据表(假设0=>'open',1=>'progressing',2=>'free'等),在dgv中,我希望允许用户更改该值,但使用组合框和字符串值。所以我创建了一个简单的winform应用程序来测试它 public Form1() { InitializeComponent(); DataTable dt = new DataTable(); dt.Columns.Add("test"

我有一个带有一些整数值的数据表(假设0=>'open',1=>'progressing',2=>'free'等),在dgv中,我希望允许用户更改该值,但使用组合框和字符串值。所以我创建了一个简单的winform应用程序来测试它

    public Form1()
    {
        InitializeComponent();

        DataTable dt = new DataTable();
        dt.Columns.Add("test");
        dt.Rows.Add(1);
        dt.Rows.Add(2);

        DataTable source = new DataTable();
        source.Columns.AddRange(new DataColumn[] { new DataColumn("Value", typeof(int)), new DataColumn("Display", typeof(string)) });
        source.Rows.Add(0, "zero");
        source.Rows.Add(1, "one");
        source.Rows.Add(2, "two");

        dataGridView1.DataSource = dt;

        var testTextColumn = new DataGridViewComboBoxColumn();
        testTextColumn.HeaderText = "Text";
        testTextColumn.Name = "testText";
        testTextColumn.DataSource = source;
        testTextColumn.DisplayMember = "Display";
        testTextColumn.ValueMember = "Value";
        dataGridView1.Columns.Add(testTextColumn);
    }
到目前为止还不错,我认为我可以简单地让测试列不可见,只让testText列可见(在最终的应用程序中),但是如何组合to值,即当我在cb中更改某些内容时,更新datatable的值?我可以通过改变事件来做到这一点,但这似乎不切实际。有某种数据绑定吗


创建单元格更改事件,然后获取您更改的行数,您可以使用索引访问列

   private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
            {
                if (dataGridView1.CurrentRow != null)
                {
                    DataGridViewRow dgvRow = dataGridView1.CurrentRow;
                  // do what u want here like 
int teste = Convert.ToInt32(dgvRow.Cells[1].Value);
    }
    }
您发布的代码中有三(3)件事情错误,无法实现您所描述的内容

1-代码行

dt.Columns.Add("test");
…默认为
字符串
值。因此,当您尝试从
source
表绑定“Value”列时,组合框将抛出一个
DataError
。因此,您需要在数据中指定
int
type列。像

dt.Columns.Add("test", typeof(int));
2-在代码设置网格
DataSource
之前,代码需要指定我们不希望网格
AutoGenerateColumns
。否则,我们将以两列结束。此外,此网格属性不是“设计器”中显示的属性。您需要在添加数据源之前设置此属性,并且需要在代码中设置此属性。类似于

dataGridView1.AutoGenerateColumns = false;
3-当代码创建组合框列时,它从不标识网格
DataSource
中要将组合框列绑定到的“哪个”列。这就是列
DataPropertyName
的目的。因此,您需要在组合框定义中添加这行代码

testTextColumn.DataPropertyName = "test";

进行这些更改时,应该只显示组合框列。

对于组合框列,您几乎总是需要进行转换-将用户看到/选择的内容转换为您想要保存的内容。例如,将cbo中的
Stooges.Moe
转换为
1
,以便存储在数据库中。这部分来自cbo中使用的类型或数据,还有用于提供映射的
ValueMember
DisplayMember
属性。也可能有用:谢谢你,我问你是否有一种不用事件处理就能解决这个问题的方法完美!!这正是我要找的。