gpt4 book ai didi

c# - 从未绑定(bind)列中的 DataGridViewComboBoxCell 获取选定索引和选定项

转载 作者:太空宇宙 更新时间:2023-11-03 18:27:41 24 4
gpt4 key购买 nike

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

我尝试转换或关注此网站 ( http://satishjdotnet.blogspot.com/2009/05/getting-selected-value-of-combo-box-in.html ) 但我只收到错误:

"Value is not invalid"

.那么我该如何解决呢?请帮我。多谢。这是我在组合框中的自定义项目:

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);
}

最佳答案

给定 CustomItem 类,其值为 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;

//...
}
}

关于c# - 从未绑定(bind)列中的 DataGridViewComboBoxCell 获取选定索引和选定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30282818/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com