如何在GridView中绑定DropDown

时间:2013-12-22 23:30:10

标签: c# asp.net gridview dropdownbox

我有一个在gridview中的下拉列表并且它是绑定但问题是仅绑定第一行并且保持绑定与gridview的其余部分相同的值。我期待gridview中每一行的下拉,并且下拉的内容将根据gridvew中的ID而有所不同。在一行中它可能是Yes,No,另一行可能是Yes,No,NA。这是我的代码:

    protected void RowDataBound(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            DropDownList ddl_Answer;
            foreach (GridViewRow grdRow in GridView1.Rows)
            {

                //get current index selected
                int current_eng_sk = Convert.ToInt32(GridView1.DataKeys[e.Row.RowIndex].Value);
                ddl_Answer = (DropDownList)(GridView1.Rows[grdRow.RowIndex].Cells[2].FindControl("ddl_Answer"));
                String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString;
                SqlConnection con2 = new SqlConnection(strConnString);
                SqlDataAdapter sda = new SqlDataAdapter();
                SqlCommand cmd1 = new SqlCommand("select distinct DD_ANSWER from table1 D, table2 Q where Q.ANS_OPT = D.ID and  ENG_SK= '" + current_eng_sk + "' and Q.ANS_OPT is not null ");

                cmd1.Connection = con2;
                con2.Open();
                ddl_Answer.DataSource = cmd1.ExecuteReader();
                ddl_Answer.DataTextField = "DD_ANSWER";
                ddl_Answer.DataValueField = "DD_ANSWER";
                ddl_Answer.DataBind();
                con2.Close();

            }
}

1 个答案:

答案 0 :(得分:2)

您已经在GridView的RowDataBound事件中。每行触发一次,因此您不需要每次都进一步foreach (GridViewRow grdRow in GridView1.Rows)。您应该能够将代码简化为:

protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DropDownList ddl_Answer;
        //get current index selected
        int current_eng_sk = Convert.ToInt32(GridView1.DataKeys[e.Row.RowIndex].Value);
        ddl_Answer = e.Row.FindControl("ddl_Answer") as DropDownList;
        using (SqlConnection con2 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString)) 
        {
            con2.Open();
            using (SqlCommand cmd1 = new SqlCommand("select distinct DD_ANSWER from table1 D, table2 Q where Q.ANS_OPT = D.ID and  ENG_SK= '" + current_eng_sk + "' and Q.ANS_OPT is not null ", con2)) 
            {
                ddl_Answer.DataSource = cmd1.ExecuteReader();
                ddl_Answer.DataTextField = "DD_ANSWER";
                ddl_Answer.DataValueField = "DD_ANSWER";
                ddl_Answer.DataBind();
            }
        }
    }
}