Quantcast
Channel: .NET – Kelly's Chronicles
Viewing all articles
Browse latest Browse all 48

Databind ComboBox with WPF and C#

$
0
0

Its been a while my apologies. I have been extremely busy.

This topic came up because in existing applications data binding at design time was heavily used. I personally avoid such data binding as much as possible because well in all honesty it causes me a lot of problems later on. I realize many of you live and die with it. So don’t take it personally.

So I am converting one of these apps to XAML and WPF. They insisted I maintain a ComboBox databind. As many of you know data binding has changed a bit in WPF from your standard application. I created a property to bind the ComboBox to. I set the DataContext of the page to itself, which I like to do. It lets me expose various properties and quickly bind to them. Have a great weekend!

XAML
—-
        <ComboBox
            Height=”23″
            HorizontalAlignment=”Left”
            Margin=”10,10,0,0″
            Name=”comboBox1″
            VerticalAlignment=”Top”
            Width=”120″
            ItemsSource=”{Binding MyDataColumns}”
            DisplayMemberPath=”ColumnName”
            />
 
CODE BEHIND
—-
 
public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
        LoadData();
        DataContext = this;
    }
 
    private DataTable _dataTable = null;
 
    private void LoadData()
    {
        SqlConnection cn = null;
        SqlCommand cmd = null;
        SqlDataAdapter adapter = null;
        DataSet dataSet = null;
 
        try
        {
            cn = new SqlConnection(“Data Source=MyMachine;Initial Catalog=MyDb;Integrated Security=True”);
            cmd = new SqlCommand(“select top 1 * from MyTable”, cn);
            adapter = new SqlDataAdapter(cmd);
            dataSet = new DataSet();
 
            adapter.Fill(dataSet);
 
            _dataTable = dataSet.Tables[0];
        }
        finally
        {
            if (cmd != null)
                cmd.Dispose();
 
            if (adapter != null)
                adapter.Dispose();
 
            if (dataSet != null)
                dataSet.Dispose();
 
            if (cn != null)
                cn.Dispose();
        }           
    }
 
    public IEnumerable MyDataColumns
    {
        get
        {
            return (IEnumerable)_dataTable.Columns;
        }
    }
}



Viewing all articles
Browse latest Browse all 48

Latest Images

Trending Articles



Latest Images