Tony_Henrich
Tony_Henrich

Reputation: 44205

DataGridView.DataSource does not have new row from the grid (.NET)

I have a datagridview which is initially bound to an empty datatable. Then the first row is populated by setting values to the columns of the grid's CurrentRow.DataBoundItem row. I enter a new row manually by typing values in the last blank row. I hit a save button which does: DataTable dt = (DataTable)MyGrid.DataSource.......

I noticed the number of rows in dt is only 1 instead of the two showing in the grid. However if I hit the Enter key first on the row and then click save, the number of rows is 3. The two filled rows plus the new row caused by the Enter key.

How do I get the two rows placed in the datatable without hitting the Enter key? (I don't want to programmatically send an Enter keystroke)

I tried to call the EndEdit() and UpdateCellValue() to accept the new row but the datasource still shows only one row.

Upvotes: 1

Views: 1977

Answers (4)

Zaher Al-balawi
Zaher Al-balawi

Reputation: 11

if you are talking about windows Apllication as i think, you can just add ds.AcceptChanges();

 if (txtUserId.Text.Trim() != "" && txtPasswoed.Text.Trim() != "" && txtUserName.Text.Trim() != "")
            {
                DataRow r = ds.Tables[0].NewRow();
                r["userName"] = txtUserName.Text.Trim();
                r["ID"] = txtUserId.Text.Trim();
                r["Password"] = txtPasswoed.Text.Trim();
                ds.Tables[0].Rows.Add(r);

                ds.AcceptChanges();

                txtPasswoed.Clear();
                txtUserName.Clear();
                txtUserId.Clear();
            }

Upvotes: 1

Tony_Henrich
Tony_Henrich

Reputation: 44205

I had to add a binding source which the grid binds to instead of binding to a datatable.

Upvotes: 0

jr3
jr3

Reputation: 915

As Jason mentioned make sure you're rebinding the grid after you insert into your DataTable.

myGrid.DataSource = dt;
myGrid.DataBind(); <-----

Upvotes: 0

Julien Poulin
Julien Poulin

Reputation: 13025

I answered a similar question recently, you should use Form.Validate() to push data back to the underlying business object (your DataTable) before saving your changes to the database.

Upvotes: 0

Related Questions