Question

In my WPF Application, I have a Combobox as "ComboBox1" with the items from tabel "Login". Now I want to retrieve the selected value in the combobox1. Ex : Table "Login" consists of records One, Two, Three. I just added this values to the combobox1 through Data Table. Then When I want to print the selected value in the combobox1. How this can be done..in WPF. I had given below my coding for saving the combobox1 with items.

        SqlDataAdapter Da = new SqlDataAdapter();
        DataSet Ds = new DataSet();

        Con.Open();
        Cmd = new SqlCommand("select Id from Login", Con);
        Da.SelectCommand = Cmd;
        try 
        {
            Da.Fill(Ds, "User_Id");
            comboBox1.DataContext = Ds.Tables["User_Id"].DefaultView;
            comboBox1.DisplayMemberPath = Ds.Tables["User_Id"].Columns["Id"].ToString();
        }
        catch(Exception ex)
        {
            MessageBox.Show("Table can't be updated");
        }
        Con.Close();

the coding for retreiving the selected value is as follows :

if (comboBox1.SelectedItem != null)
        {
            ComboBoxItem typeItem = (ComboBoxItem)comboBox1.SelectedItem;
            string value = typeItem.Content.ToString();
            textBox5.Text = value;
        }

NOTE : Check this link for clear understanding of the problem :http://postimg.org/image/bn27nae65/

Was it helpful?

Solution

Here's your xaml for the combo box named "_combo":

<ComboBox SelectedValue="{Binding SelectedValue}" x:Name="_combo" >
      <ComboBoxItem Content="One"/>
      <ComboBoxItem Content="Two"/>
      <ComboBoxItem Content="Three"/>
</ComboBox>

And here's the code behind:

private string _SelectedItem;
public string SelectedItem
{
    get { return _SelectedItem; }
    set
    {
        _SelectedItem = value;
        OnPropertyChanged("SelectedItem");
        textbox5.text = _combo.Content.ToString();
    }
}

Check out databinding and "Inotifypropertychanged" if this is confusing to you.

EDIT: Here's all the code from a brief sample I typed up.

Basically you have an object called MainViewModel, and all the properties in your XAML are bound to the view model objects properties. Below, TextBox has a property called text, which defaults to "ComboBox binding example -- ..." because that is what the string property in the view model is bound to. If you change the text in the box, the property value in code behind is changed. If some code you wrote in code behind changes the property, the text box will update in XAML as well. This is the best way to develop in WPF! (or most of the time atleast). It took me forever to understand how this works but once I got it made developement sooooo much quicker and easier. Best of all you can totally change you're GUIs appearance while the code behind that does all the operations stays the same.

This also can be done by adding a selection changed event to the ComboBox. Its actually easier in this case but doesn't provided the amount of power that INotifyPropertyChanged does. Namely because events only fire in one directions, i.e. ComboBox_Changed -> Event fired in code. INotifyPropertyChanged works in both direcitons.

This style of coding is know as MVVM. While it often confuses the hell out of beginners, it's an awesome way to applications once you get it down.

<Window x:Class="ComboBoxSample.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525" x:Name="view">
<Grid>
    <StackPanel>
        <TextBox x:Name="_textbox" Margin="5,5,5,5" Text="{Binding DataContext.text, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}" />
        <ComboBox x:Name="_combo"  Margin="5,0,5,5" SelectedItem="{Binding DataContext.SelectedItem, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}">
            <ComboBoxItem Content="Blue"/>
            <ComboBoxItem Content="Red"/>
            <ComboBoxItem Content="Green"/>
            <ComboBoxItem Content="Black"/>
        </ComboBox>
        <TextBox x:Name="_textbox2" Text="Other method for updating text" Margin="5,5,5,5"/>
        <ComboBox x:Name="_combo2" SelectionChanged="ComboBox_SelectionChanged">
            <ComboBoxItem Content="One"/>
            <ComboBoxItem Content="Two"/>
            <ComboBoxItem Content="Three"/>
        </ComboBox>
    </StackPanel>
</Grid>

Here's the mainwindow.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ComboBoxSample
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MainViewModel(_combo);
    }

    private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        string value = _combo2.Items[_combo2.SelectedIndex].ToString().Substring(38);
        _textbox2.Text = value;
    }
}
}

And here's the all important view model:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ComboBoxSample
{
public class MainViewModel : INotifyPropertyChanged
{
    public ComboBox combo;
    public TextBox textbox;

    public MainViewModel(ComboBox _combo)
    {
        combo = _combo;
    }

    private string _text = "ComboBox Binding Example --Changing the combox will change this text!";
    public string text
    {
        get { return _text; }
        set
        {
            _text = value;
            OnPropertyChanged("text");
        }
    }

    private string _SelectedItem;
    public string SelectedItem
    {
        get { return _SelectedItem; }
        set
        {
            _SelectedItem = value;
            OnPropertyChanged("SelectedValue");
            string val = combo.Items[combo.SelectedIndex].ToString().Substring(38);
            text = val;
        }
    }



    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top