Gridview行与下拉列表

时间:2012-09-19 09:43:29

标签: c# gridview

我正在开发一个asp .net项目。我有一个gridview,在rowdatabound上我想把一个下拉列表放到行的每个单元格中。所以我有以下方法。

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    DropDownList ddl = new DropDownList();
    ddl.DataSource = getImpacts();
    ddl.DataBind();
    if (e.Row.RowType != DataControlRowType.Header)
    {

        for (int i = 0; i < e.Row.Cells.Count; i++)
        {
            e.Row.Cells[i].Controls.Add(ddl);

        }
    }
}

问题是dropdouwnlist仅在最后一个单元格中添加!当我调试时,for循环从所有单元格传递!这怎么可能?

2 个答案:

答案 0 :(得分:1)

需要为每列创建下拉列表实例

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType != DataControlRowType.Header)
    {
        for (int i = 0; i < e.Row.Cells.Count; i++)
        {
           DropDownList ddl = new DropDownList();
           ddl.DataSource = getImpacts();
           ddl.DataBind();
           e.Row.Cells[i].Controls.Add(ddl);
        }
    }
}

答案 1 :(得分:1)

您可以在循环中插入,并为每个单元格迭代

        for (int i = 0; i < e.Row.Cells.Count; i++)
        {
           DropDownList ddl = new DropDownList();
           ddl.DataSource = getImpacts();
           ddl.DataBind();

           e.Row.Cells[i].Controls.Add(ddl);
        }