How to bind a drop-down control to a data source in ASP.NET

前端 未结 1 1197
天涯浪人
天涯浪人 2020-12-29 16:07

I am new to C#.

I have a project to create an HR system and I created a page to add employees but the supervisor asked me to create a drop down list that displays th

相关标签:
1条回答
  • 2020-12-29 16:38

    As your code works for retrieving Employees Info. from database, you will retrieve the Departments info. from your Departments table.

    protected void bindDepartments()
    {
        SqlConnection strcon1 = new SqlConnection(strcon);
        strcon1.Open();
        string ADDStr = "SELECT DepartmentId,DepartmentName FROM Departments ";
        SqlCommand ADDCmd = new SqlCommand(ADDStr, strcon1);
        DataTable table = new DataTable();
    
    
        SqlDataAdapter adapter = new SqlDataAdapter(ADDCmd);
    
        adapter.Fill(table);
    
        ddlDepartments.DataSource = table;
        ddlDepartments.DataValueField = "DepartmentId"; //The Value of the DropDownList, to get it you should call ddlDepartments.SelectedValue;
        ddlDepartments.DataTextField = "DepartmentName"; //The Name shown of the DropDownList.
        ddlDepartments.DataBind();
    
    }
    
    0 讨论(0)
提交回复
热议问题