Click to See Complete Forum and Search --> : Problem searching a Table


dovobet
December 13th, 2009, 09:57 AM
Hi

I am having a problem with the code below
private void surnameBox_Leave(object sender, EventArgs e)
{
string criteria = surnameBox.Text;
try
{
SqlCommand filterAccounts = new SqlCommand
("SELECT * FROM Accounts WHERE Surname = @criteria", connectionLine);
reader = filterAccounts.ExecuteReader();
while (reader.Read())
{
MessageBox.Show("1");
filterBox.Items.Add(reader.GetString(3).ToString() + ", " + reader.GetString(4).ToString());
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
connectionLine.Close();
}

Basically I want the matching records to be added to a listbox that exists on the same form as the textbox does. However, nothing appear in the textbox. The messagebox showing that the code has entered the while loop also does not appear... I am unsure whether it is my SQL statement that is wrong or not. Any help is much appreciate:)

kristof1104
December 13th, 2009, 11:18 AM
try
SqlCommand filterAccounts = new SqlCommand
("SELECT * FROM Accounts WHERE Surname = '"+ criteria +"', connectionLine);

also.. is your connection open before you execute the code?

greetz
Kristof

dovobet
December 13th, 2009, 06:18 PM
Thank you that worked perfectly, you rock Kristoff:)
Another note for anyone with the same problem is to use varchar(MAX) when trying to use a "select from where" with a field in a Table.

kristof1104
December 14th, 2009, 04:36 AM
Gladd I could help :)

greetz kristof