Gridview search

Popa Cristian Valentin 1 Reputation point
2021-08-13T13:25:53.45+00:00

Hello,
i have a problem with my gridview, i have a string that shows me a result from a search box in another page, and i want to add sql "like" command to my string:

strSql = "select * from tbl_search where tx_search='" + Request.QueryString["selectedvalue"].ToString() + "'";

For sure i need a command parameter too, but i don't know how to write it and how to put sql "like" in this string.

Thank you!

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,254 questions
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,709 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,242 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Albert Kallal 4,651 Reputation points
    2021-08-13T16:37:14.963+00:00

    Ok, assuming this grid view:

    123181-image.png

    Ok, now we assume that some city will be passed - but as noted , we want "Like with %

    Our code could look like this:

           protected void Page_Load(object sender, EventArgs e)  
            {  
                if (!IsPostBack)  
                {  
                    LoadGrid(Request.QueryString["City"]);  
                }  
            }  
      
            void LoadGrid(string strCity = "")  
            {  
                using (SqlCommand cmdSQL = new SqlCommand("SELECT * FROM tblHotels",  
                                 new SqlConnection(Properties.Settings.Default.TEST3)))  
                {  
                    if ((strCity != "") & (strCity != null))  
                    {  
                        cmdSQL.CommandText += " WHERE City Like @City + '%' ";  
                        cmdSQL.Parameters.Add("@City", SqlDbType.NVarChar).Value = strCity;  
                    }  
                    cmdSQL.Connection.Open();  
                    GridView1.DataSource = cmdSQL.ExecuteReader();  
                    GridView1.DataBind();  
      
                }  
            }  
    

    and our output would now be say for passing Jasp this:

    123099-image.png

    So, I not only in above show how you use Like, but I also made it optional, so if nothing is passed, then all records show.

    but, the meat and potatoes part is the like - you have to add it to the sql as a + '%'

    But, we still have sql injection protection here - since we don't ever concatenate the passed value.

    Regards,

    Albert D. Kallal (Access MVP 2003-2017)
    Edmonton, Alberta Canada

    1 person found this answer helpful.
    0 comments No comments