简体   繁体   中英

SqlCommand AddWithValue and if statements issue with gridview

I am trying to build a web form that uses SQL queries to help populate various dropdowns and display results in gridviews, the issue i'm having at the moment is getting the user input to replace varibles in the SQL query.

My query is as follows:

SELECT TOP 50 
    'Select' AS 'Select',
    id_ref AS 'Number',
    created_date AS 'Date Created',
    address 'Address', 
    category AS 'Category',
    borough 
FROM Events 
WHERE location_address LIKE '%%' 
    AND borough @borcond 
    AND admin_ref @stacond 
    AND id_ref @Numcond 
    AND category @cat 
    AND created_date @startDate 
    AND created_date @endDate 
    AND address LIKE @Addresscond 
ORDER BY id_todays_date DESC

My C# code is as follows:

public void SQLQueryv2(
    string AddressSel, 
    string startDateSel, 
    string endDateSel, 
    string incidentSel, 
    string borsel, 
    string stasel, 
    string numsel)
{
    //this is filled in really
    SqlConnection Connection = new SqlConnection(
        "Data Source=;Initial Catalog=;User=;Password=;");
    string sqlquery = <<as above>>

    try
    {
        SqlCommand Command = new SqlCommand(sqlquery, Connection);
        Connection.Open();

        if (borsel == "Select Borough") 
        { 
            Command.Parameters.AddWithValue("@borcond", " = IS NOT NULL "); 
        } 
        else 
        { 
            Command.Parameters.AddWithValue("@borcond","= " + "'" + borsel + "'"); 
        }
        if (stasel == "Select Town") 
        { 
        Command.Parameters.AddWithValue("@stacond", " = IS NOT NULL "); 
        } 
        else 
        { 
            Command.Parameters.AddWithValue("@borcond","= "+ "'" + borsel + "'"); 
        }
        if (startDateSel == "") 
        { 
            Command.Parameters.AddWithValue("@startDate", " = IS NOT NULL"); 
        } 
        else 
        { 
            Command.Parameters.AddWithValue(
                "@startDate", 
                ">= CONVERT(datetime," + "'" + startDateSel + "'" + ",103)"); 
        }
        if (endDateSel == "") 
        { 
            Command.Parameters.AddWithValue("@endDate", " = IS NOT NULL"); 
        } 
        else 
        { 
            Command.Parameters.AddWithValue(
                "@endDate", 
                ">= CONVERT(datetime," + "'" + endDateSel + "'" + ",103)"); 
        }
        if (incidentSel == "Select Category") 
        { 
            Command.Parameters.AddWithValue(
                "@cat", 
                " in ('cat a','cat b','cat c')"); 
        } 
        else 
        {
            Command.Parameters.AddWithValue(
                "@cat",
                " AND category =" + "'" + incidentSel + "'"); 
        }
        if (AddressSel == "") 
        { 
            Command.Parameters.AddWithValue("@Addresscond", "%%"); 
        } 
        else 
        {
            Command.Parameters.AddWithValue("@Addresscond","%" + AddressSel + "%");
        }
        if (numsel == "") 
        { 
            Command.Parameters.AddWithValue("@Numcond", " = IS NOT NULL "); 
        } 
        else 
        { 
            Command.Parameters.AddWithValue("@Numcond", "= " + "'" + numsel + "'"); 
        }

         //use adapter to populate dataset...
        SqlDataAdapter DataAdapter = new SqlDataAdapter(sqlquery, Connection);
        DataTable DataTable = new DataTable();
        DataAdapter.SelectCommand = Command;
        DataAdapter.Fill(DataTable);

        //then bind dataset to the gridview
        GridView1.AutoGenerateColumns = true;
        GridView1.DataSource = DataTable;
        GridView1.DataBind();
        lblResults.Visible = true;
        lblResults.ForeColor = System.Drawing.Color.Green;
        lblResults.Text = "Your search has returned " 
            + Dataset.Tables[0].Select(
                "'Incident Number' IS NOT NULL").Length.ToString() 
            + " records.";
    }
    catch (Exception err)
    {
        lblResults.Visible = true;
        lblResults.ForeColor = System.Drawing.Color.Red;
        lblResults.Text = 
            "An error has occurred loading data into the table view. ";
        lblResults.Text += err.Message;
    }
}

When run, the Gridview doesn't populate and the query (when investigated) it still has the variables and not the 'is nulls' or user inputs.

I think its something to so with the IF statements but i'm entirely sure. I think i just need another pair of eyes on this, any help would be appreciated.

Bit more info: If i take out the sqlCommand bits it works perfectly with the IF statements, i'm trying to stop people from using malicious SQL queries.

What juhar said. You've got the wrong idea about parameters. They're parameters and not text substitution. Here's an example of a valid query:

Select firstname, lastname from contacts
where ssn = @ssn

And in your code you'd say

Command.parameters.AddWithValue("@ssn","123-45-6789")

This really isn't the correct way to use parameters. You should only assign values to them, not add comparison operators. Here's an example of how to "fix" your query for the @borcond parameter

...
AND ((@borcond = 'Select Borough' AND borough IS NOT NULL) 
    OR borough = @borcond)
...

Note: you don't need the equal sign with IS NOT NULL

And replace the if-else with

Command.Parameters.AddWithValue("@borcond", borsel);

You'll need to do similar changes for all of your parameters. The trick here is to basically move your if-else logic from the code into the sql query.

Additionally I don't think you need the location_address LIKE '%%' in your query as that just matches everything.

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