简体   繁体   English

如何在动态添加的表中添加动态链接

[英]How to add a dynamically link in a dynamically added table

I'm a newbie and struggle to add a link, showed like an img in a dynamically added table. 我是一个新手,努力添加一个链接,就像在动态添加的表中的img所示。

 string search = Search.Text;
 IMyData members = new MyData();
 DataTable dt = new DataTable();

 dt = members.Search(search);

 Table t = new Table();
 t.ID = "tblTable";
 TableRow row = null;


 for (int i = 0; i < dt.Rows.Count; i++)
 {
    HyperLink link = new HyperLink();
    row = new TableRow();
    for (int j = 0; j < dt.Columns.Count; j++)
    {
       TableCell cell = new TableCell();
       if (j == dt.Columns.Count - 1)     //This last field may hava a number
       {
          if (Convert.ToInt32(dt.Rows[i][j].ToString()) > 0)
          {
             link.ID = "link" + i + "_" + j;
             link.NavigateUrl = "members.aspx?showLease=" + dt.Rows[i][j].ToString();
             link.ImageUrl = "img/document.png";
             Page.Controls.Add(link);      // How to put this in a cell, not on page 
          }
          else
          { 
             cell.Text = dt.Rows[i][j].ToString();
          }
        }
        row.Cells.Add(cell);
      }
      t.Rows.Add(row);
    }
    pnlTable.Controls.Add(t);

How can I put the Hyperlink to the cell, and not to the Page? 如何将超链接放到单元格而不是页面上?

Thanks 谢谢

You can add control in TableCell the way you are doing in Page. 您可以像在Page中一样在TableCell中添加控件。 Change your code like this 像这样更改代码

Page.Controls.Add(link);//Will add control in page
cell.Controls.Add(link);//Will add control in table cell

See below, I changed Page.Controls.Add(link) to cell.Controls.Add(link) and moved your Hyperlink declaration into the cell loop. 参见下文,我将Page.Controls.Add(link)更改为cell.Controls.Add(link),并将您的Hyperlink声明移至单元格循环中。 Otherwise if will only be added in the last cell. 否则,仅将其添加到最后一个单元格中。 But if I see your code it seems that only the last cell will have link or text because of the j == dt.Columns.Count - 1 但是,如果看到您的代码,由于j == dt.Columns.Count-1,似乎只有最后一个单元格具有链接或文本。

for (int i = 0; i < dt.Rows.Count; i++) {
    row = new TableRow();
    for (int j = 0; j < dt.Columns.Count; j++)
    {
       HyperLink link = new HyperLink();
       TableCell cell = new TableCell();
       if (j == dt.Columns.Count - 1)     //This last field may hava a number
       {
          if (Convert.ToInt32(dt.Rows[i][j].ToString()) > 0)
          {
             link.ID = "link" + i + "_" + j;
             link.NavigateUrl = "members.aspx?showLease=" + dt.Rows[i][j].ToString();
             link.ImageUrl = "img/document.png";
             cell.Controls.Add(link);      // How to put this in a cell, not on page 
          }
          else
          { 
             cell.Text = dt.Rows[i][j].ToString();
          }
       }
       row.Cells.Add(cell);
     }
     t.Rows.Add(row);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM