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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18022238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:04:52  来源:igfitidea点击:

How can I programmatically select an item in a listbox?

c#listboxcompact-frameworklistboxitem.net-1.1

提问by B. Clay Shannon

I have a listbox displaying items from an enum. I want to select/highlight the current value (read from a database) when the listbox displays/the form opens. This code, though:

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

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

...does not work. I saw an example using "GetItemAt" here (Programmatically selecting Items/Indexes in a ListBox) but my stripped down and archaic version of C# (.NET 1.1, C# 2) has no such critter.

...不起作用。我在这里看到了一个使用“GetItemAt”的例子(以编程方式选择 ListBox 中的项目/索引),但我的 C#(.NET 1.1、C# 2)的精简和古老版本没有这样的生物。

UPDATE

更新

I thought this would work:

我认为这会奏效:

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

...but it, also, does not (the current printer displays in the label, but the corresponding entry/value in the listbox is not selected).

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

采纳答案by jp2code

I see you've already solved this, but why not do it the tried and tested way?

我看到你已经解决了这个问题,但为什么不以久经考验的方式来做呢?

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

This way, you know the SelectedIndexvalue is set to -1 as soon as the text changes, and if it is found in your ListBox, that item is selected.

这样,您就知道SelectedIndex一旦文本更改,该值就会设置为 -1,并且如果在您的 中找到该值ListBox,则该项目将被选中。

Even better would be to write a handler when the Label control lblSelectedPrinterfires the TextChangedevent.

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

lblSelectedPrinter.TextChanged += new EventHandler(SelectedPrinter_TextChanged);

Then, create that Event Handler like shown above:

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

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

You've already solved your problem, so this is just food for thought.

你已经解决了你的问题,所以这只是思考的食物。

回答by AnotherDeveloper

int i = AppSettings.ReadSettingsVal("beltprinter"); //Save it as an int.
listBoxBeltPrinters.SelectedItem = listBoxBeltPrinters.Items.IndexOf(i);
lblSelectedPrinter.Text = listBoxBeltPrinters.SelectedItem.toString();

回答by Apollo SOFTWARE

You need it to be an integer. You can use int.Parse to Convert to cast it from string to int.

你需要它是一个整数。您可以使用 int.Parse to Convert 将其从字符串转换为 int。

listBoxBeltPrinters.SelectedItem = listBoxBeltPrinters.Items.IndexOf(int.Parse(System.Configuration.ConfigurationSettings.AppSettings.Get("beltprinter")));
lblSelectedPrinter.Text = listBoxBeltPrinters.SelectedItem.toString();

回答by spro

lblSelectedPrinter.Text = AppSettings.ReadSettingsVal("beltprinter");

listBoxBeltPrinters.SelectedItem = listBoxBeltPrinters.Items.FindByText(lblSelectedPrinter.Text);

By value:

按价值:

listBoxBeltPrinters.SelectedItem = listBoxBeltPrinters.Items.FindByValue(1);

回答by B. Clay Shannon

This works:

这有效:

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

This is the only code required to display, read, and write the settings val:

这是显示、读取和写入设置 val 所需的唯一代码:

private void PrinterPickerForm_Load(object sender, System.EventArgs e)
{
    Type type = typeof(PrintUtils.BeltPrinterType);
    foreach (FieldInfo field in type.GetFields(BindingFlags.Static | BindingFlags.Public))
    {
        string display = field.GetValue(null).ToString();
        listBoxBeltPrinters.Items.Add(display);
    }
    string currentPrinter = AppSettings.ReadSettingsVal("beltprinter");
    lblCurrentPrinter.Text = currentPrinter;
    int currentPrinterIndex = listBoxBeltPrinters.Items.IndexOf(currentPrinter);
    listBoxBeltPrinters.SelectedIndex = currentPrinterIndex;
}

private void btnSaveSelectedVal_Click(object sender, System.EventArgs e)
{
    string sel = listBoxBeltPrinters.SelectedItem.ToString();
    if (sel != lblCurrentPrinter.Text)
    {
        AppSettings.WriteSettingsVal("beltPrinter", sel);
    }
}

回答by Apollo SOFTWARE

can you try the following??? It takes from your code, and then uses FindString

你可以试试以下吗???它从您的代码中获取,然后使用 FindString

string currentPrinter = AppSettings.ReadSettingsVal("beltprinter");
lblSelectedPrinter.Text = currentPrinter;
int index = listBoxBeltPrinters.FindString(lblSelectedPrinter.Text);
listBoxBeltPrinters.SelectedIndex = index;

回答by Tyler Pantuso

This works:

这有效:

listBoxBeltPrinters.SetSelected(listBoxBeltPrinters.FindString("beltprinter"), true);

回答by coarist

Combination of listBoxObject.SetSelected()and listBoxObject.FindString()is an elegant solution. It works for me, too.

的组合listBoxObject.SetSelected()listBoxObject.FindString()是一个很好的解决方案。它也适用于我。