C# – Add new Row to DataTable

cdatatablewpf

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);
    }
}

Best Answer

pls post your xaml or cs code where you bind the Itemssource.

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 }"/>

Refresh

this.MyView.Refresh();

EDIT: 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);