如何在gridview模板中以编程方式添加控件
本文关键字:编程 方式 添加 控件 gridview | 更新日期: 2023-09-27 18:30:14
我想在我的网格视图中添加控件标签,可以用数据表添加吗?这是我的代码:
<asp:GridView ID="reportScheduleDetailsGridView"
runat="server"
AutoGenerateColumns="False">
</asp:GridView>
我尝试使用标签html跨度,但它没有呈现:
string queryString = @"SELECT * FROM [table1]";
SqlCommand cmd = new SqlCommand(queryString, connOkto);
using (SqlDataReader sdrMaster = cmd.ExecuteReader())
{
while (sdrMaster.Read())
{
DataRow rows = dataTable.NewRow();
rows[0] = sdrMaster["name"].ToString();
for (var x = 1; x < maxCol; x++)
{
queryString = @"SELECT * FROM table2";
cmd = new SqlCommand(queryString, connOkto);
using (SqlDataReader sdrRev = cmd.ExecuteReader())
{
while (sdrRev.Read())
{
blok = "<span></span>";
no = (int)Int16.Parse(sdrRev["no"].ToString());
}
}
rows[x] = blok;
if (no > 1)
{
no--;
}
else
{
blok = "";
}
}
dataTable.Rows.Add(rows);
} }
我不知道,如何在gridview中添加控件asp,比如标签。请帮忙,谢谢。
OnRowDataBound
事件。添加一个占位符,比如在网格视图的<ItemTemplate>
内部。
<asp:GridView ID="EmpGridView" OnRowDataBound="EmpGridView_RowDataBound"
<ItemTemplate>
<asp:PlaceHolder ID="placeholder1" runat="server"></asp:PlaceHolder>
</ItemTemplate>
...></asp:GridView>
Ang你的代码隐藏文件将有:
protected void EmpGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Create a label control
Label lbl = new Label();
lbl.Text="MyDynamic Label";
lbl.ID="lbl1"; // use ID values you prefer
// lets create one more control for example
LinkButton btnlink = new LinkButton();
btnlink.Text = "Delete";
btnlink.ID = "btnDelete";
linkb.Click += new EventHandler(btnlink_Click);
// add the controls to your placeholder inside <ItemTemplate>
PlaceHolder phld = e.Row.FindControl("Placeholder1") as PlaceHolder;
phld.Controls.Add(btnlink);
phld.Controls.Add(lbl);
//code to add the control to only a specific COLUMN/ Cell
e.Row.Cells[1].Controls.Add(btnlink); // adding to 2nd Column
// adding to last column..
e.Row.Cells[EmpGridView.Columns.Count - 1].Controls.Add(btnlink);
}
}
希望这种将控件添加到Templates以及GridView单元格中的各种方法对您有所帮助。