简体   繁体   中英

C# Split() in 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

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[]




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!

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]);
DBID = Convert.ToInt32(listBox3.SelectedValue.ToString().Split(':')[0]);

A safer way will be to replace the single statement with the following code,

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

Then use breakpoints in the code, to find where the NullReferenceException is occurring.

that this example assumes that you are using System.Windows.Controls.ListBox or System.Windows.Forms.ListBox , and not System.Web.UI.WebControls.ListBox . ,此示例假定您使用的是System.Windows.Controls.ListBoxSystem.Windows.Forms.ListBox ,而不是System.Web.UI.WebControls.ListBoxIn the later case, the SelectedValue is a string and not an object (as pointed out by @Srinivas Reddy Thatiparthy in another answer's comment)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM