由于索引超出范围,因此无法设置列标题文本

时间:2017-01-06 02:49:46

标签: c# sql datagridview

我点击按钮bgEqptRec()receiveHeader()后会运行两种方法。 bgEqptRec()包含设置列标题标题的recieveHeader()。但由于指数超出范围,因此无法设定。我很确定我使用的是SQL Server中正确数量的索引。这是代码:

private void btnSearch_Click(object sender, EventArgs e)
{
        bgEqptRec();
}

private void bgEqptRec()
        {
            receiveHeader();
            gvSearch.DataSource = null;
            using (var connect = connection.getConnection())
            {
                using (SqlCommand cmd = new SqlCommand("SELECT * FROM receive WHERE rec_stat='IN' AND rec_date BETWEEN '" + dtpFrom.Text + "' AND '" + dtpTo.Text + "'"))
                {
                    cmd.Connection = connect;
                    cmd.CommandType = CommandType.Text;
                    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                    {
                        using (DataTable dt = new DataTable())
                        {
                            da.Fill(dt);
                            gvSearch.DataSource = dt;
                        }
                    }
                }
            }
        }

private void receiveHeader()
        {
            gvSearch.Columns[0].HeaderText = "Supplier";
            gvSearch.Columns[1].HeaderText = "Invoice";
            gvSearch.Columns[2].HeaderText = "Brand";
            gvSearch.Columns[3].HeaderText = "Model";
            gvSearch.Columns[4].HeaderText = "Equipment";
            gvSearch.Columns[5].HeaderText = "Serial No.";
            gvSearch.Columns[6].HeaderText = "Price";
            gvSearch.Columns[7].HeaderText = "PO No.";
            gvSearch.Columns[8].HeaderText = "Release Date";
            gvSearch.Columns[9].HeaderText = "Release By";
            gvSearch.Columns[10].HeaderText = "Status";
        }

VS给出的错误是“索引超出范围。必须是非负数且小于集合的大小。”

1 个答案:

答案 0 :(得分:1)

希望问题在于:在调用receiveHeader();方法的时候,网格的dataSource要么为空,要么少于11列,因为你正在使用Columns[10]。所以我建议你在为Grid分配DataSource之后调用该方法。确保查询返回至少11列。这意味着代码将是这样的:

using (var connect = connection.getConnection())
{
   using (SqlCommand cmd = new SqlCommand("SELECT * FROM receive WHERE rec_stat='IN' AND rec_date BETWEEN '" + dtpFrom.Text + "' AND '" + dtpTo.Text + "'"))
   {
      // rest of code
      gvSearch.DataSource = dt;
    }
}
// call the method here since the grid is populated

receiveHeader();