I have datagridview binding data from datatable. When I checked the number of columns of datatable, it returned 10. However, datagridview got an error when showing more than 8 columns. The error is Index was out of range. Must be non-negative and less than the size of the collection .Below is my code and also an error I got. Please help me!
public void SearchPatient(string query)
{
MySqlConnection MysqlConnection = new MySqlConnection(Properties.Settings.Default.connectionString);
MySqlCommand MysqlCmd = new MySqlCommand(query, MysqlConnection);
MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
MyAdapter.SelectCommand = MysqlCmd;
DataTable dTable = new DataTable();
MyAdapter.Fill(dTable);
rows = dTable.Rows.Count;
MessageBox.Show(rows + " " + dTable.Columns.Count); // It showed 15 and 10
dataGridView1.DataSource = dTable;
dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
dataGridView1.ColumnHeadersDefaultCellStyle.Font = new Font(dataGridView1.ColumnHeadersDefaultCellStyle.Font, FontStyle.Bold);
dataGridView1.Columns[0].HeaderText = "ID";
dataGridView1.Columns[1].HeaderText = fullname;
dataGridView1.Columns[2].HeaderText = birthday;
dataGridView1.Columns[2].DefaultCellStyle.Format = "dd/MM/yyyy";
dataGridView1.Columns[3].HeaderText = gender;
dataGridView1.Columns[4].HeaderText = address;
dataGridView1.Columns[5].HeaderText = phonenumber;
dataGridView1.Columns[6].HeaderText = cmnd;
dataGridView1.Columns[7].HeaderText = note;
dataGridView1.Columns[8].HeaderText = "ID benh nhan"; // Error: Additional information: Index was out of range. Must be non-negative and less than the size of the collection.
}
And my query is: SELECT * FROM patientdatabase ORDER BY ID DESC LIMIT 0,15
