[英]ASP.NET Add Hyperlink for whole row of Datatable/Gridview
我正在生成包含一些數據的DataTable,並將其用作GridView的數據源,該GridView將添加到ASP.NET-Webpage。
GridView gvItems = new GridView();
DataTable dtItems = new DataTable();
dtItems.Columns.Add("name");
dtItems.Columns.Add("description");
dtItems.Columns.Add("count");
foreach(var item in items)
{
string name = item.name;
string description = item.description;
string count = item.count.ToString();
string link = "~/Views/Items.aspx?item=" + item.name;
string linkName = item.name;
dtItems.Rows.Add(name, description, count)
}
gvItems.DataSource = dtItems;
gvItems.DataBind();
PlaceHolder.Controls.Add(gvItems)
是否可以為添加的每整行生成一個超鏈接? 如果有人單擊某行內的某處,我希望打開該項目的詳細頁面。
您不能直接向整個行添加鏈接,但是可以使用屬性和一些jQuery來完成。 為此,您需要RowDataBound
事件。 但是,由於要動態創建GridView,因此需要使用代碼添加它。
gvItems.RowDataBound += GvItems_RowDataBound;
gvItems.DataSource = dtItems;
gvItems.DataBind();
然后是RowDataBound方法本身。
private void GvItems_RowDataBound(object sender, GridViewRowEventArgs e)
{
//check if the row is a datarow
if (e.Row.RowType == DataControlRowType.DataRow)
{
//cast the row back to a datarowview
DataRowView row = e.Row.DataItem as DataRowView;
//add the url as an attribute to the row
e.Row.Attributes.Add("data-url", row["link"].ToString());
//give the row a class to the jquery click event can be bound to it
e.Row.Attributes.Add("class", "ClickableRow");
}
}
然后為一些前端代碼處理點擊。
<script type="text/javascript">
$(document).ready(function () {
$(".ClickableRow").click(function () {
location.href = $(this).data("url");
});
});
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.