添加绑定列到GridView控件在codebehind文件C# [英] add boundField to gridview in codebehind file C#
问题描述
我想创建codebehind文件asp.net C#新的GridView。
正是我想通过C#code这样的BoundField添加到GridView:
I want to create new gridview in codebehind file asp.net C#. Exactly I want to add such boundfield to the gridview by c# code:
<asp:BoundField DataField="p_type" HeaderText="type" ItemStyle-Width="70px">
<ItemStyle Width="70px"></ItemStyle>
</asp:BoundField>
我装箱新的GridView有以下code:
I crated new gridview with following code:
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.CellPadding = 4;
GridView1.GridLines= GridLines.None;
GridView1.AutoGenerateColumns = false;
和我想新的绑定列添加到该GridView控件。
如何使与C#code?
And I want to add new boundField to this gridview. How to make that with c# code?
推荐答案
这篇文章解释你在C#code的GridView如何实现:
<一href=\"http://www.$c$cproject.com/Articles/13461/how-to-create-columns-dynamically-in-a-grid-view\">http://www.$c$cproject.com/Articles/13461/how-to-create-columns-dynamically-in-a-grid-view
这里的样本code来创建它:
this article explain you how implement in c# code a gridview : http://www.codeproject.com/Articles/13461/how-to-create-columns-dynamically-in-a-grid-view here a sample code to create it:
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();
}
}
这篇关于添加绑定列到GridView控件在codebehind文件C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!