如何获取datagridview组合框列的选定值?

时间:2018-08-18 12:19:52

标签: c# datagridview

我有一个带有图像标签列表和保存按钮的combox。在保存按钮上,我需要在保存按钮上获取combox选定的值(如果为空,然后验证)。我该怎么做?

enter image description here

这是我在datagridview中添加combox的方法:

string[] ImageLabels = {Photograph, PassportPage1, PassportPage2, 
PassportPage3, PassportPage4};
var list=new ArrayList();
var combo = new DataGridViewComboBoxColumn();
combo.HeaderText = "Image Labels";
combo.Name = "combo";
list = new ArrayList();
list.AddRange(ImageLabels);
combo.Items.AddRange(list.ToArray());
dgvFiles.Columns.Add(combo);

我得到空值。

enter image description here

1 个答案:

答案 0 :(得分:0)

为您的datagridview

添加以下事件

这里的datagridview名称为dataGridView1

private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
    dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    string comboboxSelectedValue = string.Empty;

    if (dataGridView1.Columns[e.ColumnIndex].GetType() == typeof(DataGridViewComboBoxColumn))
        comboboxSelectedValue = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
}

1)dataGridView1_CurrentCellDirtyStateChanged::从dataGridView1_CellValueChanged中选择值后,此事件将立即触发您的DataGridViewComboBoxColumn

2)dataGridView1_CellValueChanged:此事件将为您提供combobx中所选选项的值,我们另外检查了该值是否来自DataGridViewComboBoxColumn

您可以在Form1_Load上添加上述事件,例如

private void Form1_Load(object sender, EventArgs e)
{
    dataGridView1.CellValueChanged +=
             new DataGridViewCellEventHandler(dataGridView1_CellValueChanged);
    dataGridView1.CurrentCellDirtyStateChanged +=
                 new EventHandler(dataGridView1_CurrentCellDirtyStateChanged);
}

输出:

enter image description here