GridView 동적 바인딩 열

GridView1.DataSource = BLL.GetDataItem();//    
        //    GridView      :
        //GridView1.Columns.RemoveAt(1); 
        //     GridView     :
        //           
        BoundField column = new BoundField();
        column.HeaderText = "   ";
        //column.SortExpression = "date1";//       
        column.DataField = "date1";//      (    )
        //       GridView
        //GridView1.Columns.Add(column);
        //----         
        GridView1.Columns.Insert(1, column);//      (      )
        GridView1.DataBind();

sq 조회 l에서 모든 데이터를 조회할 때 이 방법으로 동적 귀속을 하면 됩니다.Insert 방법을 사용하여 동적 열을 삽입하면 GridView의 컨트롤이 비워지고 직접 귀속된 Text 값만 남습니다. GridView의 Enable ViewState를False로 설정합니다.
상례는 BoundField로 집합에 가입하는 것이다.GridView에 TemplateField를 동적으로 추가하려면 새 TemplateField를 만들고 적절한 템플릿을 정의한 다음 집합Columns에 TemplateField를 추가해야 합니다.
msdn 공식에서 제공하는 동적 TemplateField 추가 방법
두 가지 방법을 데모와 결합시키다
프런트 페이지 1개Button 1개GridView 1개
<asp:Button ID="Button1" runat="server" Text="  " onclick="Button1_Click" />
<div>
            <asp:GridView ID="GridView1" runat="server" DataKeyNames="RequireNo" 
                EnableViewState="False" ShowFooter="true"
            CssClass="gridview" width="99%" Font-Size="X-Small" Font-Bold="true" EmptyDataText="    "  
            AutoGenerateColumns="False" RowStyle-HorizontalAlign="center" 
                OnRowDataBound="GridView1_RowDataBound">
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" Height="25px"/>
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" />
            <EditRowStyle BackColor="#2461BF" />
            <AlternatingRowStyle BackColor="#D1DDF1" />
            <RowStyle HorizontalAlign="Center" Height="25px" BackColor="#EFF3FB"/>
            <EmptyDataRowStyle ForeColor="Red" HorizontalAlign="Center" />
            <Columns>
                <asp:TemplateField HeaderText="  ">
                    <ItemTemplate>
                        <asp:LinkButton ID="LinkButton1" Font-Size="XX-Small" CommandName="Select" runat="Server"> <%# Eval("RequireNo")%> </asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="Require_Title" HeaderText="    " ItemStyle-width="230px" HeaderStyle-Font-Size="XX-Small" ItemStyle-Font-Size="XX-Small" />                
                <asp:TemplateField HeaderText="  ">
                    <HeaderTemplate>
                        <input id="chkAll" onclick="javascript:SelectAllCheckboxes(this);" runat="server" type="checkbox" />
                    </HeaderTemplate>
                    <ItemTemplate>
                        <asp:CheckBox ID="chk" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                
                </Columns>                                
        </asp:GridView>
        </div>
백엔드, GridView에 BoundField와 TextBox(TemplateField)를 동적으로 연결합니다
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Model;
using BLL;
using DBUtility;

public partial class SystemRequire_RequireList : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        RequireInfo a = new RequireInfo();
        a.Department = "IT";
        GridView1.DataSource = Require.GetRequireListByA(a);
         //                 ,       
        for (int i = 1; i <= GridView1.Columns.Count; i++)
        {
            if (i > 1 && i < GridView1.Columns.Count - 2)
            {
                GridView1.Columns.RemoveAt(i);
            }
        }
        //    GridView      :
        //GridView1.Columns.RemoveAt(1); 
        //     GridView     :
        //           
        BoundField column = new BoundField();
        column.HeaderText = "  ";
        //column.SortExpression = "subcompany";//       
        column.DataField = "subcompany";//      (    )        
        //       GridView
        //GridView1.Columns.Add(column);
        //----         
        GridView1.Columns.Insert(1, column);//      (      )
        TemplateField customField = new TemplateField();//    System.Web.UI.WebControls;
        customField.ItemTemplate = new GridViewTemplate(DataControlRowType.DataRow, "Proposer");
        customField.HeaderTemplate = new GridViewTemplate(DataControlRowType.Header, "Proposer");
        // Add the field column to the Columns collection of the
        // GridView control.
        GridView1.Columns.Insert(2, customField);
        GridView1.DataBind();
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //     ,      
            e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#66CCFF'");
            //     ,      
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
        }
    }
}
public class GridViewTemplate : ITemplate
{
    private DataControlRowType templateType;
    private string columnName;

    public GridViewTemplate(DataControlRowType type, string colname)
    {
        templateType = type;
        columnName = colname;
    }

    public void InstantiateIn(System.Web.UI.Control container)
    {
        switch (templateType)
        {
            case DataControlRowType.Header:
                Literal lc = new Literal();
                lc.Text = "<b>" + columnName + "</b>";
                container.Controls.Add(lc);
                break;
            case DataControlRowType.DataRow:
                TextBox Name = new TextBox();
                Name.DataBinding += new EventHandler(this.Name_DataBinding);
                container.Controls.Add(Name);
                break;
            default:
                // Insert code to handle unexpected values.
                break;
        }
    }

    private void Name_DataBinding(Object sender, EventArgs e)
    {
        TextBox l = (TextBox)sender;
        GridViewRow row = (GridViewRow)l.NamingContainer;
        l.Text = DataBinder.Eval(row.DataItem, "Proposer").ToString();
    }
}

좋은 웹페이지 즐겨찾기