从未绑定列的DataGridViewComboBoxCell中获取选定索引和选定项

本文关键字:索引 获取 绑定 DataGridViewComboBoxCell | 更新日期: 2023-09-27 17:49:22

我有一个很大的问题,让我如此困惑,我有一个DataGridView没有使用绑定有DataGridViewComboBoxColumn(未绑定列),我想在ComBoBoxCell(我的项目I自定义项目)中获得选定的索引或选定的项目。

我尝试cast或遵循这个网站(http://satishjdotnet.blogspot.com/2009/05/getting-selected-value-of-combo-box-in.html),但我只收到错误:

"值不是无效的"

。怎么解呢?请帮帮我。非常感谢。这是我的自定义项目在组合框:

public class CustomItem {
    public string Text { get; set; }
    public object Value { get; set; }
    public override string ToString() {
        return Text;
    }
    public CustomItem(string text, object value) {
        this.Text = text;
        this.Value = value;
    }
}

以及如何将其添加到DataGridViewComboBoxColumn:

List<CustomItem> teamItem = new List<CustomItem>();
teamItem.Add(new CustomItem(this._homeTeam["Name"].ToString(), Convert.ToInt32(this._homeTeam["Id"])));
teamItem.Add(new CustomItem(this._awayTeam["Name"].ToString(), Convert.ToInt32(this._awayTeam["Id"])));
foreach (CustomItem i in teamItem) {
    ((DataGridViewComboBoxColumn)this.dataGridViewGoalInformation.Columns["Team"]).Items.Add(i);
}

从未绑定列的DataGridViewComboBoxCell中获取选定索引和选定项

给定CustomItem类,Value为int

 public class CustomItem
 {
    public string Text { get; set; }
    public int Value { get; set; }
    public override string ToString()
    {
        return Text;
    }
    public CustomItem(string text, int value)
    {
        this.Text = text;
        this.Value = value;
    }
}

要获取该值,请确保连接事件:editingcontrolshowing

dataGridView1.EditingControlShowing += dataGridView1_EditingControlShowing;

当组合框的值发生变化时,获取它的值:1)获取组合框控件,2)获取它的选定值:

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    if (dataGridView1.CurrentCell.ColumnIndex == 0 && e.Control is ComboBox)
    {
        ComboBox comboBox = e.Control as ComboBox;
        comboBox.SelectedIndexChanged += ComboBox_SelectedIndexChanged;
    }
}
private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    DataGridViewComboBoxEditingControl dataGridViewComboBoxEditingControl = sender as DataGridViewComboBoxEditingControl;
    object value = dataGridViewComboBoxEditingControl.SelectedValue;
    if (value != null)
    {
        int intValue = (int)dataGridViewComboBoxEditingControl.SelectedValue;
        //...
    }
}