C # Split () in ListBox

contents of the Box2 list:

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

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

Here is 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 much appreciated :)

Thanks guys,

EDIT - Sorry, yes, I really tried:

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

but im gets the following errors:

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



EDIT No. 2 -
When using:

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

, :

NullReferenceException . .

, !

+3
3

,

if (listBox3.SelectedValue != null)
{
    string selectedValue = listBox3.SelectedValue.ToString();

    if (!string.IsNullOrEmpty(selectedValue))
    {
        if (Int32.TryParse(selectedValue.Split(':')[0], NumberStyles.Integer, CultureInfo.CurrentCulture, out DBID))
        {
            // Process DBID
        }
        else
        {
            // Cannot convert to Int32
        }
    }
}

breakpoints , NullReferenceException.

, , System.Windows.Controls.ListBox System.Windows.Forms.ListBox, System.Web.UI.WebControls.ListBox. SelectedValue string, a object ( @Srinivas Reddy Thatiparthy )

+1

:

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

To:

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

Try this instead. It explicitly adds a new char:

DBID = Convert.ToInt32(listBox3.SelectedValue.ToString().Split(new char[] { ':' })[0]);
+4
source
DBID = Convert.ToInt32(listBox3.SelectedValue.ToString().Split(':')[0]);
+3
source

Source: https://habr.com/ru/post/1795940/


All Articles