简体   繁体   中英

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 columns 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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