简体   繁体   中英

c# search ms access db by ID

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM