C# How to pick Person id from listbox string?

miksuFin
miksuFin used Ask the Experts™
on
I have listbox which has many rows.
First word in every row is PersonId.
I want pick this Person Id and use it in SQL Query like this: " SELECT * FROM mydatatable WHERE ID = '"+ PersonId+"'.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Author

Commented:
This is desktop -application, not web-app.
Bootstrap 4: Exploring New Features

Learn how to use and navigate the new features included in Bootstrap 4, the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites.

Author

Commented:
I suppose that the code is something like this

int item = listBox1.ValueMember.First;
SelectedValue didn't work?

Author

Commented:
OR something like that
 int item = Convert.ToInt32(listBox1.ValueMember.First(listBox1.Items));

Author

Commented:
I tried this;  int item = Convert.ToInt32(listBox1.SelectedValue);
, but it didn't work.

Author

Commented:
this works almost:
   int item = Convert.ToInt32(listBox1.SelectedItem.ToString());

It shows wanted row like this : {SelectedItem= "3\t\tSometext\t\tSometext\t\tSometext"}

Problem is how to pick "3" from the string.

Author

Commented:
I tried also this:

  string teksti = listBox1.SelectedItem.ToString();

    int item = Convert.ToInt32(teksti.Substring(0, teksti.IndexOf(" "))); <-- Converting problem!

Author

Commented:
This works:

string teksti = listBox1.SelectedItem.ToString();

    int item = Convert.ToInt32(teksti.Substring(0, teksti.IndexOf("\t\t ")));
good that you figured  it out.
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
An alternative approach is to add objects to your ListBox instead of strings. The SelectedItem property of the ListBox will then contain an object and you can simply get a property:

yourClass item = (yourClass)listbox1.SelectedItem;
int personID = item.PersonId;

Open in new window

You could also override the ToString() method in your class to return the PersonId:

var personId = listbox1.SelectedItem.ToString();

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial