如何动态ñ复选框列添加到GridView的ASP.NET [英] How to add dynamic n checkbox columns to gridview ASP.NET
问题描述
例如:<?code> mypage.aspx NUM = XXX
我如何添加一个 NUM
复选框列的的GridView 由code-背后mypages?
How can I add a num
checkbox column to Gridview in mypages by code-behind?
我已经加入 NUM
列数据表带参数 typeof运算(布尔)
,但当我装我的页面,该复选框被禁用,所以我不能检查。
I had added num
columns to Datatable with parameter typeof(bool)
but when I loaded mypage, the checkboxes were disabled so I can't check them.
推荐答案
这是我的网格的aspx code
This is my grid aspx code
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="false">
<Columns>
</Columns>
</asp:GridView>
首先添加 NUM
模板字段到你的GridView的数量
First of all add num
number of template fields to your gridview
protected void Page_PreInit(object sender, EventArgs e)
{
int num = Request.QueryString["num"];
for (int i = 0; i < num; i++)
{
TemplateField tf = new TemplateField();
tf.HeaderText = "Status";
gv.Columns.Add(tf);
}
}
添加模板精密组件后,现在我们将添加复选框到GridView。我们写一个函数来添加复选框。下面是code
After adding template feilds, now we will add checkboxes to the gridview. We write a function to add checkboxes. Below is the code
private void AddCheckBox()
{
int num = Request.QueryString["num"];
for (int i = 0; i < num; i++)
{
foreach (GridViewRow row in gv.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox cb = new CheckBox();
cb.Checked = true;
row.Cells[i].Controls.Add(cb);
}
}
}
}
现在把这个功能在您的网格数据绑定的事件。
Now place this function in your grid databound event.
protected void gv_DataBound(object sender, EventArgs e)
{
AddCheckBox();
}
在最后也呼吁在页面加载事件的功能,所以第一次,当电网负荷它显示复选框被选中
At the end also call the function in the page load event so first time when grid loads it shows checkboxes are checked
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
AddCheckBox();
}
}
要检查我的code:
我一个必然费尔德添加到网格视图并绑定一个DataTable网格视图:
To check my code: I add a bound feild to grid view and bind the grid view with a datatable:
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Data" HeaderText="Data" />
</Columns>
</asp:GridView>
在code后面的的Page_Load 事件中,我添加以下code
and in code behind in page_load event i add the following code
DataTable dt = new DataTable();
dt.Columns.Add("Data");
DataRow dr = dt.NewRow();
dr[0] = "Test";
dt.Rows.Add(dr);
gv.DataSource = dt;
gv.DataBind();
和也取得了功能AddCheckBox 1变化
and also made 1 change in the function AddCheckBox as
for (int i = 1; i < num + 1; i++)
以上变化是由因为我在网格视图的列索引0数据绑定费尔德所以我改变它从1开始。
The above change is made because I have a databound feild at index 0 of the grid view columns so I changed it to start from 1.
和下面是结果(页输出)
and here is the result ( page output )
Data Status Status Status Status Status Status Status Status Status Status
Test Checked Checked Checked Checked Checked Checked Checked Checked Checked Checked
经过用于复选框
检查
Checked is used for checkbox is checked
这篇关于如何动态ñ复选框列添加到GridView的ASP.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!