索引超出范围必须为非负数并且小于集合的大小参数名称:索引

问题描述

| 在C#中从Visual Studio更新MysqL DataGridView只是一个小问题。下面的代码包含fillData();填充数据网格的方法。按钮代码中引发了Exception错误。该按钮的目的是将“已检查”字段从0替换为1,这意味着随后选中了“已检查”复选框。这可能是一个非常基本的问题,所以我可能会问更多问题,希望您能提供帮助。
public DataTable tb = new DataTable();
public MysqLDataAdapter a = new MysqLDataAdapter();

public void fillData()
{
    using (MysqLConnection c = new MysqLConnection(\"host=\"\";user=\"\";password=\"\"; database=\"\";\"))
    {
        c.open();                
        string strsql = \"SELECT DataID,Date,WhichMeal,HbA1C_Test,Carbohydrates,glucoseReading,InsulinUsed,InsulinType,ReviewedBy,Reviewed From PatientData WHERE username = \'\" + uname.Text + \"\';\";

        using (MysqLDataAdapter a = new MysqLDataAdapter(strsql,c))
        {
            a.Fill(tb);
            dataGridView2.DataSource = tb;
        }


private void button5_Click(object sender,EventArgs e)
{
    using (MysqLConnection c = new MysqLConnection(\"host=;user=;password= \"\"; database=\"\"))
    {
        try
        {
            string DataId =  dataGridView2.Rows[this.dataGridView2.SelectedRows[0].Index].Cells[\"DataID\"].Value.ToString();
            string Update = string.Format(\"UPDATE PatientData SET Reviewed = 1 WHERE DataID = {0}\",DataId);
            MysqLCommand command = new MysqLCommand(Update,c);

            c.open();
            command.ExecuteNonQuery();
            c.Close();
            tb.Clear();
            fillData();
        }
        catch (MysqLException ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }
}
    

解决方法

        您可以通过检查以下内容找到问题所在: 有多少个条目
this.dataGridView2.SelectedRows
this.dataGridView2.Rows
中有多少个条目?
this.dataGridView2.SelectedRows[0].Index
的价值是什么? 索引值大于这些集合之一中的有效条目数。     ,        我猜你的问题在这里:
.SelectedRows[0]
运行此代码时,您是否可以验证
.SelectedRows
属性的
Count
是否等于1? 附带说明一下,以下表达式:
dataGridView2.Rows[this.dataGridView2.SelectedRows[0].Index]
...似乎不必要地复杂。可以用它代替吗?
this.dataGridView2.SelectedRows[0]
    ,        您的问题在于此行:
string DataId =  dataGridView2.Rows[this.dataGridView2.SelectedRows[0].Index].Cells[\"DataID\"].Value.ToString();
您试图在没有记录的地方插入记录。解决此问题的方法是尝试先在行中插入一些虚拟数据,然后用实际数据覆盖它。     ,        我在处理gridview内的按钮事件时遇到了此类问题。我的解决方案是:
if (e.ColumnIndex == 0 && e.RowIndex >=0)
{
  //condition here
}