Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Split() in ListBox

Tags:

c#

split

listbox

listBox2 contents:

0:FirstProduct
1:ProductAgain
2:AnotherProduct
3:OkFinalProduct

What I'm trying to do, when the selected index has changed on listBox2, is to have it make my int "DBID" the value of the number before the ":".

Here's my attempt:

    private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
    if (listBox2.SelectedIndex == -1)
    {
        return;
    }
    int DBID;
    DBID = Convert.ToInt32(listBox3.SelectedValue.ToString().Split(":"[0]));
    ShowProduct(DBID);
}

ANY help with this is greatly appreciated :)

Thanks guys

EDIT - Sorry, yes I actually tried:

DBID = Convert.ToInt32(listBox3.SelectedValue.ToString().Split(':')[0]); 

but im getting the following errors:

  • The best overloaded method match for string.Split(params char[])' has some invalid arguments
  • Argument1: cannot convert from 'string' to 'char[]



EDIT #2 -
When using:

DBID = Convert.ToInt32(listBox3.SelectedValue.ToString().Split(':')[0]);

After running the application and clicking on a different listbox item, I'm encountering this exception:

NullReferenceException was unhandled. Object reference not set to an instance of an object.

I appreciate all the help so far guys!

like image 906
kogh Avatar asked Mar 04 '26 04:03

kogh


2 Answers

Try changing:

DBID = Convert.ToInt32(listBox3.SelectedValue.ToString().Split(":"[0]));

To:

DBID = Convert.ToInt32(listBox3.SelectedValue.ToString().Split(':')[0]);

Update

Try this instead. It explicitly adds a new char:

DBID = Convert.ToInt32(listBox3.SelectedValue.ToString().Split(new char[] { ':' })[0]);
like image 137
NakedBrunch Avatar answered Mar 05 '26 16:03

NakedBrunch


DBID = Convert.ToInt32(listBox3.SelectedValue.ToString().Split(':')[0]);
like image 34
ajma Avatar answered Mar 05 '26 16:03

ajma