Get selected value from combo box in C# WPF

后端 未结 21 701
粉色の甜心
粉色の甜心 2020-12-08 09:29

I have just started using WPF forms instead of Windows Forms forms. In a Windows Forms form I could just do:

ComboBox.SelectedValue.toString();
21条回答
  •  渐次进展
    2020-12-08 10:09

    This largely depends on how the box is being filled. If it is done by attaching a DataTable (or other collection) to the ItemsSource, you may find attaching a SelectionChanged event handler to your box in the XAML and then using this in the code-behind useful:

    private void ComboBoxName_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ComboBox cbx = (ComboBox)sender;
        string s = ((DataRowView)cbx.Items.GetItemAt(cbx.SelectedIndex)).Row.ItemArray[0].ToString();
    }
    

    I saw 2 other answers on here that had different parts of that - one had ComboBoxName.Items.GetItemAt(ComboBoxName.SelectedIndex).ToString();, which looks similar but doesn't cast the box to a DataRowView, something I found I needed to do, and another: ((DataRowView)comboBox1.SelectedItem).Row.ItemArray[0].ToString();, used .SelectedItem instead of .Items.GetItemAt(comboBox1.SelectedIndex). That might've worked, but what I settled on was actually the combination of the two I wrote above, and don't remember why I avoided .SelectedItem except that it must not have worked for me in this scenario.

    If you are filling the box dynamically, or with ComboBoxItem items in the dropdown directly in the XAML, this is the code I use:

    private void ComboBoxName_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ComboBox cbx = (ComboBox)sender;
        string val = String.Empty;
        if (cbx.SelectedValue == null)
            val = cbx.SelectionBoxItem.ToString();
        else
            val = cboParser(cbx.SelectedValue.ToString());
    }
    

    You'll see I have cboParser, there. This is because the output from SelectedValue looks like this: System.Windows.Controls.Control: Some Value. At least it did in my project. So you have to parse your Some Value out of that:

    private static string cboParser(string controlString)
    {
        if (controlString.Contains(':'))
        {
            controlString = controlString.Split(':')[1].TrimStart(' ');
        }
        return controlString;
    }
    

    But this is why there are so many answers on this page. It largely depends on how you are filling the box, as to how you can get the value back out of it. An answer might be right in one circumstance, and wrong in the other.

提交回复
热议问题