我有来自datagridview
的{{1}}个绑定数据。当我检查datatable
的列数时,它返回10.但是,datatable
在显示超过8列时出错。错误是datagridview
。这是我的代码,也是我得到的错误。请帮帮我!
Index was out of range. Must be non-negative and less than the size of the collection
我的问题是: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.
}
答案 0 :(得分:1)
看起来在设计器中添加了列,并且DataGridView的AutoGenerateColumns设置为false。 由于您的列数与您的数据源不匹配,因此您收到此错误。
要解决此问题,