Welcome to WebmasterWorld Guest from 54.147.220.66

Forum Moderators: ocean10000

Message Too Old, No Replies

Check if DataReader has data

   
2:16 pm on Sep 28, 2010 (gmt 0)

5+ Year Member



I have the following code that pulls info out of an MSSQL DB into a dropdown list. It is successfully writing the info to a dropdown list. However if NOTHING is returned the drop down list is blank.

I need to put "N/A" in the drop down list if nothing is returned and I'm not exactly sure how to do that. Here is the code that does work when data is returned:
 
//if option exists show it, otherwise put N/A in DropDownList
SqlDataReader ddDR4 = null;
SqlCommand sql4 = new SqlCommand("SELECT DISTINCT options FROM hwproducts WHERE options IS NOT NULL AND style='" + pstyle + "'", MyConnection);
MyConnection.Open();
ddDR4 = sql4.ExecuteReader(CommandBehavior.CloseConnection);
DropDownListOption1.DataSource = ddDR4;
DropDownListOption1.DataTextField = "options";
DropDownListOption1.DataValueField = "options";
DropDownListOption1.DataBind();
MyConnection.Close();


How do I put "N/A" into the DropDownListOption1 if nothing is returned?

Thanks!
Chris
2:31 pm on Sep 28, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Check to see if your SqlDataReader hasRows
...
MyConnection.Close();

if (!ddDR4.HasRows)
{
DropDownListOption1.Items.Clear();
ListItem li = new ListItem("N/A");
DropDownListOption1.Items.Add(li);
}


* BTW you should be using parametrized queries. If the user can influence the value of pstyle you are susceptible to a SQL Injection attack.
4:38 pm on Sep 28, 2010 (gmt 0)

5+ Year Member



I had to change the code a little (logic flow), this is what worked:
   //if option exists show it, otherwise put N/A in DropDownList
SqlDataReader ddDR4 = null;
SqlCommand sql4 = new SqlCommand("SELECT DISTINCT options FROM hwproducts WHERE options IS NOT NULL AND style='" + pstyle + "'", MyConnection);
MyConnection.Open();
ddDR4 = sql4.ExecuteReader(CommandBehavior.CloseConnection);
if (!ddDR4.HasRows)
{
DropDownListOption1.Items.Clear();
ListItem li = new ListItem("N/A");
DropDownListOption1.Items.Add(li);
}
else
{
DropDownListOption1.DataSource = ddDR4;
DropDownListOption1.DataTextField = "options";
DropDownListOption1.DataValueField = "options";
DropDownListOption1.DataBind();
}
MyConnection.Close();


I dont *think* SQL Injection will be a problem but its always better to be safe than sorry. Thanks for that help too!