Sometimes we may need to pass values (server side) to the client functions (javascript) on the GridView controls. In such case, we can attach the javascript functions to the GridView controls from code-behind using the RowDataBound event of the GridView.

I have a GridView that is bound to an ObjectDataSource, and I have converted one of the column into a TemplateField, so that I can access the controls in the underlying templates.

[code:html]
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CountryId"
        DataSourceID="ObjectDataSource1">
        <Columns>
            <asp:TemplateField HeaderText="TestColumn">
                <ItemTemplate>
                    <asp:Button ID="Button1" runat="server" Text='Click Me'></asp:Button>
                </ItemTemplate>
            </asp:TemplateField>

[/code]



To attach a javascript function the Button1, we add the attributes in the RowDataBound event ( I use RowDataBound event because, you can access the underlying DataItem of the row, so that we can pass the database values to the javascript function. You can also use the RowCreatedEvent of the GridView to add the attributes.)

[code:c#]
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string paramValue = "somevalue";
            Button btnTest = (Button)e.Row.FindControl("Button1");
            if (btnTest != null)
                btnTest.Attributes.Add("onClick", "javascript:methodName('" + paramValue + "');");
        }
    }
[/code]


This way you can pass parameters from code-behind to javascript methods for the controls inside a GridView. My next post will be on how to access the underlying data in the RowDataBound event which helps in manipulating and customizing the way data is presented

E Screw