Convert gridview field into Dropdownlist

2019-09-01 13:24发布

i need to convert a field in gridview to a dropdownlist, but i need to do this in codebehind, and I cannot add a templatefield in apsx(but it could be created at run time execution...) I populate my grid with this code:

        foreach (var item in response.Select(x => x.idMatriz).Distinct())
        {
            dr = dt.NewRow();
            for (int i = 0; i < colunas; i++)
            {
                dr[i] = response.Where(x => x.Propriedade == dt.Columns[i].ToString() && x.idMatriz == item).Select(x => x.Valor).FirstOrDefault();
            }
            dt.Rows.Add(dr);
        }

It works but i need this fileds be a dropdown.... any help?

1条回答
戒情不戒烟
2楼-- · 2019-09-01 13:52

It looks like all you need to do is dynamically create a template field and add it to the gridview.

var field = new TemplateField {HeaderText = col.ColumnName}
gridView.Columns.Add(field);

After that, on the row created event of the gridview create and wire up the dropdown.

    public void DynamicGridView_RowCreated(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType != DataControlRowType.DataRow)
        {
            return;
        }

        var grid = sender as GridView;
        if (grid == null)
        {
            return;
        }

        for (var i = 0; i < grid.Columns.Count; i++)
        {
            var column = grid.Columns[i] as TemplateField;
            if (column == null)
                continue;

            var cell = e.Row.Cells[i];
            var dropdown = new DropDownList();
            cell.Controls.Add(dropdown);
        }
    }
查看更多
登录 后发表回答