WPF: C# How to get selected value of Listbox?

前端 未结 5 1736
忘掉有多难
忘掉有多难 2021-01-27 17:00

I am trying to fetch the selected value of the listbox. When I actually try LstGroup1.SelectedItem I get the value { BoothID = \"4\", BoothName = \"HP\" }

相关标签:
5条回答
  • 2021-01-27 17:12

    Have you tried :

    var Booth = (LstGroup1.SelectedItem);
    string ID=Booth.BoothID;
    string Name=Booth.BoothName:
    
    0 讨论(0)
  • 2021-01-27 17:16

    I think, you should try one of the following : //EDIT : This solution only works, if Booth is a class/struct

    var myBooth = LstGroup1.SelectedItem as Booth;
    String id =myBooth.BoothID;
    String name=myBooth.BoothName:
    

    or use a generic list with a different type :

    public List<Booth> BoothsInGroup1 { get; set; }
    ....
    var myBooth = LstGroup1.SelectedItem;
    String id =myBooth.BoothID;
    Stringname=myBooth.BoothName:
    

    And if Booth isn't a class yet, add a new class:

    public class Booth
    {
        public int BoothID { get; set; }
        public String BoothName { get; set; }
    }
    

    So u can use it in your generic list, an you can fill it after databasereading

    BoothsInGroup1.Add(new Booth
       { 
         BoothID = Convert.ToInt32(da["BoothID"]),
         BoothName = da["BoothName"].ToString() 
       });
    
    0 讨论(0)
  • 2021-01-27 17:31
    public List<object> BoothsInGroup1 { get; set; }
    
    BoothsInGroup1 = new List<object>();
    
    BoothsInGroup1.Add(new { BoothID = da["BoothID"].ToString(), BoothName = da["BoothName"].ToString() });
    
    
    var Booth = (LstGroup1.SelectedItem);
    var output = Booth.BoothID;
    
    0 讨论(0)
  • 2021-01-27 17:35

    You can always create a class called Booth to get the data in the Object Format. From My point of view Dynamic is not the right way of doing this. Once you have the Class Booth in the Solution you can run

    Booth Booth1 = LstGroup1.SelectedItem as Booth;
    string BoothID1 = Booth1.BoothID;
    
    0 讨论(0)
  • 2021-01-27 17:36

    since you are using anonymous type to populate the listbox, so you have left with no option then an object type to cast the SelectedItem to. other approach may include Reflection to extract the field/property values.

    but if you are using C# 4 or above you may leverage dynamic

        if (LstGroup1.SelectedIndex >= 0 && LstGroup2.SelectedIndex >= 0)
        {
            //use dynamic as type to cast your anonymous object to
            dynamic Booth = LstGroup1.SelectedItem as dynamic;
            //Few things to do 
    
            //you may use the above variable as
            string BoothID = Booth.BoothID;
            string BoothName = Booth.BoothName:
    
        }
    

    this may solve your current issue, but I would suggest to create a class for the same for many reasons.

    0 讨论(0)
提交回复
热议问题