从asp.net Gridview动态添加和删除列

时间:2018-05-24 11:26:39

标签: c# asp.net

我有一个包含固定列数的网格视图,但我想让列动态,列数应根据所选选项而变化。

<asp:GridView ID="grid_additional_test" CssClass="table table-condensed table-striped hover table-bordered static pull-left table-hover"
runat="server" AutoGenerateColumns="False" Width="200px" OnRowDataBound="grid_additional_test_RowDataBound">
<Columns>
<asp:BoundField HeaderText="Test Code" DataField="Test_Code">
<HeaderStyle HorizontalAlign="Center" Width="20%" />
<ItemStyle Width="15%" CssClass="colL fix_gv_clm" HorizontalAlign="Left" />
<HeaderStyle CssClass="fix_gv_clm" />
</asp:BoundField>
</Columns>
<HeaderStyle BackColor="#F2F2F2" />
</asp:GridView>

` 这是我绑定数据的代码:

grid_additional_test.DataSource = ds.Tables[0];
        grid_additional_test.DataBind();
        grid_additional_test.Visible = true;

请分享您对此的见解。

2 个答案:

答案 0 :(得分:0)

检查一下。

for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
        {
            BoundField bf = new BoundField();
            bf.DataField = ds.Tables[0].Columns[i].ColumnName;
            bf.HeaderText = ds.Tables[0].Columns[i].ColumnName;
            grid_additional_test.Columns.Add(bf);
        }
grid_additional_test.DataSource = ds.Tables[0].DefaultView;
grid_additional_test.DataBind();

确保删除通过标记添加到GridView的所有列。

答案 1 :(得分:0)

您还可以从列编辑器中取消选中“自动生成字段”

检查此 enter image description here