开发者

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

I have loaded a DataTable with 4 elements and attached it to a dataset. I have bound the dataset to a GridView. I am using the following code to fill the 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();

This works just fine and fills the 4 column开发者_如何学Gos of the Gridview from top to bottom, left to right as intended. What I would like to do is to make the NavigateURL of each column be the actualvalue in the column. As an example the values Url# represent the values printed out in the Gridview, but I also want them to be hyperlink urls?

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

Any suggestions would be appreciated. What the ultimate goal is, is to do a SQL Query pulling URL locations out of a database, then filling a GridView's columns from top to bottom, left to right with the values pulled in the query and making each a hyperlink. If there is a better way to accomplish this, I would appreciate a steer in the right direction.


In the OnDataBound event you can actually get the item that is databound to that row. So my suggestion is get that item and set the hyperlink's NavigateURL to whatever value you want.

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"];
  }
}

EDIT: By OnDataBound I meant to say OnRowDataBound

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜