Swag
Swag

Reputation: 2140

Get id from selected item listbox

With a SELECT query I get some data from the database (for example users). I put all the data in a List<User>.

List<User> listUsers = new List<User>();

To load this data in the listbox I do:

Foreach(User u in listUsers)
{
     listbox.Items.Add(u.name + " " + u.lastname)
}

What I would like to do is the next:

When someone clicks on one of the list items (on one of the users), my c# form application need to get the user id (from the dbs) from the selected user.

string name = listbox.SelectedItem.ToString();

I can't do:

SELECT UserID FROM Person WHERE Username = name;

Because the SelectedItem will contain a name and last name with a space.

Can someone help me?

Thanks

Upvotes: 0

Views: 3793

Answers (2)

shahkalpesh
shahkalpesh

Reputation: 33474

While filling the listbox, make a query to get the UserID column along with user name, user last name.

Create a class that will represent each item of the list, such as

public class UserInfo
{
   public string DisplayName {get; set;}
   public int UserID {get; set;}
}

Make listUsers to be of List<UserInfo> type. While filling the data from the tables into the list, do the following

while (myUserData.Read())
{
   listUsers.Add(new UserInfo() {DisplayName = myUserData["DisplayName"] , UserID = myUserData["UserID")})
}

Post the list filling, use DataSource to bind the data, DisplayMember property to the DisplayName property, ValueMember property to UserID property.

Look at this page for an example of how to use databinding for details.

Upvotes: 0

Nikola Davidovic
Nikola Davidovic

Reputation: 8656

Why don't you introduce a Property ID in your User class? You could fill that property too along with other data. Then you can also override the ToString() method in your class user which will help you to display the name and lastname. You can add instances of User class instead of strings and cast selections directly to the User class where you have your ID. Check the code:

public class User
{
       public string Name { get; set; }
       public string LastName { get; set; }
       public int ID { get; set; }
       public override string ToString()
       {
             return Name + " " + LastName;
       }
       ...
}

//fill the listBox
foreach(User u in listUsers)
{
       listbox.Items.Add(u);
}

//get the celected User

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
       ListBox lb = (ListBox)sender;
       User user = (User)lb.Items[lb.SelectedIndex];
       MessageBox.Show(user.ID.ToString());
}

Upvotes: 3

Related Questions