Populate Dropdownlist With Selected Index

1 minute read

This is a demo to populate asp.net dropdownlist by C#.

Step 1: Create a asp.net dropdownlist

Create a dropdownlist in asp.net page. Here, I created a dropdownlist name ddlStudentInfo.

<asp:DropDownList ID = "ddlStudentInfo" runat = "server" Height="19px" Width="166px"></asp:DropDownList>

Step 2: Create StudentInfo class

Create a student info class to create list of StudentInfo object.

public class StudentInfo
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Step 3: Populate dropdownlist

Create a list of StudentInfo object. Make it data source of dropdownlist and choose your selected index. Here, I choose selected index 2 means dropdownlist shows Asrafuzzaman as selected text and 3 as selected value. I have write all those in Page Load. You can do as you required.

protected void Page_Load(object sender, EventArgs e)
{
        List lstStudentInfo = new List();
        
        StudentInfo objStudentInfo1 = new StudentInfo();
        objStudentInfo1.Id = 1;
        objStudentInfo1.Name = "Mahedee Hasan";
        
        lstStudentInfo.Add(objStudentInfo1);
        
        StudentInfo objStudentInfo2 = new StudentInfo();
        objStudentInfo2.Id = 2;
        objStudentInfo2.Name = "Mahmud Ahsan";
        lstStudentInfo.Add(objStudentInfo2);
        
        StudentInfo objStudentInfo3 = new StudentInfo();
        objStudentInfo3.Id = 3;
        objStudentInfo3.Name = "Asrafuzzaman";
        lstStudentInfo.Add(objStudentInfo3);
        
        StudentInfo objStudentInfo4 = new StudentInfo();
        objStudentInfo4.Id = 4;
        objStudentInfo4.Name = "Enamul Haque";
        lstStudentInfo.Add(objStudentInfo4);
        
        ddlStudentInfo.DataSource = lstStudentInfo;
        ddlStudentInfo.DataValueField = "Id";
        ddlStudentInfo.DataTextField = "Name";
        ddlStudentInfo.SelectedIndex = 2; //Selected index 2 means selected value is 3 and text is Asrafuzzaman
        ddlStudentInfo.DataBind();
 
}