Re: Binding a ListBox to a DataTable

From: Yura Korolev (dr.cab_at_mail.ru)
Date: 12/14/04


Date: Wed, 15 Dec 2004 02:14:22 +0300


"Scott" <Scott@discussions.microsoft.com> wrote in message
news:7136FA95-C08B-4CF7-9B61-C75C409C2D1B@microsoft.com...
>
>
> "Yura" wrote:
>
>> Try to set DisplayMember and Value member before DataSource:
>
> That let's me get the SelectedValue properly, but the SelectedItem doesn't
> come back in code properly still.

SelectedItem always returns current DataRow/DataRowView or object (if you
bind collection of objects) not SelectedValue

>
> Is it possible to re-bind? I have a second listbox that changes based on
> the first listbox's selection. My Debug.Print() shows that the table
> coming
> back has the new, changed values, but the ListBox doesn't update when I
> reassign the DataSource on the second ListBox.

Do not create new DataTable, just use the same.

using (SqlConnection conn = new SqlConnection(CONN_STR))
using (SqlDataAdapter da = new sqlDataAdapter("roboticSiteNames", conn)) {

    DataTable dt = lbSiteCode.DataSource as DataTable;
    if (dt == null) {

        dt = new DataTable();

        da.Fill(dt); // fill the table

        lbSiteCode.DisplayMember = dt.Columns[0].ColumnName;
        lbSiteCode.ValueMember = dt.Columns[1].ColumnName;

        lbSiteCode.DataSource = dt;
    }
    else
        da.Fill(dt);
}