private void Filtriraj()
{
string filter = string.Empty;
if (txtID.Text.Length > 0)
{
filter = "ID LIKE '%" + txtID.Text + "%'";
}
if (txtName.Text.Length > 0)
{
filter = "Name LIKE '%" + txtName.Text + "%'";
}
}
I want to search thru ms access db tables in my c# app. The one above is connected to "Table1" that has some fields like ID, name, 开发者_开发知识库surname, address...ID type is set to autonumber, all others are to text. I'm able to search all fields except by ID, this way above wont work, i get exception when i try to search by ID (I type in txtbox some ID number that is in db, exmp: '1') Search by txtName is working fine.
Autonumber is some form of number (long I think) so you can't use the LIKE keyword. You must search for an exact match (or greather than, less than etc.). You also can't surround a number with single quotes, so those will need to be removed.
I'd switch your code to something like this:
.
.
.
if (txtID.Text.Length > 0)
{
int id;
if (Int32.TryParse(txtID.Text, out id))
{
filter = "ID = " + id.ToString();
}
}
.
.
.
Also, your code looks like it may not work properly if you have multiple text boxes filled with data (because you are not using else if). Whatever text box you check last will end up being the filter that gets used because you're reassigning the filter variable each time. And if you're using the filter text directly from the text boxes, you're opening yourself up to possible SQL Injection. You should probably look into using parameterized queries.
精彩评论