简体   繁体   English

WPF:C#如何获取列表框的选定值?

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

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" } and even if i try to get the value from LstGroup1.SelectedValue the output is same.当我实际尝试LstGroup1.SelectedItem时,我得到了值{ BoothID = "4", BoothName = "HP" } ,即使我尝试从LstGroup1.SelectedValue获取值,输出也是相同的。 Now I want to fetch BoothID ie the expected output is 4 but i am unable to get so.现在我想获取BoothID即预期的输出是4但我无法得到。

My ListBox name is LstGroup1 .我的ListBox名称是LstGroup1

public List<object> BoothsInGroup1 { get; set; }
// Inside the Constructor 
BoothsInGroup1 = new List<object>();
//After Fetching the value add 
BoothsInGroup1.Add(new { BoothID = da["BoothID"].ToString(), BoothName = da["BoothName"].ToString() });

//Now here I get 
var Booth = (LstGroup1.SelectedItem);
//Output is { BoothID = "4", BoothName = "HP" }

// Expected Output 4

Suggest me how to do that.建议我如何做到这一点。


EDIT编辑

public partial class VotingPanel : Window
{
    public List<object> BoothsInGroup1 { get; set; }
    public VotingPanel()
    {
        InitializeComponent();
        DataContext = this;
        BoothsInGroup1 = new List<object>();

        //Connection is done
        SqlConnection con = new SqlConnection(ConnectionString);
        con.Open();

        FieldNameCmd.CommandText = "SELECT * FROM Booth b, BoothGroup bg where bg.GroupID=b.GroupID;";
        IDataReader da = FieldNameCmd.ExecuteReader();
        while (da.Read())
        {
            if (Group1Name.Text == da["GroupName"].ToString())
            { // Adds value to BoothsInGroup1
                BoothsInGroup1.Add(new { BoothID = da["BoothID"].ToString(), BoothName = da["BoothName"].ToString() });
            }
        }
    }
    private void BtnVote_Click(object sender, RoutedEventArgs e) // on Click wanted to find the value of Selected list box
    {   
        if (LstGroup1.SelectedIndex >= 0 && LstGroup2.SelectedIndex >= 0)
        {
            var Booth = (LstGroup1.SelectedItem);
            //Few things to do 
        }
    }
}

XAML XAML

<ListBox Grid.Row="1"
         Name="LstGroup1"
         ItemsSource="{Binding BoothsInGroup1}"
         Margin="5,1">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid Margin="5">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition />
                    <ColumnDefinition />
                </Grid.ColumnDefinitions>
                <TextBlock Text="{Binding BoothID}"
                           HorizontalAlignment="Center"
                           VerticalAlignment="Bottom"
                           FontSize="15"
                           FontWeight="ExtraBold"
                           Margin="5,3"
                           Grid.Column="1" />
                <TextBlock Text="{Binding BoothName}"
                           Grid.Column="1"
                           VerticalAlignment="Center"
                           FontWeight="ExtraBold"
                           FontSize="30"
                           Margin="15" />

            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

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. 由于您使用匿名类型填充列表框,因此您别无选择,而是将object类型强制转换为SelectedItem other approach may include Reflection to extract the field/property values. 其他方法可能包括反射以提取字段/属性值。

but if you are using C# 4 or above you may leverage dynamic 但是如果您使用的是C#4或更高版本,则可以利用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. 这可能会解决您当前的问题,但是出于许多原因,我建议出于同样的原因创建一个类。

Have you tried : 你有没有尝试过 :

var Booth = (LstGroup1.SelectedItem);
string ID=Booth.BoothID;
string Name=Booth.BoothName:

I think, you should try one of the following : //EDIT : This solution only works, if Booth is a class/struct 我认为,您应该尝试以下操作之一://编辑:仅当Booth是类/结构时,此解决方案才有效

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: 如果Booth还不是课程,请添加一个新的课程:

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() 
   });

You can always create a class called Booth to get the data in the Object Format. 您始终可以创建一个名为Booth的类来获取对象格式的数据。 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;
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;

For those that know the type or object that they want the code will look like this:对于那些知道他们想要的类型或对象的人来说,代码如下所示:

private void lboxAccountList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
      //Class object = (Class)listName.SelectedItem;
      // object.getName or object.getSomeVariable or object.callMethod(object.getName)

      Account account  = (Account)lboxAccountList.SelectedItem;
      MessageBox.Show(""+account.AccountNo+" "+account.Balance);          
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM