GridView的HyperLinkField的DataNavigateUrlFormatString如何使用自定義的變量,而不是數據庫綁定的值


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);
                }
                
            }
        }
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM