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

前端 未结 5 1739
忘掉有多难
忘掉有多难 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: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.

提交回复
热议问题