【问题标题】:c# select a value in comboboxc#在组合框中选择一个值
【发布时间】:2011-05-27 09:21:16
【问题描述】:

我在 c# windows 窗体中的组合框充满了来自我的数据库的数据... 显示成员是字符串,值成员是整数

我现在必须在显示表单之前预先选择它。 我试过了:

combobox.DisplayMember = string;
combobox.Text = string;
combobox.SelectedItem = string;
combobox.SelectedText = string;
combobox.SelectedValue = string;

谁能给我一点帮助? 会很高兴:-)

编辑:ei。也许其他人的解决方案... 请记住,VS2010 设计器创建的负载是在构造函数之后加载的。正如我所想的那样,不在 initializeComponents() 中。

【问题讨论】:

  • 对不起,朋友,再检查一遍,如果有任何问题,请发表评论。

标签: c# database select combobox


【解决方案1】:

使用ComboBox.SelectedIndex

例如:

myComboBox.SelectedIndex = [index of item to select];

注意ComboBox.Items 是一个ObjectCollection,它有一个名为IndexOf() 的方法。将一个对您要选择的对象的引用传递给它,您应该会得到正确的索引。

【讨论】:

  • 如果我问得这么愚蠢,我应该如何获得索引? :-)
  • @Anders Metnik 好吧,一种方法是使用ComboBox.Items.IndexOf()。见编辑。
【解决方案2】:

找到Item,然后将组合框的SelectedItem属性设置为true。

编辑:

comboBox.SelectedItem = comboBox.Items.Cast<string>().First(o => o == "blala");

如果您的项目是字符串,请使用Cast&lt;string&gt;(),快速查询组合框。项目将向您显示该对象。

如果我记不清到底是不是winforms,你应该将选中项的selected属性设置为false,然后再设置另一个为true。

检查一下,如果是这种情况,只需添加以下行:

combobox.SelectedIndex = -1;

【讨论】:

  • 我的物品下没有.First,你知道为什么吗? :-(
  • 将 System.Linq 命名空间添加到您的使用中。
  • 使用系统;使用 System.Collections.Generic;使用 System.ComponentModel;使用 System.Data;使用 System.Drawing;使用 System.Linq;使用 System.Text; using System.Windows.Forms;\n 这些是我的潮流?
  • 呵呵,非常感谢您的回答,它们都工作得很好。(尽管在您上次编辑后没有测试过)。
  • +1,我用过:comboBox.SelectedItem = comboBox.Items.Cast&lt;ListItem&gt;().First(o =&gt; o.Text == "blala");
【解决方案3】:

如果您的 ComboBox 是数据绑定的并且您已正确设置 DisplayMember 和 ValueMember 属性,那么您只需将 SelectedValue 属性设置为您要选择的项目的值。

例如,如果您的组合框中有以下对象:

标识说明 -- ------------------ 2 洛雷姆 4 Ipsum 6 多洛尔 8 坐

您可以将 DisplayMember 设置为“Description”,将 ValueMember 设置为“ID”。然后为了选择“Dolor”项,您只需设置 SelectedValue = 6。

【讨论】:

【解决方案4】:

另一种方式:

combobox.SelectedIndex = combobox.FindStringExact("myString")

【讨论】:

    猜你喜欢
    • 2017-04-19
    • 2016-05-29
    • 1970-01-01
    • 2012-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    相关资源
    最近更新 更多