Introduction:
In this article I will explain how to set dropdownlist selected value on page load or code
behind in asp.net (c#, vb.net). In dropdownlist we can set selected item by
value or text using FindByValue and FindByText properties.
We have two different methods to
set dropdownlist selected value.
Method 1: Set Dropdownlist
Selected Value Based on value
using FindByValue property we can set dropdownlist
selected value
ddlusers.Items.FindByValue("4").Selected
= true;
Method 2: Set Dropdownlist
Selected value based on Text
using FindByText property we can set dropdownlist
selected value
ddlusers.Items.FindByText("Sales").Selected
= true;
Source Code for sample
Application:
Design
your page as given below:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>set dropdownlist default value in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<fieldset style="width:250px">
<legend><strong>Set Default Value OF dropdown </strong></legend>
<div>
<asp:DropDownList ID="ddlDept"
runat="server">
<asp:ListItem Value="1">HR</asp:ListItem>
<asp:ListItem Value="2">Marketing</asp:ListItem>
<asp:ListItem Value="3">Production</asp:ListItem>
<asp:ListItem Value="4">Sales</asp:ListItem>
<asp:ListItem Value="5">Inventory</asp:ListItem>
</asp:DropDownList>
</div></fieldset>
</form>
</body>
</html>
ASP.Net code Behind file code:
C# Code
write the code like as shown below
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// set dropdownlist selected based on text
ddlusers.Items.FindByText("Sales").Selected
= true;
}
}
VB.NET Code
Partial Class VBCode
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
' set dropdownlist selected based on text
ddlusers.Items.FindByText("Sales").Selected
= True
End If
End Sub
End Class
0 comments:
Post a Comment