Reputation: 5866
I am trying add a new row into datagridview with the button click for learning purposes. When I click the button, it deletes the old data and add the new row. But I want to append it to the grid
here is my form_load function which gets the data from the database and fill the grid.
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection("Data Source=ARIF-BILGISAYAR;Initial Catalog=RotanetLocal;Persist Security Info=True;User ID=sa;Password=12345");
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM TestTable", connection);
DataSet sourceDataSet = new DataSet();
adapter.Fill(sourceDataSet);
gridControl1.DataSource = sourceDataSet.Tables[0];
}
and here is my button event which is supposed to append a row into the grid, but it deletes the old data and inserts the new one
private void btn_update_Click(object sender, EventArgs e)
{
DataTable dtOperation = new DataTable();
var myOriginalDataSource = (DataTable)gridControl1.DataSource;
var dr = myOriginalDataSource.NewRow();
dr["id"] = 1;
dr["name"] = "Gelen Havale";
dr["lname"] = "Gelen Havale";
dtOperation.Rows.Add(dr);
gridControl1.Refresh();
}
my btn_update_click function is now trying to create a row and append it to the old data. but it now crashes. It says taht this row belongs to another table. how can I fix that?
Upvotes: 0
Views: 3204
Reputation: 10208
It looks like you are completely replacing the DataSource property which will tell the control to completely re-render.
Add the new row to the existing DataSource and then call the Refresh()
method.
On the other-hand if you are using WPF move away from using DataTable
and start using an ObservableCollection<T>
instead.
private void btn_update_Click(object sender, EventArgs e)
{
var myOriginalDataSource = gridControl1.DataSource;
var dr = myOriginalDataSource.NewRow();
dr["id"] = 1;
dr["name"] = "Gelen Havale";
dr["lname"] = "Gelen Havale";
gridControl1.Refresh();
}
The Refresh()
is psudocode as I don't know the DevExpress WinForms controls very well.
Upvotes: 1
Reputation: 10208
You need to change your code to this:
private void btn_update_Click(object sender, EventArgs e)
{
var myOriginalDataSource = (DataTable)gridControl1.DataSource;
var dr = myOriginalDataSource.NewRow();
dr["id"] = 1;
dr["name"] = "Gelen Havale";
dr["lname"] = "Gelen Havale";
gridControl1.Refresh();
}
I think it would be worth spending some time reading up on Object Orientation Principles
You were still creating a new DataTable
needlessly and adding the row to that instance rather than the DataTable
already data-bound to your grid control instance.
Upvotes: 1