gpt4 book ai didi

c# - Winform Datagridview cellclick 错误 - 索引超出范围

转载 作者:行者123 更新时间:2023-11-30 14:23:58 24 4
gpt4 key购买 nike

我有一个简单的数据网格,其中列出了 SQLSERVER 表中的一堆记录。数据网格填充没有任何问题。我想单击一行并将相应的数据加载到我在它旁边创建的文本框中。到目前为止这么简单。

这是我的 cellclick 事件代码

    private void dataGridVieworderitems_CellClick(object sender, DataGridViewCellEventArgs e)
{
{
//try
//{
//if (dataGridVieworderitems.SelectedRows.Count > 0) // make sure user select at least 1 row
{
string jobId = dataGridVieworderitems.SelectedRows[0].Cells[0].Value + string.Empty;
string standpack = dataGridVieworderitems.SelectedRows[0].Cells[1].Value + string.Empty;
string description = dataGridVieworderitems.SelectedRows[0].Cells[2].Value + string.Empty;
string price = dataGridVieworderitems.SelectedRows[0].Cells[3].Value + string.Empty;
string itemType = dataGridVieworderitems.SelectedRows[0].Cells[4].Value + string.Empty;
string notes = dataGridVieworderitems.SelectedRows[0].Cells[5].Value + string.Empty;

labelidvalue.Text = jobId;
labelstandpackvalue.Text = standpack;
labeldescriptionvalue.Text = description;
textBoxprice.Text = price;
labeltypevalue.Text = itemType;
textBoxnotes.Text = notes;
}
//}
//catch (Exception)
//{
// MessageBox.Show("something went wrong!");
//}
}
}

我特意注释掉了 If 语句和 try catch block 来生成错误..我收到以下错误..

System.ArgumentOutOfRangeException was unhandled HResult=-2146233086 Message=Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index ParamName=index .... ...

它是 WINFORM 和 c#.. 数据 GridView 有数据.. 但它说索引超出范围。有人可以指出我正确的方向吗?

这就是我填充网格的方式

    public DataTable GetStaffCurrentOrderItems()
{
try
{
DataTable dtstaffcurrentorderlist = new DataTable();

string connString = System.Configuration.ConfigurationManager.ConnectionStrings["nav"].ConnectionString;
using (SqlConnection con = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand("select [ID],standpack as [Item], item_description as [Description], '$'+convert(varchar(5),price) as Price,item_type as [Item Type],notes as [Notes] from tbl_staff_orders_items", con))
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
dtstaffcurrentorderlist.Load(reader);
}
con.Close();
}
return dtstaffcurrentorderlist;
}
catch (Exception)
{
return null;
}
}

最佳答案

在您的 cellClick 事件处理程序中检查是否像这样处理空值

if (dataGridVieworderitems.CurrentCell == null ||
dataGridVieworderitems.CurrentCell.Value == null ||
e.RowIndex == -1) return;

这将解决您的问题,因为它会在单击 GridView 的单元格时检查所有可能的空值。如果有除 null 之外的任何内容,则 else 部分将为您获取数据。

希望对您有所帮助!

关于c# - Winform Datagridview cellclick 错误 - 索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42990943/

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