1

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

 <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,比如标签。请帮忙,谢谢。

4

1 回答 1

2

添加控件的一种方法是使用OnRowDataBoundGridView 的事件。<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 单元格中的各种方式对您有所帮助。

于 2013-09-04T04:15:53.220 回答