cost
cost

Reputation: 4480

Why isn't my databinding working?

Trying out databinding for the first time, but something isn't working. I'm trying to populate a combobox with the list of items in this database column. My dataset ds shows that it has stuff in it (the debugger shows it has a count of about 1500, the number of items that should be in there) and if I use the same connection string with a reader, I can print out all of the things that should be appearing in the combobox. Though the combobox is coming up empty, any ideas?

<ComboBox Height="23" HorizontalAlignment="Left" Margin="24,318,0,0" Name="comboBox2" VerticalAlignment="Top" Width="190" IsEditable="True" >
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding clt}" Width="100" />
                </StackPanel>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

And now the C#

DataSet ds = new DataSet();

        string con_string = "user id=sql;password=pass;Server=xxx.xxx.xxx.xxx,xxxx;Database=db;Trusted_Connection=False;connection timeout=15";
        string command_string = "SELECT clt FROM Client";
        SqlConnection sql_con = new SqlConnection(con_string);

            SqlCommand command = new SqlCommand(command_string, sql_con);
            SqlDataAdapter sqlDa = new SqlDataAdapter();
            sqlDa.SelectCommand = command;
            sqlDa.Fill(ds);
            comboBox2.DataContext = ds.Tables[0].DefaultView;

All of the code executes without any exceptions.

Upvotes: 1

Views: 149

Answers (2)

Sukanya
Sukanya

Reputation: 1061

Write this code:-

    SqlDataAdapter sqlDa = new SqlDataAdapter(command_string,sql_con);
        sqlDa.Fill(ds);

        comboBox2.DataSource = ds.Tables[0];
        comboBox2.DisplayMember = "clt";

This will display result.

Upvotes: 0

Louis Kottmann
Louis Kottmann

Reputation: 16628

Either add ItemsSource="{Binding}" in the XAML declaration of your combobox (prefered way)

Or do comboBox2.ItemsSource = ds.Tables[0].DefaultView; (quite goofy, but it does work)

That said, please note that this is not the best practice. You should have a ViewModel that holds the data specific for a view, and its logic through commands.

That ViewModel needs to implement INotifyPropertyChanged if you're gonna bind against it. Typically, you'd have an ObservableCollection in that ViewModel, and you'd fill it with the result from your query. Then you'd bind on it.

Upvotes: 1

Related Questions