0

我有tblDepartments带列的表DeptID, Department, Description。我也有下拉框drpDepartments。我想Department在下拉框中显示列的内容。我尝试将此 C# 代码用于 winforms,但它不起作用:

        drpDepartments.DataSource = dsDep.Tables["tblDepartment"];
        drpDepartments.DisplayMember = "Department";
        drpDepartments.ValueMember = "DeptID";
        drpDepartments.Text = "Choose Department";

我如何使用 ASP.NET C# 来做到这一点?谢谢。

新代码(仍然无法正常工作)

        sConn = new SqlConnection(sStr);
        daEmp = new SqlDataAdapter("SELECT * FROM tblEmployee", sConn);
        daDep = new SqlDataAdapter("SELECT * FROM tblDepartment", sConn);
        dsEmp = new DataSet();
        dsDep = new DataSet();

        daEmp.Fill(dsEmp, "tblEmployee");
        daDep.Fill(dsDep, "tblDepartment");

        dsEmp.Tables["tblEmployee"].PrimaryKey = new DataColumn[] { dsEmp.Tables["tblEmployee"].Columns["EmployeeID"] };

        DataTable dt=new DataTable();
        daDep.Fill(dt);

        drpDepartments.DataTextField = "Department";
        drpDepartments.DataValueField = "DeptID";
        drpDepartments.DataSource = dt;
        drpDepartments.DataBind();
4

3 回答 3

1

你必须在 asp.net webForms 中这样称呼它

        drpDepartments.DataSource = dsDep.Tables["tblDepartment"];// Set DataSource Table First
        drpDepartments.DataTextField = "Department";// Set Column Name of DataTable to set as Text Field
        drpDepartments.DataValueField = "DepartmentID";// Set Column Name of DataTable to set as Value Field
        drpDepartments.DataBind();

您必须从using System.Web.UI.WebControls;命名空间使用它。好像您正在使用 winforms 命名空间。

DataTextField等价于DisplayMemberValueMember等价于DataValueField

于 2013-11-13T06:16:13.410 回答
0

您是否调用了 DataBind()?

drpDepartments.DataSource = dsDep.Tables["tblDepartment"];
drpDepartments.DisplayMember = "Department";
drpDepartments.ValueMember = "DepartmentID";
drpDepartments.Text = "Choose Department";
drpDepartments.DataBind();
于 2013-11-13T06:12:03.123 回答
0
drpDepartments.DataSource = ds1;
drpDepartments.DataTextField = "textcol";
drpDepartments.DataValueField = "valuecol";
drpDepartments.DataBind();

在 btn_save 方法中执行此操作后添加此..

 cmd.Parameters.AddWithValue("@a", drpDepartments.SelectedValue);

希望能帮助到你。

于 2013-11-13T06:31:38.630 回答