1

所以在这里我试图填充我的下拉列表,后面的代码如下:

 protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(CommonFunctions.GetAppDBConnection(Constants.AppID, Constants.TMDDBConnection));
        con.Open();
        SqlCommand mycommand = new SqlCommand("select * from MSUnit", con);
        SqlDataReader ddlvalues = mycommand.ExecuteReader();
        ddlTransactionCategory.DataSource = ddlvalues;
        ddlTransactionCategory.DataTextField = "categoryCode";
        ddlTransactionCategory.DataValueField = "OrgID";
        ddlTransactionCategory.DataBind();


        mycommand.Connection.Close();
        mycommand.Connection.Dispose();
    }

问题是,我似乎无法让它工作,有什么帮助吗?这段代码做得对吗?

4

3 回答 3

1

请尝试以下代码:

protected void Page_Load(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(CommonFunctions.GetAppDBConnection(Constants.AppID, Constants.TMDDBConnection));
    con.Open();
    SqlCommand mycommand = new SqlCommand("select * from MSUnit", con);
    SqlDataAdapter adp =new   SqlDataAdapter(mycommand);
    DataSet ds =new DataSet();
    adp.Fill(ds);
    ddlTransactionCategory.DataSource = ds;
    ddlTransactionCategory.DataTextField = "categoryCode";
    ddlTransactionCategory.DataValueField = "OrgID";
    ddlTransactionCategory.DataBind();


    mycommand.Connection.Close();
    mycommand.Connection.Dispose();
}

谢谢, 海特什

于 2013-06-12T03:52:20.293 回答
0

无法绑定到 SqlDataReader(或者至少我从未尝试过)。改为获取 DataTable 或 DataSet,填充它,然后以相同的方式将其绑定到下拉列表。

于 2013-06-12T03:49:29.703 回答
0

像下面这样使用 SqlDataAdataper

using (SqlConnection con = new SqlConnection(CommonFunctions.GetAppDBConnection(Constants.AppID, Constants.TMDDBConnection)))
{
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter("select * from MSUnit", con);
        DataTable dt = new DataTable
        da.Fill(dt)
        ddlTransactionCategory.DataSource = dt;
        ddlTransactionCategory.DataTextField = "categoryCode";
        ddlTransactionCategory.DataValueField = "OrgID";
        ddlTransactionCategory.DataBind();
}

如果要使用 DataReader,则必须一一插入。

while (ddlvalues.Read())
{
    ddlTransactionCategory.Items.Add(new ListItem(ddlvalues.getString("OrgID"),ddlvalues.getString("categoryCode"))) 
}
于 2013-06-12T03:52:16.293 回答