Datagridview cell.value = DatagridviewComboboxCell.value

时间:2016-10-06 21:24:22

标签: c# datagridview

我希望看到我在其他单元格中的组合框中看到的任何内容仅针对当前行我尝试这样的事情而没有结果:

dataGridView1.Rows[0].Cells[0].Value = 
   dataGridView1.Rows[0].Cells[1].Value;\\ cell  1 is my comboboxcell 

1 个答案:

答案 0 :(得分:0)

我有一个以Item命名的类,用于在List中添加项目,

项目类;

public class Item
        {
            public string Name { get; set; }
            public int Id { get; set; }
        }

在Form_Load中,我加载了datagridview,

private void Form1_Load(object sender, EventArgs e)
        {
            dataGridView1.Columns.Add("test1", "test1");
            DataGridViewComboBoxColumn testCol = new DataGridViewComboBoxColumn();
            testCol.HeaderText = "comboValues";
            dataGridView1.Columns.Add(testCol);
            dataGridView1.Columns.Add("test2", "test1");
            List<Item> items = new List<Item>();
            items.Add(new Item() { Name = "One", Id = 1 });
            items.Add(new Item() { Name = "Two", Id = 2 }); // created two Items 
            var cbo = dataGridView1.Columns[1] as DataGridViewComboBoxColumn; // index of 1 is the comboboxColumn
            cbo.DataSource = items; // setting datasource 
            cbo.ValueMember = "Id";
            cbo.DisplayMember = "Name";
            dataGridView1.Rows.Add("", items[1].Id, "test1");
            dataGridView1.Rows.Add("", items[0].Id, "test2");
            dataGridView1.Rows.Add("", items[1].Id, "test3"); // and test rows
        }

我们需要在新选择之前检查哪一行是前一行,因此我们需要使用Row_Leave事件。

int previousRowIndex = 0; // a variable to keep the index of row
        private void dataGridView1_RowLeave(object sender, DataGridViewCellEventArgs e)
        {
            previousRowIndex = e.RowIndex;
        }

主要事件是SelectionChanged,

private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            dataGridView1.Rows[previousRowIndex].Cells[0].Value = ""; // first set the previous row's first cell value empty string.
            DataGridViewComboBoxCell comboCell = dataGridView1.CurrentRow.Cells[1] as DataGridViewComboBoxCell; 
            dataGridView1.CurrentRow.Cells[0].Value = comboCell.EditedFormattedValue; // then set the first cell's value as the combobox's selected value.
        }

<强>结果;

dgv row selection

希望有所帮助,