Reputation: 108
I can't get data from a table to a listbox. I try to make a query to search book by name and place it to listbox but its always return Book not available, I don't know exactly what's wrong with my code. Here's the code:
try
{
conn.Open();
_listbox.Items.Clear();
SqlCeCommand cmd = new SqlCeCommand("SELECT * FROM buku WHERE nama LIKE '%@bookname%'", conn);
cmd.Parameters.Add("@bookname", _search);
SqlCeDataReader r = cmd.ExecuteResultSet(ResultSetOptions.Scrollable);
if (r.HasRows)
{
while (r.Read())
{
_listbox.Items.Add(r[0].ToString());
}
}
else
{
_listbox.Items.Add("Book Not Available");
}
}
I tried to make a query like this:
SqlCeCommand cmd = new SqlCeCommand("SELECT * FROM buku WHERE nama LIKE '%'+@bookname+'%'", conn);
Error message:
@bookname: Q - Input string was not in a correct format.
Upvotes: 0
Views: 81
Reputation: 63065
do as below,
SqlCeCommand cmd = new SqlCeCommand("SELECT * FROM buku WHERE nama LIKE @bookname", conn);
cmd.Parameters.AddWithValue("@bookname", "%"+ _search+ "%");
Upvotes: 0
Reputation: 14389
try:
SqlCeCommand cmd = new SqlCeCommand("SELECT * FROM buku WHERE nama LIKE @bookname", conn);
cmd.Parameters.Add("@bookname","%"+ _search+"%");
Since you use parameters you don't have to quote the parameter.
Also since you only use the 1st field of the result, I would sugest to write you select like:
"SELECT fieldImInterestedIn FROM buku WHERE nama LIKE @bookname"
Upvotes: 2