数据库中获取数据始终显示第一个记录
当我在搜索框中搜索不同的建筑号码时,它总是在表中显示第一个记录。 当我尝试使用分化的建筑号码时,它确实显示了它始终保持表格的第一条记录。
任何人都可以纠正我的代码吗?谢谢。
private void button3_Click(object sender, EventArgs e)
{
OleDbConnection con2 = new OleDbConnection(@"provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\Users\test\TDB.accdb");
try
{
con2.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con2;
string query = "select * from TestDatabase where Building_No='" + textBox1.Text + "'";
cmd.CommandText = query;
cmd.Parameters.AddWithValue("@Building_No", textBox1.Text);
cmd.Parameters.AddWithValue("@Building_Name", textBox4.Text);
cmd.Parameters.AddWithValue("@Year_", textBox2.Text);
OleDbDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
textBox4.Text = reader["Building_Name"].ToString();
textBox2.Text = reader["Year_"].ToString();
}
}
catch (Exception)
{
MessageBox.Show("No Reference # found!", "Error");
textBox4.Clear();
textBox2.Clear();
}
}
When i search differennt building number in search box it always display first record in the table.
When i tried diffrent building number it does now display it always stay first record of the table.
Can anybody correct my code. Thanks.
private void button3_Click(object sender, EventArgs e)
{
OleDbConnection con2 = new OleDbConnection(@"provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\Users\test\TDB.accdb");
try
{
con2.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con2;
string query = "select * from TestDatabase where Building_No='" + textBox1.Text + "'";
cmd.CommandText = query;
cmd.Parameters.AddWithValue("@Building_No", textBox1.Text);
cmd.Parameters.AddWithValue("@Building_Name", textBox4.Text);
cmd.Parameters.AddWithValue("@Year_", textBox2.Text);
OleDbDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
textBox4.Text = reader["Building_Name"].ToString();
textBox2.Text = reader["Year_"].ToString();
}
}
catch (Exception)
{
MessageBox.Show("No Reference # found!", "Error");
textBox4.Clear();
textBox2.Clear();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果“ oledbcommand.executereader”的结果是多行,
则必须调用oledbdatareader.read()多个。
例子:
e.g.
If the result of 'OleDbCommand.ExecuteReader' is multiple rows
You must call OleDbDataReader.Read() multiple.
example:
e.g.
可能是因为您没有关闭连接。您可以尝试以下代码吗?
It could be because you didn't close the connections. Can you try the code below?