简体   繁体   中英

Drop down list items count is working

I have a drop down list, which has first item hard coded and other are bind by sql data source. Now on C# code I want this drop down list's items count which I'm getting 1 always (the first hard coded list item). while this drop down list is properly showing all list item on browser. I'm not able to understand the exact problem.

<asp:DropDownList ID="ddlGroup" runat="server" DataSourceID="dsGroupListByUserId"
     Width="100px" DataTextField="GroupName" DataValueField="GroupID" AppendDataBoundItems="True">
    <asp:ListItem Value="0">N/A</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="dsGroupListByUserId" runat="server" ConnectionString="<%$ ConnectionStrings:EMSsql %>" SelectCommand="GetGroup_ByEventID" SelectCommandType="StoredProcedure" >
    <SelectParameters>
        <asp:SessionParameter DefaultValue="0" Name="EventID" SessionField="EventID" Type="Int64" />
    </SelectParameters>
</asp:SqlDataSource>

And this is how i'm trying to fetch items count-

int ItemsCount = ddlGroup.Items.Count;

Put your databind in a !Page.IsPostBack.

Everything gets refreshed everytime the page is postback, which is why your count is 1 because it is the only list item client side. Anything populated server side will need to be in a not post back.

If (!Page.IsPostBack)
{
ddlGroup.DataBind();
}

I think this is because you are not using Page.IsPostBack property into page_Load .

Use IsPostBack into Page_load like

private void Page_Load()
{
    if (!IsPostBack)
    {
         // Bind your dropdown.
    }
}

Hope it works for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM