asp.net customdatagrid 绑定数据用到的ItemDataBound 中的HyperLinkColumn 的跳转链接 通过C#后台 处理的方法

一.前台html代码:

<tittle:CustomDataGrid id="grdResult" runat="server" Width="1000px" GridWidth="785px" DataKeyField="ID"
AutoGenerateColumns="False" AllowSorting="true" CellPadding="0" FreezeColumns="0" FreezeHeader="False"
FreezeRows="0" PageSize="20" 
onitemdatabound="grdResult_ItemDataBound">
<PagerStyle HorizontalAlign="Center" ForeColor="#C5D7ED" Mode="NumericPages"></PagerStyle>
<Columns>
<asp:BoundColumn DataField="MaterialCode" HeaderText="部品代码" SortExpression="MaterialCode" HeaderStyle-Width="150px" >
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="SnNum" HeaderText="SN" SortExpression="SnNum" HeaderStyle-Width="110px" >
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:BoundColumn>
<asp:BoundColumn Visible="False" DataField="InvoiceId"></asp:BoundColumn>
<asp:BoundColumn Visible="False" DataField="Url"></asp:BoundColumn>
<asp:HyperLinkColumn DataTextField="RelatedRecordNo" HeaderText="关联单据编号" SortExpression="RelatedRecordNo" HeaderStyle-Width="180px" >
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:HyperLinkColumn>
</Columns>
</tittle:CustomDataGrid>

二、C#后台处理:

protected void grdResult_ItemDataBound(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Pager|| e.Item.ItemType == ListItemType.Header
|| e.Item.ItemType == ListItemType.Footer) //判断是否为页眉,页脚
{
return;
}
else
{

HyperLink link = (HyperLink)e.Item.Cells[4].Controls[0];//第3行HyperLinkColumn对象
link.NavigateUrl = string.Format("javascript:window.location('{0}.aspx?MasterID={1}');", e.Item.Cells[3].Text, e.Item.Cells[2].Text);
//e.Item.Cells[3].Text 为url路径,前台对应为:<asp:BoundColumn Visible="False" DataField="Url"></asp:BoundColumn> Visible="False"为不可见
//e.Item.Cells[2].Text 为ID 前台对应为:<asp:BoundColumn Visible="False" DataField="InvoiceId"></asp:BoundColumn>
}
}

//大家也可以试试用这个:

if (e.Item.ItemType==ListItemType.Item||e.Item.ItemType==ListItemType.AlternatingItem)
{
HyperLink link = (HyperLink)e.Item.Cells[4].Controls[0];//第3行HyperLinkColumn对象
link.NavigateUrl = string.Format("javascript:window.location('{0}.aspx?MasterID={1}');", e.Item.Cells[3].Text, e.Item.Cells[2].Text);
//e.Item.Cells[3].Text 为url路径,前台对应为:<asp:BoundColumn Visible="False" DataField="Url"></asp:BoundColumn> Visible="False"为不可见
//e.Item.Cells[2].Text 为ID 前台对应为:<asp:BoundColumn Visible="False" DataField="InvoiceId"></asp:BoundColumn>
}

 注意:千万不要在ItemDataBound里面存在查询数据库的方法,因为会执行很多遍,不合理。

原文地址:https://www.cnblogs.com/allenhua/p/3043826.html