Search code examples
c#sqlasp.netselectcommand

Having trouble using SelectCommand to select values in SQL database (C#)


So in an application I'm making, I have a selectCommand that is supposed to read the text within a textbox on a button click, and filters search results based off of the value.

Select command is.

SelectCommand="SELECT (bunch of columns) WHERE members.LastName LIKE '%@Ln%';

The value of @Ln is retrieved from code behind here:

public void searchButtonClick(object sender, EventArgs e)
    {
        SqlDataSource1.SelectParameters.Clear();
        SqlDataSource1.SelectParameters.Add("Ln", inputLastName.Text);        
    }

My goal is to select all records with last names containing whatever was entered into the last name text box. For example, I want "Mar", "Martinez", or a blank text box to all select somebody with the last name Martinez. A blank text box should select all last names.

But I believe my problem lies in the syntax of the SelectCommand. I've tested it without the single quotation marks, and many other variances of it to no avail. If I leave just "WHERE members.LastName LIKE @Ln", it selects records where the last name is the exact value of inputLastName.Text, but as I mentioned, that's not what I'm looking for. :(

I'm new to coding so please try to explain as clearly as possible, sorry if my problem was not articulated in the best way. Thank you in advance!


Solution

  • Dont forget the "@" in SqlDataSource1.SelectParameters.Add("@Ln",... and change your SelectCommand to:

    SelectCommand="SELECT (bunch of column) WHERE members.LastName LIKE @Ln";
    
    SqlDataSource1.SelectParameters.Add("@Ln", '%' +  inputLastName.Text + '%');
    

    so it should work.