【发布时间】:2017-03-13 11:23:20
【问题描述】:
我正在尝试将数据从数据库输入到我的 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 \\--\--\Home\start2016\--\Visual Studio 2015\Projects\--\--\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:
【问题讨论】:
-
我已经有一段时间没有使用这种方法了,但是尝试将这个
dt = ds.Tables["TempTable"];更改为dt = ds.Tables[0];,看看它是否有效。 -
请显示完整的异常,最好也显示堆栈跟踪。
-
什么是 dgProducts 以及它是如何初始化的?
-
@ChristopherLake 谢谢你的回复。您的方法似乎与
dt = ds.Tables["TempTable"];相同。blue tops, 5, 10仍然输出到 DataGridView。 -
@DavidG 感谢您的评论。我已添加要求的信息。
标签: c# sql ms-access datagridview