Click here to Skip to main content
15,564,321 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am getting data from database in manually created column of datagridview,When i get data from database and i try to add row in that datagridview it cause error as i mention in title.This is my code.

What I have tried:

C#
int col = dataGridView1.CurrentCell.ColumnIndex;
int row = dataGridView1.CurrentCell.RowIndex;
                
if (dataGridView1.CurrentRow.Index+1 == dataGridView1.Rows.Count)
{
   if (col < dataGridView1.Columns.Count - 1)
   {
      dataGridView1.CurrentCell = dataGridView1.Rows[row].Cells[col + 1];
      dataGridView1.Focus();
   }
   else if (col == dataGridView1.Columns.Count - 1)
   {
      dataGridView1.Rows.Add(1);
      dataGridView1.CurrentCell = dataGridView1.Rows[row].Cells[1];
      dataGridView1.Focus();
   }
}
Posted
Updated 5-Oct-19 11:07am
v3

Your datagridview is data bound, it means that it constructs itself from the datasource you provide to it.
You have two solutions:
  • Either you strip off the data binding and do the boilerplate code yourself.
  • Or you add a new record to the datasource and refresh the gridview => it will update itself with the new row.
 
Share this answer
 
When you link a data source such as a List or a DataTable to a DataGridView, you cannot add rows directly to the DGV, because that would leave it out of sync with it's data source, and it wouldn't "know" what to display when - or what to update the Database with should you require that.

Instead, update the datasource: add items to your List, or DataRows to your DataTable and invalidate the control to update the display if necessary.
 
Share this answer
 
Comments
Member 13608869 5-Oct-19 6:42am    
sir i am using same gridview for insert update and display. for e.g i firstly insert 3 rows of data in datagridview and save it into database then i want to update it i use display command for getting data in datagridview, i get 3 rows in datagridview which i insert in database.Now i want to insert one more row and want to update it by same datagridview.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900