tags:

views:

47

answers:

1

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 throws this exception. Can anyone please explain me why this error occurs..

Many thanks in advance..

A: 

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.

drharris
How can I achieve this..Can you please guide me..I've to pass the 'userPK' of my 'users' table to the ShowMyModalPopup()
ASr..
Well, if it's already coming into the GridView (through whatever query you specified), all you would need to do is use the code: `e.Row["userPK"].Value` to get that value for the hyperlink. If it's not already coming into the GridView for display, you will need to update the query (or the auto-generated DataTable) to include that. I hope that makes sense; it's hard to explain without knowing the exact circumstances.
drharris

related questions