无法使用下拉列表绑定数据?

时间:2013-07-23 09:08:51

标签: c# asp.net sql-server-2008

我正在使用包含下拉列表的C#在asp.net中创建一个应用程序。现在我不想编写相同的代码来从数据库中获取相同的数据。我尝试使用此代码,但它无法正常工作

 protected void Page_Load(object sender, EventArgs e)
    {

        DataTable DT = sel_obj.select_Dept_Name();
        departmentDrop.DataSource = DT;
        departmentDrop.DataMember = "Department_Name";
        departmentDrop.DataBind();
    }
 public DataTable select_Dept_Name()
    {
        module c = new module();
        c.DB_Connection();

        if (c.con.State == ConnectionState.Open)
        {
            c.con.Close();
            c.con.Open();
        }

        DataSet DS = new DataSet();
        string QRY = "";
        QRY = "SELECT Department_Name FROM Department_Master";
        SqlDataAdapter DA = new SqlDataAdapter(QRY, c.con);
        DA.Fill(DS);
        DataTable DT = DS.Tables[0];
        return DT;
    }

1 个答案:

答案 0 :(得分:1)

您需要调用“DataBind()”函数。您还需要确保您的表包含要与下拉列表绑定的数据。

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
        DataTable DT = sel_obj.select_Dept_Name();
        departmentDrop.DataSource = DT ;
        departmentDrop.DataTextField = "Department_Name";
        departmentDrop.DataValueField = "Department_Name";
        departmentDrop.DataBind();
        }
    }