Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Select an item in dropdownlist by text programmatically

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 247
    Comment on it

    To understand this, consider the following code:

            //Dummy DataTable
            DataTable dt = new DataTable();
            dt.Columns.Add("EmployeeName");
            dt.Columns.Add("EmployeeId");
            for (int i = 1; i <= 10; i++)
            {
                DataRow dr = dt.NewRow();
                dr[0] = "Name" + i.ToString();
                dr[1] = i;
                dt.Rows.Add(dr);
            }
    
            //Configure DropDownList
            DropDownList1.DataTextField = "EmployeeName";
            DropDownList1.DataValueField = "EmployeeId";
            DropDownList1.DataSource = dt;
            DropDownList1.DataBind();
    
            //default value
            string defaultText = "Name5";
    

    Approach 1:

            foreach (ListItem item in DropDownList1.Items)
            {
                if (item.Text == defaultText)
                {
                    item.Selected = true;
                    break;
                }
            }
    

    Approach 2:

            DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByText(defaultText));
    

    Happy Coding!!

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: