循环包含多行的数据库结果
我正在开发一个新项目。它使用访问数据库,在之前的帮助下,我能够搜索多行。问题是,搜索仅检查数据库中最后一个字段是否匹配。我想我需要对每一行使用一个 for 循环。我在下面尝试过这个。然而我遇到的问题是:
使用未分配的局部变量“returnedRows”
我不知道如何修复它,也不知道我的代码是否接近实现这一目标。
private void btnSearch_Click(object sender, EventArgs e)
{
string searchFor = txtSearch.Text;
int results = 0;
DataRow[] returnedRows;
results = returnedRows.Length;
if (results > 0)
{
for (int i = 0; i < results; i++)
{
DataRow dr1;
dr1 = returnedRows[i];
for (int j = 0; j < results; j++)
{
DataRow dr2;
dr2 = returnedRows[j];
returnedRows = ds1.Tables["Laptops"].Select("Memory='" + searchFor + "' and HD='" + searchFor + "'");
}
MessageBox.Show("Maker - " + (dr1[1].ToString() + "\n" + "Model - " + (dr1[2].ToString() + "\n" + "Current Price - £" + (dr1[3].ToString()))));
}
}
else
{
MessageBox.Show("No such item");
}
}
I am working on a new project. It uses an access database and with help from here previously I was able to search on more than one row. The trouble is, the search only checks the last field in the database for matches. I think I need to use a for loop for each row. I have tried this below. The problem I get however is:
Use of unassigned local variable 'returnedRows'
I do not know how to fix it or if my code is even close to achieving this.
private void btnSearch_Click(object sender, EventArgs e)
{
string searchFor = txtSearch.Text;
int results = 0;
DataRow[] returnedRows;
results = returnedRows.Length;
if (results > 0)
{
for (int i = 0; i < results; i++)
{
DataRow dr1;
dr1 = returnedRows[i];
for (int j = 0; j < results; j++)
{
DataRow dr2;
dr2 = returnedRows[j];
returnedRows = ds1.Tables["Laptops"].Select("Memory='" + searchFor + "' and HD='" + searchFor + "'");
}
MessageBox.Show("Maker - " + (dr1[1].ToString() + "\n" + "Model - " + (dr1[2].ToString() + "\n" + "Current Price - £" + (dr1[3].ToString()))));
}
}
else
{
MessageBox.Show("No such item");
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种方法是使用读取器对象。以下是一些很好的链接:
http: //msdn.microsoft.com/en-us/library/haa3afyz%28v=vs.71%29.aspx
http://www.java2s.com/Code/CSharp/Database-ADO .net/UseADataReader.htm
但是无论您最初的问题是什么,您绝对总是需要在使用任何数组之前对其进行初始化(甚至是为了获取“长度”)。
One approach is to use a reader object. Here are some good links:
http://msdn.microsoft.com/en-us/library/haa3afyz%28v=vs.71%29.aspx
http://www.java2s.com/Code/CSharp/Database-ADO.net/UseADataReader.htm
But regardless of your initial question, you absolutely ALWAYS need to initialize any array before you use it (even to get "Length").