c# - 如何在 C# Windows 窗体中设置 ComboBox 的选定项?

标签 c# .net winforms combobox

我试图在 DataGrid 的点击事件上设置 comboBox 的选定项,但我做不到。我用谷歌搜索并尝试了不同的方法但没有成功。

对我来说,SelectedIndex 可以正常工作,但我无法在 ComboBox 中找到项目的索引,因此我无法选择该项目。

无效代码:

for (int i = 0; i < cmbVendor.Items.Count; i++)

    if (cmbVendor.Items[i].ToString() == Convert.ToString(gridView1.GetFocusedRowCellValue("vVendor")))
    {
        cmbVendor.SelectedIndex = i;
        break;
    }

最佳答案

您可以通过 .Items.IndexOf() 方法获取项目索引。试试这个:

comboBox1.SelectedIndex = comboBox1.Items.IndexOf(gridView1.GetFocusedRowCellValue("vVendor"));

您不需要迭代。

您可以在 Stack Overflow 问题 中找到更多信息 How do I set the selected item in a comboBox to match my string using C#? .

关于c# - 如何在 C# Windows 窗体中设置 ComboBox 的选定项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9396117/

相关文章:

.net - 使整个方法成为线程安全的最简单方法?

c# - 是否有 "stock"空闲/等待对话框?

c# - 缓存或应用程序变量来存储对象列表?

C# 嵌套、 Elasticsearch : update and add to a field that is a list

c# - 为 Azure Functions 创建测试项目

c# - 为什么大多数时候只能向前遍历?

c# - 如何跟踪.NET中StackOverflowException的原因?

.net - CheckedListBox.Items 中每个项目的类型是什么?

c# - 用于 Mono 的 Winforms 或 XWT GUI 设计器?

windows - 错误1001。初始化安装时发生异常