如何在gridview模板中以编程方式添加控件?

时间:2013-09-04 01:34:24

标签: c# asp.net gridview

我想在gridview中添加控件标签,是否可以添加数据表? 在这里我的代码:

 <asp:GridView ID="reportScheduleDetailsGridView" 
               runat="server" 
               AutoGenerateColumns="False">
 </asp:GridView>

我尝试使用标签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);
    } }

我不知道,如何在gridview中添加控件asp,就像标签一样。 请帮助,谢谢。

1 个答案:

答案 0 :(得分:2)

添加控件的一种方法是使用GridView的OnRowDataBound事件。在网格视图的<ItemTemplate>内添加一个placeHolder。

<asp:GridView ID="EmpGridView" OnRowDataBound="EmpGridView_RowDataBound"
     <ItemTemplate>
     <asp:PlaceHolder ID="placeholder1" runat="server"></asp:PlaceHolder>
     </ItemTemplate>
...></asp:GridView>

您的代码隐藏文件将包含:

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);
            }
        }

希望通过各种方式将控件添加到模板以及GridView的单元格中可以帮助您。