[导入]以編程方式為GridView添加欄位

1。加一個gridview:
<asp:gridview id="GridView1" runat="server" autogeneratecolumns="False" datasourceid="SqlDataSource1" OnRowCreated="GridView1_RowCreated"><Columns>
<asp:BoundField ReadOnly="True" DataField="ID" InsertVisible="False" SortExpression="ID" HeaderText="ID"></asp:BoundField>
</Columns>
</asp:gridview>

2。兩個事件寫法:

    protected void Button1_Click1(object sender, EventArgs e)
    {
         //添加一個欄位;
        TemplateField tf = new TemplateField();
        tf.HeaderText = "TEST";
        GridView1.Columns.Add(tf);
    }

    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        ListItemType lit = (ListItemType)e.Row.RowType;
        if (lit == ListItemType.AlternatingItem || lit == ListItemType.Item)
        {
           //將TextBox加入到新欄位中;
            int c = e.Row.Cells.Count;
            Literal lt = new Literal();
            lt.Text = "<input type=text>";
            TextBox tb = new TextBox();
            tb.ID = "tb";
            tb.EnableViewState = true;
            tb.AutoPostBack = true;
           
            e.Row.Cells[c - 1].Controls.Add(lt);
            e.Row.Cells[c - 1].Controls.Add(tb);
        }
    }
完了。


萍踪侠影 2006-12-19 21:34 发表评论

文章来源: http://www.cnblogs.com/floatping/archive/2006/12/19/597224.html

你可能感兴趣的:(GridView)