EL323 EL323 - 1 month ago 10
ASP.NET (C#) Question

How to set dropdownlist from code behind?

I have the following DropDownList:

<asp:DropDownList ID="commission" class="form-control" runat="server">
<asp:ListItem Enabled="true" Text="Select Commission" Value="-1"></asp:ListItem>
<asp:ListItem Text="10%" Value="0.1"></asp:ListItem>
<asp:ListItem Text="15%" Value="0.15"></asp:ListItem>
<asp:ListItem Text="20%" Value="0.20"></asp:ListItem>
<asp:ListItem Text="25%" Value="0.25"></asp:ListItem>
</asp:DropDownList>


I am reading value of dropdown list from database. I get object reference not set to an instance of an object Error.
This is what I have tried:

double com = reader.GetDouble(6);
if (com == 0.1)
{
commission.Items.FindByText("10").Selected = true; // I get the exeption here
}
else if (com == 0.15)
{
commission.Items.FindByText("15").Selected = true;
}
else if (com == 0.2)
{
commission.Items.FindByText("20").Selected = true;
}
else if (com == 0.25)
{
commission.Items.FindByText("25").Selected = true;
}

Answer

The ListItemCollection.FindByText method compares full strings. It will not do partial strings. So 10 will not match 10%. See the quote below from MSDN:

This method does not do partial searches or wildcard searches. If an item is not found in the collection using this criteria, null is returned.

Since null is returned, then you try to set the .Selected property to true, you receive a NullReferenceException. The solution is easy, add % to your strings.

double com = reader.GetDouble(6);
if (com == 0.1)
{
    commission.Items.FindByText("10%").Selected = true;
}
else if (com == 0.15)
{
    commission.Items.FindByText("15%").Selected = true;
}
else if (com == 0.2)
{
    commission.Items.FindByText("20%").Selected = true;
}
else if (com == 0.25)
{
    commission.Items.FindByText("25%").Selected = true;
}

Using a bunch of else if statements like this is overly verbose. You can shrink it down with a switch statement.

switch(com)
{
    case 0.1:  commission.Items.FindByText("10%").Selected = true; break;
    case 0.15: commission.Items.FindByText("15%").Selected = true; break;
    case 0.2:  commission.Items.FindByText("20%").Selected = true; break;
    case 0.25: commission.Items.FindByText("25%").Selected = true; break;
}

Note also you could simplify your code by looking up according to value.

commision.Items.FindByValue(com).Selected = true;

In the the future, to resolve a NullReferenceException, figure out what object is null (it's often obvious by looking at the line of code that throws the exception) and then figure out why it's null. If it involves something built into .NET, then check the relevant documentation to make sure you understand how it works.

Also, you appear to be using double for financial matters. You should use decimal. See the discussion here.