WPF Combobox DataBound to a DataTable, Refresh automatically
I have one combobox
that I am databinding
to a DataTable
which is fetching the data from database as follows:
SqlDataAdapter adp = new SqlDataAdapter
(@"SELECT [CategoryID],[CategoryName]FROM [Northwind].[dbo].[Categories]",
@"Integrated Security=SSPI;Initial Catalog=Northwind;Data So开发者_运维知识库urce=AKSHAY-PC\SQLEXPRESS");
DataTable tbl = new DataTable();
adp.Fill(tbl);
cmbCities.ItemsSource = ((IListSource)tbl).GetList();
cmbCities.DisplayMemberPath = "[CategoryName]";
cmbCities.SelectedValuePath = "[CategoryID]";
When the table data is changed(added/removed rows), the combobox
does not get refreshed because IList
does not have the change notification built it.
Is there any way it can be made possible?
If it's not possible, is there any way to "refresh" the databinding so that the datatable
will fetch the data again. In this case, what I will do is execute the above code when the window is initialized and then refresh it again without needing to execute the same code again. Something like cmbCities.Data.Refresh()
.
Below code will clear and fill the combobox from your sql adapter when you click the corresponding buttons.
XAML:
<Window x:Class="TestApp.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel>
<ComboBox Name="cmbCities" />
<Button Content="Clear" Click="OnClear"/>
<Button Content="Fill" Click="OnFill"/>
</StackPanel>
</Window>
Code behind:
using System;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Windows;
namespace TestApp
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
_adp.Fill(_tbl);
cmbCities.ItemsSource = ((IListSource)_tbl).GetList();
cmbCities.DisplayMemberPath = "[CategoryName]";
cmbCities.SelectedValuePath = "[CategoryID]";
DataContext = this;
}
private void OnClear(object sender, RoutedEventArgs e)
{
_tbl.Clear();
}
private void OnFill(object sender, RoutedEventArgs e)
{
_adp.Fill(_tbl);
}
private DataTable _tbl = new DataTable();
private SqlDataAdapter _adp = new SqlDataAdapter(@"SELECT [CategoryID],[CategoryName]FROM [Northwind].[dbo].[Categories]", @"Integrated Security=SSPI;Initial Catalog=Northwind;Data Source=AKSHAY-PC\SQLEXPRESS");
}
}
精彩评论