c# - 如何以编程方式选择列表框中的项目?

标签 c# listbox compact-framework listboxitem .net-1.1

我有一个列表框显示枚举中的项目。当列表框显示/表单打开时,我想选择/突出显示当前值(从数据库中读取)。不过这段代码:

lblSelectedPrinter.Text = AppSettings.ReadSettingsVal("beltprinter");
listBoxBeltPrinters.SelectedItem = listBoxBeltPrinters.Items.IndexOf(lblSelectedPrinter.Text);

...不起作用。我在此处 (Programmatically selecting Items/Indexes in a ListBox) 看到了一个使用“GetItemAt”的示例,但我的 C# 精简版本(.NET 1.1、C# 2)没有这样的小东西。

更新

我认为这会起作用:

string currentPrinter = AppSettings.ReadSettingsVal("beltprinter");
lblSelectedPrinter.Text = currentPrinter;
int currentPrinterIndex = listBoxBeltPrinters.Items.IndexOf(currentPrinter);
listBoxBeltPrinters.SelectedItem = currentPrinterIndex;

...但它也没有(当前打印机显示在标签中,但未选择列表框中的相应条目/值)。

最佳答案

我看到您已经解决了这个问题,但为什么不用久经考验的方法呢?

  lblSelectedPrinter.Text = AppSettings.ReadSettingsVal("beltprinter");
  listBoxBeltPrinters.SelectedIndex = -1;
  if (!String.IsNullOrEmpty(lblSelectedPrinter.Text)) {
    for (int index = 0; index < listBoxBeltPrinters.Items.Count; index++) {
      string item = listBoxBeltPrinters.Items[index].ToString();
      if (lblSelectedPrinter.Text == item) {
        listBoxBeltPrinters.SelectedItem = index;
        break;
      }
    }
  }

这样一来,您就知道 SelectedIndex 值会在文本更改后立即设置为 -1,如果在您的 ListBox 中找到它,则该项目已被选中.

更好的方法是在 Label 控件 lblSelectedPrinter 触发 TextChanged 事件时编写处理程序。

lblSelectedPrinter.TextChanged += new EventHandler(SelectedPrinter_TextChanged);

然后,创建如上所示的事件处理程序:

private void SelectedPrinter_TextChanged(object sender, EventArgs e) {
  listBoxBeltPrinters.SelectedIndex = -1;
  if (!String.IsNullOrEmpty(lblSelectedPrinter.Text)) {
    for (int index = 0; index < listBoxBeltPrinters.Items.Count; index++) {
      string item = listBoxBeltPrinters.Items[index].ToString();
      if (lblSelectedPrinter.Text == item) {
        listBoxBeltPrinters.SelectedItem = index;
        break;
      }
    }
  }
}

您已经解决了您的问题,所以这只是值得深思的问题。

关于c# - 如何以编程方式选择列表框中的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18022238/

相关文章:

c# - 如何在 Windows Mobile 上以 C# 设置网络管理设置或使对话框显示?

c# - 如何使用 LINQ 优化多个 if else

c# - "services.AddRazorPages();"实际上添加了哪些服务?

c# - 如何使用 EF6 Code First 将外键属性公开给具有导航属性的现有实体

vb.net - 从对象内部的对象列表绑定(bind)列表框

c# - .net Compact Framework 4.0

c# - 我怎样才能只公开 IList<> 的一个片段?

C# 通过两个日期将时间写为字符串

Silverlight MVVM ListBoxItem IsSelected

python - 在 tkinter 中使用 wait_window() 时如何返回列表框的选定项目