向数据表添加新行 [英] Add new Row to DataTable
问题描述
我有一个 DataGrid
绑定到一个带有一个表和一个列(FooTable 和 FooName)的数据库.使用下面的代码,我可以将 DataGrid
绑定到 DataTable
并显示数据库数据.但是,当我每次通过 DataSet_Add_Click()
添加新行时,DataGrid
不会添加任何内容.虽然我已经通过 ItemsSource
将 DataTable
绑定到 DataGrid
,但是向 DataTable 添加新行不会向 DataGrid 添加行.为什么?
I have a DataGrid
bind to a database with one Table and one Column (FooTable and FooName).
With my following code, I can bind DataGrid
to DataTable
and display database data. But when each time I add a new row by DataSet_Add_Click()
, nothing gets added to the DataGrid
. I though I have bind DataTable
to DataGrid
through ItemsSource
, but adding new row to DataTable doesn't add row to DataGrid. Why?
public partial class MainWindow : Window
{
SqlCeConnection conn = new SqlCeConnection();
/* Define the Connection String */
string connString;
DataGrid dg1 = new DataGrid();
DataTable dt = new DataTable();
public MainWindow()
{
InitializeComponent();
connString = @"...";
SqlCeConnection conn = new SqlCeConnection(connString);
conn.Open();
SqlCeDataAdapter da = new SqlCeDataAdapter();
string sqlStr = @"SELECT * FROM FooTable";
da.SelectCommand = new SqlCeCommand(sqlStr, conn);
DataSet ds = new DataSet();
da.Fill(ds, "FooTable");
dt = ds.Tables["FooTable"];
dg1.ItemsSource = ds.Tables;
DataRow newRow = dt.NewRow();
newRow["FooName"] = "Mary";
dt.Rows.Add(newRow);
CreateDataGrid();
}
public struct DataItem1
{
public string FooName { get; set; }
}
private void CreateDataGrid()
{
DataGridTextColumn col = new DataGridTextColumn();
col = new DataGridTextColumn();
col.Binding = new Binding("FooName");
col.Header = "FooName";
dg1.Columns.Add(col);
/* dataGrid1 exist in XAML and is a parent of the DataGrid */
dataGrid1.Children.Add(dg1);
}
private void DataSet_Add_Click(object sender, RoutedEventArgs e)
{
DataRow newRow2 = dt.NewRow();
newRow2["FooName"] = "Mary";
dt.Rows.Add(newRow2);
}
}
推荐答案
请在绑定 Itemssource 的地方发布您的 xaml 或 cs 代码.
pls post your xaml or cs code where you bind the Itemssource.
您的 DataSet_Add_Click 是否将行添加到您的数据表中?如果是,那么它似乎只是您的数据网格的刷新/绑定问题.
does your DataSet_Add_Click add the row to your datatable? if yes then it seems is just a refresh/binding problem with your datagrid.
当我使用数据表和数据网格时,我总是使用以下内容
when i work with datatables and datagrid i always use the following
//ctor or init
dt = ds.Tables["FooTable"];
//the next line you have to write after you initialize your datatable
this.MyView = (BindingListCollectionView)CollectionViewSource.GetDefaultView(this.dt);
XAML
<DataGrid ItemsSource="{Binding MyView }"/>
刷新
this.MyView.Refresh();
MyView 是一个属性
MyView is a property
public BindingListCollectionView MyView
{
get {return this._myview;}
set {this._myview = value; OnPropertyChanged("MyView");
}
您可以在代码中进行绑定.
you can do binding in code.
Binding myBinding = new Binding("MyView");
myBinding.Source = this;//the instance with the MyView property
mydatagridctrl.SetBinding(ItemsControl.ItemsSourceProperty, myBinding);
这篇关于向数据表添加新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!