Cristian Baciu Cristian Baciu - 2 years ago 92
SQL Question

C# .NET: read method of OleDbDataReader class won't run

I am building an intranet for my school project inside a form application using the .NET framework and the C# language. This function populates a data grid inside a form. However, the code inside the while structure won't run. I have gone step by step with the debugger, and I reckon the read() method of the "dr" object will not go trough my two inner joined tables, but when I press a button that i have set to show me how many books are there registered in the database, it works. I think there is something wrong with my SQL statement, by what I have searched on this site, but I did not manage to resolve the bug. Carti.Nota and Carti.Stoc are columns with the Number type inside a Microsoft Access 2013 Database.

private void PopulateGridBooks()
using (OleDbConnection connect = new OleDbConnection(ConfigurationManager.ConnectionStrings["LibrarieConectare"].ConnectionString))
OleDbCommand command = connect.CreateCommand();
command.Parameters.AddWithValue("@titlu", cautaTitlu.Text);
command.CommandText =
" SELECT Carti.IDCarte, Carti.Titlu, Carti.Editie, Carti.An, Carti.ISBN, Carti.Nota, Carti.IDAutor, Carti.Stoc, Edituri.NumeEditura " +
" FROM (Carti INNER JOIN Edituri ON Carti.IDEditura = Edituri.IDEditura) " +
" WHERE Titlu LIKE '%@titlu%'";
OleDbDataReader dr = command.ExecuteReader();
if (dr.HasRows)
while (dr.Read())
dataGridView1.Rows.Add(dr["IDCarte"], dr["Titlu"], dr["NumeEditura"], dr["Stoc"]);
catch (Exception ex)
MessageBox.Show("Eroare la populare data grid carti: " + ex.Message);

Answer Source

Think I found it - your parameter is wrong, you should not have an @ in the AddwithValue.


//Exclude the @ in the below. 
command.Parameters.AddWithValue("titlu", cautaTitlu.Text);

maybe move your parameter addition line to after the command text too.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download