John
John

Reputation: 487

How to select first value in list box by default when the page loads

<asp:ListBox ID="listbox_Userrole"  runat="server" DataSourceID="SK" DataTextField="RoleName" DataValueField="RoleName" ></asp:ListBox>
<asp:SqlDataSource ID="SurelyKnown" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
                                ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>"
                                SelectCommand="SELECT RoleName FROM tbl_role WHERE RoleID&gt;1"></asp:SqlDataSource>

How to select first value in list box by default when the page loads.

Upvotes: 1

Views: 10690

Answers (3)

Agamand The True
Agamand The True

Reputation: 832

Use the DataBound event of the list box like this :-

 protected void lstBox_DataBound(object sender, EventArgs e)
{
    if (lstBox.Items.Count > 0)
    {
        lstBox.SelectedIndex = 0;
    }
}

Hope this helps.

Upvotes: 1

RoccoC5
RoccoC5

Reputation: 4213

In your code-behind, add the following to your Page_Load event handler:

protected override void Page_Load(object sender, EventArgs e)
{
    this.listbox_Userrole.SelectedIndex = 0;
}

Upvotes: 4

PaulStock
PaulStock

Reputation: 11263

In page load, set listbox_userrole.selectedindex = 0

Upvotes: 1

Related Questions