[英]How to populate a gridview dropdown dynamically depending on another column's value?
[英]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.