Jaggu
Jaggu

Reputation: 6428

SelectedValue null in dropdownlist so errow thrown

This is my code in aspx:

 <EditItemTemplate>           
    <asp:DropDownList ID="DropDownList1" runat="server" 
         DataSourceID="SqlDataSource2" SelectedValue='<%#GetSYSACCID(Eval("SYSACCID"))%>'
         DataTextField="UserName" DataValueField="SYSACCID">
    </asp:DropDownList>
  </EditItemTemplate>

DropDownList is inside EditItemTemplate of TemplateField in gridview. The GetSYSACCID is a function defined in aspx.cs. Problem is when Eval("SYSACCID") is null, GetSYSACCID returns null and so error is thrown. How can I handle this? I know this looks easy but still it's giving me a pain.

Thanks in advance :)

Upvotes: 0

Views: 5029

Answers (2)

Muhammad Akhtar
Muhammad Akhtar

Reputation: 52241

You can do something like...

SelectedValue='<%# GetSYSACCID(Eval("SYSACCID") == null ? 0 : Eval("SYSACCID"))%>'

You have default value to handle null value. e.g.

<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource2" AppendDataBoundItems="true"
            SelectedValue='<%#GetSYSACCID(Eval("SYSACCID"))%>' DataTextField="UserName" DataValueField="SYSACCID" >
            <asp:ListItem Value="0" Text="---Select---"></asp:ListItem>
        </asp:DropDownList>

Upvotes: 2

Mrchief
Mrchief

Reputation: 76198

Try this:

SelectedValue='<%# GetSYSACCID(Eval("SYSACCID")) ?? 0 %>'

or modify GetSYSACCID to return 0 when you receive null input.

Upvotes: 0

Related Questions