简体   繁体   中英

How to Refresh ComboBox binding to a DB

I have a combo box populated using dataset table adapters. I have a textbox and a button next to it. Onclick of this button the textbox value is added to the database. I want to refresh my Combobox once any new entry has been made. I did my research and figured out that I will have to Create an ObservableCollection and fill it with the data from DB. But since I am using dataset all the classes for each of the table is already present.

Here is my code:

XAML

<ComboBox Name="service" SelectedValuePath="Id" DisplayMemberPath="Service" ></ComboBox>
<TextBox Name="txtTobeAdded"></TextBox>
<Button Name="add" Content="Add" Click="add_Click"></Button>

C#

public partial class Window3 : Window
{

    private SqlDatatsetTableAdapters.ServicesTableAdapter tableAdapterServices = new SqlDatatsetTableAdapters.ServicesTableAdapter();

    public Window3()
    {
        InitializeComponent();
        System.Data.DataView vw = tableAdapterServices.GetData().DefaultView;
        service.ItemsSource = vw;
        service.SelectedIndex = 0;
    }

    private void add_Click(object sender, RoutedEventArgs e)
    {
        tableAdapterServices.InsertQuery(txtTobeAdded.Text);
    }
}

try:

private void add_Click(object sender, RoutedEventArgs e)
{
    tableAdapterServices.InsertQuery(txtTobeAdded.Text);
    service.ItemsSource = tableAdapterServices.GetData().DefaultView;;
    service.SelectedIndex = 0;
}

Its a lazy solution pushing the values back into the combo box. If you would like to learn the way to do it using an observable collection you will have to look at data Binding and the MVVM design pattern. More Info Found here

your scenario : Whatever changes to the database must be reflected to the combobox..

solution 1 : just call the another form as ShowDialog() instead of Show() and as soon as the child form is closed bind the datasource of the combobox again. as u can query the database again and retrieve the data again.

solution 2 : Just have a static List and send the newly added value to the Parent form from the child form using the Parent constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM