gpt4 book ai didi

c# - 在从 DataTable 填充的组合框中选择一个值

转载 作者:行者123 更新时间:2023-11-30 14:40:21 24 4
gpt4 key购买 nike

我有一个由 DataTable 填充的组合框,如下所示。我希望能够设置显示哪个项目。要设置的值是将在“Id”列中找到的字符串。

public DataTable list = new DataTable();
public ComboBox cbRates = new ComboBox();

//prepare rates combo data source
this.list.Columns.Add(new DataColumn("Display", typeof(string)));
this.list.Columns.Add(new DataColumn("Id", typeof(string)));

//populate the rates combo
int counter = 0;

foreach (string item in dropdownItems)
{
this.list.Rows.Add(list.NewRow());
if (counter == 0)
{
this.list.Rows[counter][0] = "Select Rate..";
this.list.Rows[counter][1] = "";
}
else
{
string[] itemSplit = item.Split('`');
if (itemSplit.Length == 2)
{
this.list.Rows[counter]["Display"] = itemSplit[0];
this.list.Rows[counter]["Id"] = itemSplit[1];
}
else
{
this.list.Rows[counter]["Display"] = item;
this.list.Rows[counter]["Id"] = item;
}
}
counter++;
}
this.cbRates.DataSource = list;
this.cbRates.DisplayMember = "Display";
this.cbRates.ValueMember = "Id";

//now.. how to set the selected value?

int rowCount = 0;
foreach (DataRow cbrow in this.list.Rows)
{
if (DB.GetString(cbrow["Id"]) == answerSplit[1])
{
//attempting to set the SelectedIndex throws an exception
//on another combobox populated NOT from a DataTable - this does work fine.
this.cbRates.SelectedIndex = rowCount;
}
rowCount++;
}

//this doesn't seem to do anything.
foreach (DataRow dr in this.list.Rows)
{
if ((string)dr["Id"] == answerSplit[1]) this.cbRates.SelectedItem = dr;
}

//nor this
foreach(DataRow dr in this.cbRates.Items)
{
try
{
if ((string)dr["Id"] == answerSplit[1]) this.cbRates.SelectedItem = dr;
}
catch
{
MessageBox.Show("Ooops");
}
}

如果 FindExactString、FindString、FindByValue 不存在于紧凑的框架中,我就没有什么可以尝试的了。

如果尝试使用

this.cbRates.SelectedIndex = 2;

我收到以下错误;

System.Exception: Exception
at Microsoft.AGL.Common.MISC.HandleAr(PAL_ERROR ar)
at System.Windows.Forms.ComboBox.set_SelectedIndex(Int32 value)

但是,如果我出于测试目的将相关代码放入它自己的表单中,我可以正确设置 selectedIndex。

我认为这些问题是相互关联的。

最佳答案

你知道你可以直接使用数据表作为数据源吗?

        cbo.DataSource = table;
cbo.DisplayMember = "Display";
cbo.ValueMember = "Id";

关于c# - 在从 DataTable 填充的组合框中选择一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5403943/

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