Am struggling to use SQL parameters for C# \ ASP.Net, not used C# with ASP.Net much so quite new to it, I have a web page with a dropdown box (drpdSerType) and a text box (txtRNumSer) and a button, the button code is below...
If I don't use the parameters as seen the commented code then it works fine...
try
{
SqlConnection con = new SqlConnection();
SqlDataAdapter sda = new SqlDataAdapter();
DataTable dt = new DataTable();
con.ConnectionString = "Server=server1;Database=db1;Integrated Security=True";
sda.SelectCommand.Parameters.AddWithValue("@I", drpdSerType.SelectedValue.ToString());
sda.SelectCommand.Parameters.AddWithValue("@S", txtRNumSer.Text);
sda = new SqlDataAdapter("SELECT Number, Type, Qty, Date, num, ReceiptID FROM IssuedRN WHERE @I = @S", con);
//This line works but no secure
//sda = new SqlDataAdapter("SELECT Number, Type, Qty, Date, num, ReceiptID FROM IssuedRN WHERE " + drpdSerType.SelectedValue.ToString() + " = '" + txtRNumSer.Text + "'", con);
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
I get the following error; System.NullReferenceException: 'Object reference not set to an instance of an object.' Related to line
sda.SelectCommand.Parameters.AddWithValue("@I", drpdSerType.SelectedValue.ToString());
I have also followed the guidance here; https://csharp-station.com/Tutorial/AdoDotNet/Lesson06
Thanks for any help on this, I have tried many different ways to use parameters but all seem to do this or give the above error.
Thanks Karl
Update:
I have added in a switch statement driven by the drop down list, so the parameter @I is now hard coded...
string qryselect = drpdSerType.SelectedValue.ToString();
string cmd = "";
switch (qryselect)
{
case "Number":
cmd = "SELECT Number, Type, Qty, Date, RNum, ReceiptID FROM IssuedRN WHERE Number = @S";
break;
case "RNum":
cmd = "SELECT Number, Type, Qty, Date, RNum, ReceiptID FROM IssuedRN WHERE RNum = @S";
break;
case "ReceiptID":
cmd = "SELECT Number, Type, Qty, Date, RNum, ReceiptID FROM IssuedRN WHERE ReceiptID = @S";
break;
}
Am guessing am missing something in the passing of the values in the drop down to the SQL parameter as the values are pre-populated and match the columns and querying, they are never null.