Convert gridview field into Dropdownlist

我怕爱的太早我们不能终老 提交于 2019-12-25 02:07:44

问题


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:


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);
        }
    }


来源:https://stackoverflow.com/questions/21315343/convert-gridview-field-into-dropdownlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!