C#DataGridView溢出错误



我正在尝试从数据库中输入数据到我的数据杂志表中。我遇到的问题是,我只能在溢出错误之前从数据库中检索并设置第一行数据。
这是我的代码:

string passedvalue = "Tops"
DataSet ds = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter();
DataTable dt = new DataTable();
string command = "SELECT ProductName,Price,Stock FROM Products WHERE Category = "" + passedvalue + """;
da = new OleDbDataAdapter(command, con);
da.Fill(ds, "TempTable");
dt = ds.Tables["TempTable"];

int count = 0;
foreach (DataRow row in dt.Rows)
{
    try
    {
        dgProducts.Rows[count].Cells[0].Value = row["ProductName"].ToString();
        dgProducts.Rows[count].Cells[1].Value = row["Price"].ToString();
        dgProducts.Rows[count].Cells[2].Value = row["Stock"].ToString();
    }
    catch (Exception) { }
    count++;
}

我的数据库如下:

ID,ProductName,Price,Stock,Category
0, blue top, 5, 10, Tops
1, green top, 6, 55, Tops
2, blue trousers, 4, 4, Trousers
3, red top, 5, 5, Tops  

当我运行代码时,

blue tops, 5, 10

在抛出错误之前将添加到表中。

我相信我包含了任何必需的信息,但是如果没有,请在下面对其进行评论,我会添加。

编辑:
DGProducts是DataGridView

this.dgProducts = new System.Windows.Forms.DataGridView();  

在表单中设计师

例外是:

    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
  Source=mscorlib
  StackTrace:
       at System.Collections.ArrayList.get_Item(Int32 index)
       at System.Windows.Forms.DataGridViewRowCollection.SharedRow(Int32 rowIndex)
       at System.Windows.Forms.DataGridViewRowCollection.get_Item(Int32 index)
       at program.productSelect.productSelect_Load(Object sender, EventArgs e) in \----Homestart2016--Visual Studio 2015Projects----productSelect.cs:line 54
       at System.Windows.Forms.Form.OnLoad(EventArgs e)
       at System.Windows.Forms.Form.OnCreateControl()
       at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
       at System.Windows.Forms.Control.CreateControl()
       at System.Windows.Forms.Control.WmShowWindow(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       at System.Windows.Forms.Form.WmShowWindow(Message& m)
       at System.Windows.Forms.Form.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
  InnerException:

我是新手使用数据库和网格视图的新手,我不知道

dgProducts.DataSource = dt;

自我注释:更多研究。
感谢您的帮助!

在WindowsForm上选择DataGridView Tool,右键单击,选择属性,在解决方案资源管理器中找到选择模式。并将值设置为FullRowselect ...问题必须解决..

最新更新