0

I have Grid with DropDownList and it has static data. It is being saved perfectly. But, while editing, I need to get SelectedValue of the DropDown from the DataBase.

My code is:

<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderText="Order">
    <ItemTemplate>
        <asp:DropDownList ID="ddlOrder" SelectedValue='<%# (DataBinder.Eval(Container.DataItem,"Order")) %>' runat="server" Width="60">
            <asp:ListItem Text="1" Value="1"></asp:ListItem>
             <asp:ListItem Text="2" Value="2"></asp:ListItem>
             <asp:ListItem Text="3" Value="3"></asp:ListItem>
             <asp:ListItem Text="4" Value="4"></asp:ListItem>
        </asp:DropDownList>

    </ItemTemplate>

And:

protected void gvServicePort_RowDataBound(object sender , GridViewRowEventArgs e)
{
    //DropDown
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        var dropdownList = (DropDownList)e.Row.FindControl("ddlOrder");
        for (int i = 1; i < 15; i++)
        {
            dropdownList.Items.Add(i.ToString());
        }
        dropdownList.SelectedValue =
              Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Order"));
    }
}

It is throwing and error that say that 'ddlOrder' has a SelectedValue which is invalid because it does not exist in the list of items.

Can anyone help?

Ivan Ferić
  • 4,725
  • 11
  • 37
  • 47
Out
  • 627
  • 2
  • 13
  • 20

1 Answers1

1

Test that the value exists in your DropDownList before attempting to assign.

if (dropdownList.Items.FindByValue(value) != null)
{
  // go ahead and assign
  dropdownList.SelectedValue = value;
}
else
{
  // handle the issue if necessary
}

I have had occasions where the value did exist in the list but setting SelectedValue was unpredictable and still resulted in the "does not exist in the list" error you mentioned. If you finding this is the case you may want to try one of the following options for assigning the selected item.

Use the FindByValue method:

dropdownList.Items.FindByValue(value).Selected = true;

or this one:

dropdownList.SelectedIndex = dropdownList.Items.IndexOf(dropdownList.Items.FindByText(value));

I always forget how to implement these last two snippets but I was able to find them both in this SO question: How to programatically set SelectedValue of Dropdownlist when it is bound to XmlDataSource.

Community
  • 1
  • 1
Rich C
  • 802
  • 2
  • 13
  • 33