将绑定字段添加到代码隐藏文件 C# 中的网格视图



我想在 C# asp.net 代码隐藏文件中创建新的网格视图。正是我想通过 c# 代码将这样的绑定字段添加到网格视图中:

<asp:BoundField DataField="p_type" HeaderText="type" ItemStyle-Width="70px">
   <ItemStyle Width="70px"></ItemStyle>
</asp:BoundField>

我使用以下代码构建了新的网格视图:

 GridView GridView1 = new GridView();
 GridView1.AllowPaging = false;
 GridView1.CellPadding = 4;
 GridView1.GridLines= GridLines.None;
 GridView1.AutoGenerateColumns = false;

我想向这个网格视图添加新的边界字段。如何使用 C# 代码做到这一点?

本文解释了如何在 C# 代码中实现网格视图:http://www.codeproject.com/Articles/13461/how-to-create-columns-dynamically-in-a-grid-view下面是创建它的示例代码:

public partial class _Default : System.Web.UI.Page
{
    #region constants
    const string NAME = "NAME";
    const string ID = "ID";
    #endregion
    protected void Page_Load(object sender, EventArgs e)
    {
        loadDynamicGrid();
    }
    private void loadDynamicGrid()
    {
        #region Code for preparing the DataTable
        //Create an instance of DataTable
        DataTable dt = new DataTable();
        //Create an ID column for adding to the Datatable
        DataColumn dcol = new DataColumn(ID ,typeof(System.Int32));
        dcol.AutoIncrement = true;
        dt.Columns.Add(dcol);
        //Create an ID column for adding to the Datatable
        dcol = new DataColumn(NAME, typeof(System.String));
        dt.Columns.Add(dcol);
        //Now add data for dynamic columns
        //As the first column is auto-increment, we do not have to add any thing.
        //Let's add some data to the second column.
        for (int nIndex = 0; nIndex < 10; nIndex++)
        {
            //Create a new row
            DataRow drow = dt.NewRow();
            //Initialize the row data.
            drow[NAME] = "Row-" + Convert.ToString((nIndex + 1));
            //Add the row to the datatable.
            dt.Rows.Add(drow);
        }
        #endregion
        //Iterate through the columns of the datatable to set the data bound field dynamically.
        foreach (DataColumn col in dt.Columns)
        {
            //Declare the bound field and allocate memory for the bound field.
            BoundField bfield = new BoundField();
            //Initalize the DataField value.
            bfield.DataField = col.ColumnName;
            //Initialize the HeaderText field value.
            bfield.HeaderText = col.ColumnName;
            //Add the newly created bound field to the GridView.
            GrdDynamic.Columns.Add(bfield);
        }
        //Initialize the DataSource
        GrdDynamic.DataSource = dt;
        //Bind the datatable with the GridView.
        GrdDynamic.DataBind();
    }
}

相关内容

  • 没有找到相关文章

最新更新