Gerard
Gerard

Reputation: 43

Adding a new column with buttons in gridview and binding data to it

I have added a button for Print in my gridview table as follows

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
                    AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ID" 
                    DataSourceID="SqlDataSource2" 
                    onselectedindexchanged="GridView1_SelectedIndexChanged" Width="522px">
                    <Columns>
                        <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" 
                            ReadOnly="True" SortExpression="ID" />
                        <asp:BoundField DataField="Story_number" HeaderText="Story_number" 
                            SortExpression="Story_number" />
                        <asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date" />
                        <asp:BoundField DataField="Memory_card" HeaderText="Memory_card" 
                            SortExpression="Memory_card" />
                        <asp:BoundField DataField="Story_Name" HeaderText="Story_Name" 
                            SortExpression="Story_Name" />
                        <asp:ButtonField ButtonType="Button" Text="print" />
                    </Columns>
                </asp:GridView>

Please help me with the c# code for this button. When the button is pressed I need it to redirect to a page (print.aspx). I have been trying the following code but it does not work .Thanks in advance for your help.

Session["id"] = GridView1.SelectedRow.Cells[0].Text;
Response.Redirect("Print.aspx");

Upvotes: 0

Views: 1864

Answers (1)

Cesar BA
Cesar BA

Reputation: 146

Instead of buttonField, use template field

<asp:TemplateField>
    <ItemTemplate>
        <asp:ImageButton ID="ButtonPrint" runat="server" CssClass="yourCssClassIsNeedIt" OnClick="printRegFunction"
            CommandArgument='<%# Bind("id") %>' ImageUrl="images/button.png"/>
    </ItemTemplate>
</asp:TemplateField>

your server code or behind code here:

protected void printRegFunction(object sender, ImageClickEventArgs e)
    {
        Session["id"] = ((ImageButton)sender).CommandArgument;
        Response.Redirect("Print.aspx");

    }

Upvotes: 3

Related Questions