Can't Find on a combox

rfresh

Active member
Joined
Aug 23, 2012
Messages
26
Programming Experience
1-3
This is pretty simple c# code below.

Why does .SelectedIndex result in -1? I was expecting the value to be 2.

C#:
comboBoxLSK.Items.Add("test1");
comboBoxLSK.Items.Add("test2");
comboBoxLSK.Items.Add("test3");
comboBoxLSK.SelectedIndex = comboBoxLSK.FindStringExact("test3");
 
I just tested your code and it does exactly as expected, i.e. sets the SelectedIndex of the ComboBox to 2. If you're not seeing that then you're getting the SelectedIndex value incorrectly, either before that code is executed or after some other code that changes the SelectedIndex to -1 or something else that we just don't know about.
 
Yeah...that's very odd for me because I'm stepping into that code in my VS 2013 debugger and when I stop and inspect that index value, it's either null or -1. And, you're right, it should be 2.

Maybe I need to restart my PC. I'll give that a try. Thanks for looking at this. I was just wondering if I was missing something simple.
 
Yeah...that's very odd for me because I'm stepping into that code in my VS 2013 debugger and when I stop and inspect that index value, it's either null or -1. And, you're right, it should be 2.

Maybe I need to restart my PC. I'll give that a try. Thanks for looking at this. I was just wondering if I was missing something simple.

When you break on that line, the line has not yet been executed. It's not until after the line is executed that you'll see the new property value. I tested like this:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            comboBoxLSK.Items.Add("test1");
            comboBoxLSK.Items.Add("test2");
            comboBoxLSK.Items.Add("test3");
            comboBoxLSK.SelectedIndex = comboBoxLSK.FindStringExact("test3");
            MessageBox.Show(comboBoxLSK.SelectedIndex.ToString());
        }
    }
}
I just created a new project, added and renamed the ComboBox, created the event handler, pasted in your code and added the extra line.
 
Yes, I was stopping past that line so it should have been set correctly but it wasn't.

I rebooted my PC and now it it working as expected. Very odd thing to have happened.

Thanks for the help and time.
 
Back
Top Bottom