[英]How add control programmatically in gridview template?
I want add control label in my gridview, is it possible add with datatable? 我想在gridview中添加控件标签,是否可以用datatable添加? here my code: 这是我的代码:
<asp:GridView ID="reportScheduleDetailsGridView"
runat="server"
AutoGenerateColumns="False">
</asp:GridView>
I try use tag html span, but it not render: 我尝试使用标记html span,但不渲染:
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);
} }
I don't know, how can add control asp in gridview, like label. 我不知道,如何在gridview中添加控件asp,如label。 Please help, thanks. 请帮忙,谢谢。
One way to add controls is using OnRowDataBound
event of GridView. 添加控件的一种方法是使用GridView的OnRowDataBound
事件。 Add a placeHolder to say, inside <ItemTemplate>
of your grid view. 在网格视图的<ItemTemplate>
内添加一个placeHolder来表示。
<asp:GridView ID="EmpGridView" OnRowDataBound="EmpGridView_RowDataBound"
<ItemTemplate>
<asp:PlaceHolder ID="placeholder1" runat="server"></asp:PlaceHolder>
</ItemTemplate>
...></asp:GridView>
Ang your code behind file will have: 昂文件后面的代码将具有:
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);
}
}
Hope this various ways of adding controls to Templates as well as in a cell of GridView helps you. 希望通过各种向模板添加控件以及在GridView单元中添加控件的方式对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.