选择Query不填充我的DataSet ASP.NET C#

时间:2014-04-02 11:20:25

标签: c# asp.net sql gridview

当我直接执行此SELECT查询时,它可以工作。但是,在调试时,我看到我的数据集是空的。问题可能是什么?

protected void Grid_ItemList_RowDataBound(object sender, GridViewRowEventArgs e)
        {

        if (e.Row.RowType == DataControlRowType.DataRow)
            {
            Connection con = new Connection();
            con.con = new SqlConnection(con.str);

            try
                {
                con.con.Open();
                con.cmd = new SqlCommand("Select Item_Code,Item_Name from Pharmacy_Item_M", con.con);
                var ddl = (DropDownList)e.Row.FindControl("ddlnames");
                SqlDataAdapter da = new SqlDataAdapter(con.cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                con.con.Close();
                ddl.DataSource = ds;    
                ddl.DataTextField = "ItemName";
                ddl.DataValueField = "ItemCode";
                ddl.DataBind();

                }
            catch (Exception ex)
                {
                log.Warn("Unable to open connection");
                }
            }
        }

我正在关注this教程。

2 个答案:

答案 0 :(得分:2)

可能会帮助你

protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //Find the DropDownList in the Row
        DropDownList ddlnames = (e.Row.FindControl("ddlnames") as DropDownList);
        ddlRole.DataSource = GetData("Select Item_Code,Item_Name from Pharmacy_Item_M");
        ddlRole.DataTextField = "Item_Name";
        ddlRole.DataValueField = "Item_Code";
        ddlRole.DataBind();

        //Add Default Item in the DropDownList
        ddlnames.Items.Insert(0, new ListItem("Please select"));

        //Select the role of user in DropDownList
        string x = (e.Row.FindControl("lblnames") as Label).Text;
        ddlnames.Items.FindByValue(x).Selected = true;
    }        
}

和GetData函数

 private DataSet GetData(string query)
{
    string conString = ConfigurationManager.ConnectionStrings["xxxx"].ConnectionString;
    SqlCommand cmd = new SqlCommand(query);
    using (SqlConnection con = new SqlConnection(conString))
    {
        using (SqlDataAdapter da = new SqlDataAdapter())
        {
            cmd.Connection = con;
            da.SelectCommand = cmd;
            using (DataSet ds = new DataSet())
            {
                da.Fill(ds);
                return ds;
            }
        }
    }
}

答案 1 :(得分:2)

你的价值和文字字段:

ddl.DataTextField = "ItemName";
ddl.DataValueField = "ItemCode";

应匹配表select语句中的字段名称:

"Select Item_Code,Item_Name from...