Asp.net: Set default value in dropdownlist from code behind

In this article I am going to explain how to set the default value in dropdownlist from code behind in asp.net using C# and vb.net

Implementation:
I have created a table Tb_Country and insert dummy data.
ID
int
CountryName
varchar(100)

HML Markup:
<asp:DropDownList ID="DropDownList1" runat="server" CssClass="dropdownlist" AutoPostBack="true">
 </asp:DropDownList>

Import the namespace:
C# code:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

VB.net Code:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Set default value in Dropdownlist
Create a method/function to populate the dropdown with default value and call it on page load. A default item is inserted at first position.

C# Code:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
    protected void Page_Load(object sender, EventArgs e)
    {      
        if (!IsPostBack)
        {
           Populatedropdown();
        }     
    }
  
 public void Populatedropdown()
    {       
        try
        {
            SqlCommand cmd = new SqlCommand("SELECT * FROM Tb_Country", con);
            DataTable dt = new DataTable();
            SqlDataAdapter adp = new SqlDataAdapter();
            adp = new SqlDataAdapter(cmd);
            adp.Fill(dt);
            DropDownList1.DataSource = dt;
            DropDownList1.DataTextField = "CountryName";
            DropDownList1.DataValueField = "ID";
            DropDownList1.DataBind();
            DropDownList1.Items.Insert(0,new ListItem("--Select City--","-1"));
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message.ToString());
        }      
    }

VB.net Code:
Private con As New SqlConnection(ConfigurationManager.ConnectionStrings("connection").ToString())
    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Populatedropdown()
        End If
    End Sub


Public Sub Populatedropdown()
        Try
            Dim cmd As New SqlCommand("SELECT * FROM Tb_Country", con)
            Dim dt As New DataTable()
            Dim adp As New SqlDataAdapter()
            adp = New SqlDataAdapter(cmd)
            adp.Fill(dt)
            DropDownList1.DataSource = dt
            DropDownList1.DataTextField = "CountryName"
            DropDownList1.DataValueField = "ID"
            DropDownList1.DataBind()
            DropDownList1.Items.Insert(0, New ListItem("--Select City--", "0"))
        Catch ex As Exception
            Response.Write(ex.Message.ToString())
        End Try
    End Sub



Post a Comment

0 Comments