开发者

ArgumentOutOfRangeException was unhandled by user code - (ASP .net)

开发者 https://www.devze.com 2023-01-02 18:02 出处:网络
I use a GridView to display the records from the database. Also i\'ve attached a Hyperlink to the GridView using TemplateField.

I use a GridView to display the records from the database. Also i've attached a Hyperlink to the GridView using TemplateField. When I try to add "onclick" attribute to the HyperLink inside the RowDateBound event, I get the following error..

   GridView1.DataKeys[e.Row.RowIndex].Value = 'GridView1.DataKeys[e.Row.RowIndex]' threw an exception of type 'System.ArgumentOutOfRangeException'

Message = "Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index"

This is the coding inside the RowDataBound mentod..

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                HyperLink HyperLink1 = (HyperLink)e.Row.FindControl("HyperLink1");

//The following line makes the error
                HyperLink1.Attributes.Add("onclick", "ShowMyModalPopup('" + GridView1.DataKeys[e.Row.RowIndex].Value + "')");

            } 
        }

This is "ShowMyModalPopup" function in javascript

<script type="text/javascript">
        function ShowMyModalPopup(userpk)
        { 
         var modal = $find('ModalPopupExtender1'); 
         modal.show(); 
         WebService.FetchOneUser(userpk,DisplayResult);
        }
</script>

Eventhough the value of index is zero, it throw开发者_如何转开发s this exception. Can anyone please explain me why this error occurs..

Many thanks in advance..


I'm going to guess that the reason it doesn't work is because RowDataBound fires before the GridView actually gets the data. The reason for this is that this particular event is used to manipulate data before final display. So, when you call this code:

GridView1.DataKeys[e.Row.RowIndex].Value

It does not have any data in the grid yet. If you can access this value in another way, such as another column on the row (you have access to the row itself), this would be the best way to do it. If not, then consider adding a column for the data you need to pass into ShowMyModalPopup, and then hiding it on the grid itself. This way you can form the hyperlink based on the row data itself and not relying on it to already be in the GridView.

0

精彩评论

暂无评论...
验证码 换一张
取 消