GridView的HyperLinkField的DataNavigateUrlFormatString如何使用自定义的变量,而不是数据库绑定的值

时间:2023-03-08 16:37:32

GridView的HyperLinkField的DataNavigateUrlFormatString如何使用自定义的变量,而不是数据库绑定的值.报错:指定的参数已超出有效值的范围。参数名: index

当我们在GridView中,偷懒,直接绑定数据库返回的 datatable的时候,用  HyperLinkField  的 DataNavigateUrlFields 来绑定数据库的字段,并且用 DataNavigateUrlFormatString 来显示url链接是很方便的。

如果是要绑定datatable里面的2个字段,则是把 DataNavigateUrlFields 后面的值用逗号分开 DataNavigateUrlFields=“UserId,QQNumber” DataNavigateUrlFormatString='List.aspx?ID={0}&qq={1}'

<asp:GridView ID="GVTeacher" runat="server" >
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="UserId" DataNavigateUrlFormatString='List.aspx?ID={0}' DataTextField="老师名称" Target="show" HeaderText="老师名称"/>
<asp:BoundField DataField="回答总数" HeaderText="回答总数" />
</Columns>
</asp:GridView>

但是如果我们想在超链接里面,写一个非数据库的字段的值呢?或者是写自己定义的一个变量的值呢?

例如:下面这个超级链接,他的绑定数据库的字段是 “学生名称”,但是这个URL 并没有指定(也就是没有写 DataNavigateUrlFields 和 DataNavigateUrlFormatString)

如果我们的URL既想用到数据库里面的值,又想用到自己的变量,怎么来做?

这个时候需要在 GridView上 加上行事件,onrowdatabound="GVStudent_RowDataBound"

<asp:GridView ID="GVStudent" runat="server" BackColor="White" BorderColor="White"
Visible="false" onrowdatabound="GVStudent_RowDataBound">
<Columns>
<asp:HyperLinkField DataTextField="学生名称" Target="show" HeaderText="学生名称"/>
<asp:BoundField DataField="提问总数" HeaderText="提问总数" />
</Columns>
</asp:GridView>

然后在后台的CS上,加上以下代码

protected void GVStudent_RowDataBound(object sender, GridViewRowEventArgs e)
{
//this.GVStudent.EditIndex != e.Row.DataItemIndex
//这一句话是为了防止报错
//异常详细信息: System.ArgumentOutOfRangeException: 指定的参数已超出有效值的范围。参数名: index
if (e.Row.RowType == DataControlRowType.DataRow && this.GVStudent.EditIndex != e.Row.DataItemIndex)
{
DataRowView DDR = e.Row.DataItem as DataRowView; HyperLink temp = e.Row.Cells[0].Controls[0] as HyperLink;
if (temp!=null)
{
temp.NavigateUrl = string.Format(@"StudentList.aspx?ID={0}&start={1}&end={2}", DDR["UserId"], txtStart.Text, txtEnd.Text);
} }
}