Introduction:
In this article I will explain how to set default value in dropdownlist in asp.net using c#,and
vb.net . In dropdownlist
we can set default value by using selectedindex and selectedvalue properties.
There
are two Method we will use to set default value in Dropdown list:
Method
1: using SelectedIndex
Using
selectedindex property we can set dropdownlist default value as:
ddlDept.SelectedIndex
= 2;
Method
2: Using SelectedValue
using
selectedvalue property we can set dropdownlist default value as:
ddlDept.SelectedValue
= 2;
Source Code for Sample Application
In
your aspx page, write following code
<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:
C#
Code
Now
add following namespaces in code behind:
using System;
After completion of adding namespaces you need to write the code like as shown below
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//
set dropdown default value using selectedvalue
ddlDept.SelectedValue = "2";
}
}
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
dropdown default value using selectedvalue
ddlDept.SelectedValue = "2"
End If
End Sub
End Class
0 comments:
Post a Comment