开发者

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

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 开发者_StackOverflowobject.

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.

Note that this example assumes that you are using System.Windows.Controls.ListBox or System.Windows.Forms.ListBox, and not System.Web.UI.WebControls.ListBox. In the later case, the SelectedValue is a string and not an object (as pointed out by @Srinivas Reddy Thatiparthy in another answer's comment)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜