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

时间:2013-03-18 15:53:39

标签: c# asp.net dynamic

我是新手并且很难添加链接,在动态添加的表格中显示为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);

如何将超链接放到单元格而不是页面?

由于

2 个答案:

答案 0 :(得分:0)

您可以按照您在Page中的方式在TableCell中添加控件。像这样改变你的代码

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

答案 1 :(得分:0)

见下文,我将Page.Controls.Add(link)更改为cell.Controls.Add(链接)并将您的超链接声明移动到单元循环中。否则,只会在最后一个单元格中添加。 但是,如果我看到你的代码,似乎只有最后一个单元格会有链接或文本,因为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);
}