繁体   English   中英

如何以编程方式动态填充gridview的绑定(超链接)列,然后将该列的值用作URL?

[英]How do I programmatically fill a gridview's bound (hyperlink) column dynamically and then use the column's value as the url?

我已加载具有4个元素的DataTable并将其附加到数据集。 我已经将数据集绑定到GridView。 我正在使用以下代码填充GridView:

ds.Tables.Add(dt);  
GridView1.DataSource = ds.Tables[0];
foreach (DataColumn dcc in ds.Tables[0].Columns)  
{
    HyperLinkField mycol = new HyperLinkField();
    mycol.DataTextField = dcc.Caption.ToString();

    mycol.HeaderText = dcc.Caption;
    mycol.Target="_blank";
    mycol.HeaderStyle.Width = 10;
    mycol.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
    mycol.ItemStyle.ForeColor = System.Drawing.Color.Black;
    GridView1.Columns.Add(mycol);
    mycol.Visible = true;
}
GridView1.DataBind();

这工作得很好,并按预期从上到下,从左到右填充了Gridview的4列。 我想做的是使每一列的NavigateURL成为该列中的实际值。 例如,值Url#代表在Gridview中打印出的值,但我也希望它们是超链接url?

COl1    Col2    Col3    Col4
Url1    Url2    Url3    Url4
Url5    Url6    Url7    Url8

任何建议,将不胜感激。 最终目标是执行一个SQL查询,将URL位置从数据库中拉出,然后使用查询中拉出的值从上至下,从左至右填充GridView的列,并使每个超链接。 如果有更好的方法可以做到这一点,我将朝正确的方向前进。

实际上,在OnDataBound事件中,您可以获取数据绑定到该行的项目。 因此,我的建议是获取该项目并将超链接的NavigateURL设置为所需的任何值。

protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType == DataControlRowType.DataRow){
    var item = (DataRow)e.Row.DataItem;
    //I'm assuming the type is DataRow from you above example
    var linkCol = (HyperLinkField)e.Row.Cells[yourHyperLinkIndex] 
    linkCol.NavigateUrl = item["columnName"];
  }
}

编辑:通过OnDataBound我的意思是说OnRowDataBound

暂无
暂无

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

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