ASP.NET中GridView控件动态显示列

ASP.NET中GridView控件动态显示列

一个很简单的GridView

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnDataBound="GridView1_DataBound">
                <Columns>
                    <asp:BoundField DataField="Date" HeaderText="时间" DataFormatString="{0:yyyy-MM-dd}"  />
                    <asp:BoundField HeaderText="星期" />
                    <asp:TemplateField HeaderText="状态">
                        <ItemTemplate>
                            <asp:DropDownList ID="DropDownList1" runat="server" SelectedValue='<%# Eval("Status") %>'>
                                <asp:ListItem Value="0">默认</asp:ListItem>
                                <asp:ListItem Value="1">上班</asp:ListItem>
                                <asp:ListItem Value="2">休假</asp:ListItem>
                            </asp:DropDownList>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>

然后给GridView加上DataBound事件,数据绑定后激发。可以获取到表格中的数据,然后根据其他列来修改数据,达到动态显示

        protected void GridView1_DataBound(object sender, EventArgs e)
        {
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                GridView1.Rows[i].Cells[1].Text = Comm.GetWeek(GridView1.Rows[i].Cells[0].Text);
            }
        }

Comm.GetWeek是自定义方法和类,不用管。如果是自定义模版,需要使用GridView1.Rows[i].Cells[0].FindControl(单元格中控件ID)。得到object类型对象,把它转换成指定控件类型就可以使用了

猜你喜欢

转载自blog.csdn.net/qq_38613453/article/details/82808336