how to set the default value to the drop down list control?

后端 未结 4 1234
名媛妹妹
名媛妹妹 2020-12-17 17:59

I have a drop down list control on my web page. I have bind the datatable to the dropdownlist control as follows -

lstDepartment.DataTextField = \"Department         


        
相关标签:
4条回答
  • 2020-12-17 18:31

    After your DataBind():

    lstDepartment.SelectedIndex = 0;  //first item
    
    or
    
    lstDepartment.SelectedValue = "Yourvalue"
    
    or 
    //add error checking, just an example, FindByValue may return null
    lstDepartment.Items.FindByValue("Yourvalue").Selected = true;
    
    or
    //add error checking, just an example, FindByText may return null
    lstDepartment.Items.FindByText("Yourvalue").Selected = true;
    
    0 讨论(0)
  • 2020-12-17 18:34

    Assuming that the DropDownList control in the other table also contains DepartmentName and DepartmentID:

    lstDepartment.ClearSelection();
    
    foreach (var item in lstDepartment.Items) 
    {
      if (item.Value == otherDropDownList.SelectedValue)
      {
        item.Selected = true;
      }
    }
    0 讨论(0)
  • 2020-12-17 18:41

    if you know the index of the item of default value,just

    lstDepartment.SelectedIndex = 1;//the second item
    

    or if you know the value you want to set, just

    lstDepartment.SelectedValue = "the value you want to set";
    
    0 讨论(0)
  • 2020-12-17 18:52
    lstDepartment.DataTextField = "DepartmentName";
    lstDepartment.DataValueField = "DepartmentID";
    lstDepartment.DataSource = dtDept;
    lstDepartment.DataBind();
    'Set the initial value:
    lstDepartment.SelectedValue = depID;
    lstDepartment.Attributes.Remove("InitialValue");
    lstDepartment.Attributes.Add("InitialValue", depID);
    

    And in your cancel method:

    lstDepartment.SelectedValue = lstDepartment.Attributes("InitialValue");
    

    And in your update method:

    lstDepartment.Attributes("InitialValue") = lstDepartment.SelectedValue;
    
    0 讨论(0)
提交回复
热议问题