C# - Datagridview无法绑定数据表中的数据

时间:2018-03-05 03:22:18

标签: c# datagridview datatable indexoutofrangeexception

我有来自datagridview的{​​{1}}个绑定数据。当我检查datatable的列数时,它返回10.但是,datatable在显示超过8列时出错。错误是datagridview。这是我的代码,也是我得到的错误。请帮帮我!

Index was out of range. Must be non-negative and less than the size of the collection

这是我的数据库: enter image description here

我的问题是: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. }

1 个答案:

答案 0 :(得分:1)

看起来在设计器中添加了列,并且DataGridView的AutoGenerateColumns设置为false。 由于您的列数与您的数据源不匹配,因此您收到此错误。

要解决此问题,

  1. 在设计器中添加列以匹配数据源
  2. 或者,将dataGridView1.AutoGenerateColumns设置为True
  3. 请参阅此处的参考:https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.autogeneratecolumns(v=vs.110).aspx