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

C# - Datagridview cannot bind data from datatable

我有 datagridview 来自 datatable 的绑定数据。当我检查datatable的列数时,它返回10。但是,datagridview显示超过8列时出错。错误是 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.

    }

这是我的数据库:

我的查询是:SELECT * FROM patientdatabase ORDER BY ID DESC LIMIT 0,15

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

要解决这个问题,

  1. 在设计器中添加列以匹配数据源
  2. 或者,将 dataGridView1.AutoGenerateColumns 设置为 True

在此处查看参考资料:https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.autogeneratecolumns(v=vs.110).aspx