1

I'm trying to query a SQL Server database table based on a user variable (using ASP.NET and C#). I want to be able to pull just the user's unique records from the Waste Application Information table where the Farm Owner name is equal to the variable name (which is a string).

Here's part of my code:

conn.Open();
WasteAppData = "SELECT * FROM [WASTE APPLICATION INFORMATION] WHERE [FARM OWNER] = (user variable) ";

SqlCommand com = new SqlCommand(WasteAppData, conn);

GridView1.DataSource = com.ExecuteReader();
GridView1.DataBind();

If I replace the "(user variable)" with the actual value in the table column it does work correctly. Like this: 'Joe Smith' I've tried referencing the variable which is pulled from another webform with no luck... I think my syntax is incorrect? Any help would be great!

3
  • I've tried referencing the variable there's no such feature in .NET which means you tried to concatenate or inject the string in a SQL injection bug. Use parameterized queries instead. Commented Feb 23, 2021 at 16:41
  • You say "I've tried referencing the variable ... but that didn't work." Show us that code. Commented Feb 23, 2021 at 16:44
  • Also, give us the specific error message and/or behavior. There are many things that can cause a client-server database query to fail, so just saying that it didn't work isn't usually enough to figure out what went wrong. Commented Feb 23, 2021 at 16:47

1 Answer 1

1

You need to do it this way:

WasteAppData = "SELECT * FROM [WASTE APPLICATION INFORMATION] WHERE [FARM OWNER] = @FarmOwn";
using (SqlCommand cmdSQL = new SqlCommand(WasteAppData , conn)
 {
    cmdSQL.Parameters.Add("@FarmOwn", SqlDbType.NVarChar).Value = strFarmOwnwer;
    cmdSQL.Connection.Open();
    GridView1.DataSource = cmdSQL.ExecuteReader;
    GridView1.DataBind();
}

In this case "strFarmOwner" would be replaced with your actual variable that holds the value you want.

Sign up to request clarification or add additional context in comments.

1 Comment

Albert, That got me fixed! I really do appreciate it! I had a few other issues which I figured out as well...missing Namespaces, etc. This is the first day that I've used stackoverflow so I'm 1/1! Pretty good average. Have a great day!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.