gpt4 book ai didi

c# - 由于索引超出范围,无法设置列标题文本

转载 作者:太空宇宙 更新时间:2023-11-03 12:34:39 25 4
gpt4 key购买 nike

我有两个方法会在单击按钮后运行,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报错是“Index was out of range. Must be non-negative and less than the size of the collection”。

最佳答案

希望问题是:在调用 receiveHeader(); 方法时,网格的 dataSource 为 null 或少于 11 的几列,因为您正在使用 列 [10]。所以我建议你在为网格分配数据源之后调用该方法。确保查询返回至少 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();

关于c# - 由于索引超出范围,无法设置列标题文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41498155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com