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();
}
}
CodePudding user response:
If the result of 'OleDbCommand.ExecuteReader' is multiple rows
You must call OleDbDataReader.Read() multiple.
example:
while (reader.Read())
{
Console.WriteLine(reader["Building_Name"].ToString());
}
e.g.
textBox4.Text = "";
while (reader.Read())
{
textBox4.Text = reader["Building_Name"].ToString() ",";
}
CodePudding user response:
It could be because you didn't close the connections. Can you try the code below?
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();
}
reader.Close();
cmd.Dispose();
con2.Close();
}
catch (Exception)
{
MessageBox.Show("No Reference # found!", "Error");
textBox4.Clear();
textBox2.Clear();
}
}