简体   繁体   中英

C# datagridView change the column indexes after delete some row?

I have datagridview object which connects to the Microsoft Access database. I add the "Delete" button programmatically to the object. the problem is after when deleting some rows, the indexes of columns change as shown below, can give any idea to solve this problem, please?

   void fillgrid()
{
     con.Open();
     OleDbDataAdapter da = new OleDbDataAdapter("select * from student_table order by 
ID", con);
     DataTable dt = new DataTable();
     da.Fill(dt);
     dataGridView1.DataSource = dt;
     var col5 = new DataGridViewButtonColumn();

     col6.Name = "Delete";
     col6.Text = "Delete";
     col6.UseColumnTextForButtonValue = true;

     if(dataGridView1.Columns.Count==3)
        dataGridView1.Columns.AddRange(new DataGridViewColumn[] { col5, col6 });
     con.Close();
}
// ID, Name, Age, DeleteButton indexes are the following
// 0 , 1   , 2  , 3

// Delete any student row
con.Open();
OleDbCommand cmd = new OleDbCommand("Delete from student_table where ID="+txtId.Text +" 
                   ", con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("IDataRecord Deleted ...");
fillgrid();

// DeleteButton, ID, Name, Age, indexes are (become) as the following
// 0           , 1 , 2   , 3

Tried to index the specific column by header name ["ID"] instead of number [index no] and the problem was solved.

Thanks dears for your comments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM