Question

I am reading from a SQL datareader in C# and passing the values from the columns to a dropdownlist. There are two columns being read. Using IsDbNull, I am able to handle the null values. However, as I have the code written right now, if dr.GetString(0) is null, no values are passed along at all, while as long as only dr.GetString(1) (or neither) is null, all of the values are passed along and the null values are ignored. Here is what I have for while the datareader is reading:

while (dr.Read())
{
     if (!dr.IsDBNull(0))
     {
          machineName.Items.Add(dr.GetString(0).ToString());
     }
     else if (!dr.IsDBNull(1))
     {
          machineName.Items.Add(dr.GetString(1).ToString());
     }
 }

What I need to happen is for the dropdownlist to be populated with whatever values the datareader returns, regardless of which column they are in. I've removed the using and try/catch statements in order to declutter the code. Thanks everyone.

Was it helpful?

Solution

My preferred way of handling nulls in a reader is to use named columns and then use Convert.ToString(object)

So, you'd have the following:

while (dr.Read())
{
     string firstItem = Convert.ToString(dr["FIRST_ITEM"]);
     if(!string.IsNullOrEmpty(firstItem))
     {
        machineName.Items.Add(firstItem);
     }
     ... etc.
}

I'm not sure I understand your question, though.
You say

However, as I have the code written right now, if dr.GetString(0) is null, no values are passed along at all, while as long as only dr.GetString(1) (or neither) is null, all of the values are passed along and the null values are ignored.

which sounds like you're using if/else if, but your code shows two if statements.

Edit:

To better address your updated question, my solution would be to have a generic list of ListItems and add each column to that list. Then, bind that list to the dropdown:

List<ListItem> items = new List<ListItem>();

while(dr.Read())
{
    string firstItem = Convert.ToString(dr["FIRST_ITEM"]);
    if(!string.IsNullOrEmpty(firstItem))
    {
        ListItem thisItem = new ListItem(firstItem, firstItem);
        items.Add(thisItem);
    }
}

 machineName.Items = items;

This way, if you have no data, items will be null. If you have one column in one row and the other column in the next row, it'll add them appropriately. Although, your code should work the same if you took out the else.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top