简体   繁体   中英

how should I give the user a selection and grab the guid from that selection

I have to give the user an option to select from a list of items and then, pending on what single item they select, I need to get the guid from that item. This will be populated from a Linq query from a Sql table.

I started with this:

private void PopulateGatewayList()
{
  var gateways = from gw in _entities.Gateways
                 where gw.IsActive
                 select gw;

  foreach (var gateway in gateways)
  {
    checkedListBox_Gateways.Items.Add(gateway.Name);
  }
}

But I have no way of grabbing the guid once they check something.

What is a good way of giving the user the name but give me back the guid?

** ANSWER **

Using Michael Yoon's help, I did the following:

private void PopulateGatewayList()
{
  var gateways = from gw in _entities.Gateways
                 where gw.IsActive
                 select gw;

  foreach (var gateway in gateways)
  {
    checkedListBox_Gateways.Items.Add(new ListItem(gateway.Name, gateway.GatewayId.ToString()));
    //checkedListBox_Gateways.Items.Add(gateway.Name);
  }
}


private void checkedListBox_Gateways_SelectedIndexChanged(object sender, EventArgs e)
{
  foreach (Object selecteditem in checkedListBox_Gateways.SelectedItems)
  {
    var strItem = selecteditem as ListItem;
    Console.WriteLine("Selected: " + strItem.Value);
  }
}

You need to add an object to the collection that contains the id and string. You can use KeyValuePair or make your own. I'll use keyvaluepair in my example.

checkedListBox_Gateways.DisplayMember = "Key";
checkedListBox_Gateways.ValueMember = "Value";
checkedListBox_Gateways.Items.Add(new KeyValuePair<string, string>(gateway.Name, gateway.Id.ToString()));

Then you can enumerate the SelectedItems collection, cast each back to a keyvaluepair and get the value out of it.

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