The method GetData
in the following code works as long as I use valid column names, however, when trying to use a variable (query string parameter value) in the SQL query, I get empty results.
I am assuming I am not using the .AddWithValue
method properly. Am I not writing the SQL command properly, or does it have something to do with the code placement of the .AddWithValue
method call? Or something else I am missing?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.AspNet.FriendlyUrls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
namespace Koobek
{
public partial class WebForm6 : System.Web.UI.Page
{
string cat = "";
string getcat = "";
protected void Page_Load(object sender, EventArgs e)
{
var segments = Request.GetFriendlyUrlSegments();
int count = segments.Count;
if (segments.Count > 0)
cat = segments[0];
string getcat = Request.QueryString["cat"];
ListView1.DataSource = this.GetData();
ListView1.DataBind();
System.Diagnostics.Debug.WriteLine(getcat);
}
private DataSet GetData()
{
string conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string query = @"SELECT DISTINCT newcatdisplay, newclassdisplay, newclass, newcat FROM ejn_series WHERE newcat = @getcat ORDER BY newclassdisplay";
SqlCommand cmd = new SqlCommand(query);
cmd.Parameters.AddWithValue("@getcat", getcat);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
if (ds.Tables[0].Rows.Count == 0)
{
System.Console.WriteLine("empty");
}
return ds;
}
}
}
}
}
}