How can I programmatically select an item in a listbox?
Asked Answered
H

9

13

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.

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).

Hookup answered 2/8, 2013 at 16:50 Comment(6)
what error does it say in the debugger @Clay?Pedropedrotti
No debugger; my "debugger" is MessageBox.Show() due to the cobwebby nature of these tools.Hookup
can you put it in a try catch and throw the exception to us?Pedropedrotti
Thanks for your help, AmitApollo (I remember when you fought Rocky, by the way). There was no exception, it just wasn't working. It is now; I answered my own question.Hookup
Yeah, the D*mn Russian killed me in the fourth one! +1 for braving .NET 1.1/2.0. Time to leap into the 2010's ;)Pedropedrotti
Don't worry - at home I use VS2012 and am most heavily involved now with jQuery*Hookup
T
11

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 SelectedIndex value is set to -1 as soon as the text changes, and if it is found in your ListBox, that item is selected.

Even better would be to write a handler when the Label control lblSelectedPrinter fires the TextChanged event.

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.

Thorton answered 3/8, 2013 at 21:54 Comment(1)
if the "tried and tested way" is a nested if { for { if { break; } } } statement, then you know something's wrongAlgicide
H
4

This works:

listBoxBeltPrinters.SetSelected(listBoxBeltPrinters.FindString("beltprinter"), true);
Helsie answered 16/8, 2015 at 1:25 Comment(0)
O
2
int i = AppSettings.ReadSettingsVal("beltprinter"); //Save it as an int.
listBoxBeltPrinters.SelectedItem = listBoxBeltPrinters.Items.IndexOf(i);
lblSelectedPrinter.Text = listBoxBeltPrinters.SelectedItem.toString();
Ornament answered 2/8, 2013 at 16:57 Comment(0)
P
2

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

listBoxBeltPrinters.SelectedItem = listBoxBeltPrinters.Items.IndexOf(int.Parse(System.Configuration.ConfigurationSettings.AppSettings.Get("beltprinter")));
lblSelectedPrinter.Text = listBoxBeltPrinters.SelectedItem.toString();
Pedropedrotti answered 2/8, 2013 at 17:0 Comment(1)
I have no ConfigurationSettings.AppSettings After System.Configuration. the only thing available to me is "Assemblies"Hookup
H
2

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:

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);
    }
}
Hookup answered 2/8, 2013 at 17:52 Comment(0)
P
2

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

string currentPrinter = AppSettings.ReadSettingsVal("beltprinter");
lblSelectedPrinter.Text = currentPrinter;
int index = listBoxBeltPrinters.FindString(lblSelectedPrinter.Text);
listBoxBeltPrinters.SelectedIndex = index;
Pedropedrotti answered 2/8, 2013 at 18:39 Comment(1)
Thanks, but as I mentioned in my response to your previous comment, I already solved it, and added my solution as an answer. And I think I mentioned that I can't use FindString() - it's not available to me in my outdated and outmoded programming environment. Now pardon me while I get back to my abacus...Hookup
P
2

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

Polymorphism answered 9/1, 2018 at 14:24 Comment(0)
A
1
lblSelectedPrinter.Text = AppSettings.ReadSettingsVal("beltprinter");

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

By value:

listBoxBeltPrinters.SelectedItem = listBoxBeltPrinters.Items.FindByValue(1);
Albaugh answered 2/8, 2013 at 17:5 Comment(3)
Neither "FindByText" nor "FindByValue" is available to me following listBoxBeltPrinters.Items. Using these archaeologist's dreams (VS2003, &c) I feel like I'm fishing in the dark with a plastic pink rod outfitted only with a frayed line that's dangling in a dry creek (I'm going for the Bulwar-Lytton award).Hookup
jaj, the method index=lista.FindString("item") return the index, could be so lista.SetSelected(index,true);Albaugh
I don't know what "jaj" means, but FindString() is not available to me.Hookup
C
0

Use ListBox.ItemContainerStyl in your xaml to set ListBoxItem Style.Style Triggers. There is one example in stackoverflow. It works for me.

Chromaticity answered 2/2 at 10:57 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Groce

© 2022 - 2024 — McMap. All rights reserved.