简体   繁体   English

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

[英]How to get selected value of datagridview combobox column?

I have a combox with list of image labels and a save button. 我有一个带有图像标签列表和保存按钮的combox。 On the save button I need to get the combox selected value on the save button if it is null then validate. 在保存按钮上,我需要在保存按钮上获取combox选定的值(如果为空,然后验证)。 How I can do this? 我该怎么做?

enter image description here 在此处输入图片说明

This is how I add combox in datagridview: 这是我在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);

I am getting null values. 我得到空值。

enter image description here 在此处输入图片说明

Add the below event for your datagridview 为您的datagridview添加以下事件

Here my datagridview name is dataGridView1 这里我的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: This event will fire your dataGridView1_CellValueChanged immediately after you select value from your DataGridViewComboBoxColumn . 1)dataGridView1_CurrentCellDirtyStateChanged:DataGridViewComboBoxColumn选择值后,此事件将立即触发dataGridView1_CellValueChanged

2) dataGridView1_CellValueChanged: This event will give you the value of your selected option in combobx, we additionally checked that is this the values comes from DataGridViewComboBoxColumn or not. 2)dataGridView1_CellValueChanged:此事件将为您提供combobx中所选选项的值,我们另外检查了该值是否来自DataGridViewComboBoxColumn

You may add above events on Form1_Load like 您可以在Form1_Load上添加上述事件,例如

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

Output: 输出:

在此处输入图片说明

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

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