GridView CheckBox PostBack And Paging
By AzamSharp
Views: 16961

Introduction:

Few days back one gentleman asked me that how can I select a row within a GridView control using CheckBox while the auto-postback property of the CheckBox is set to true. Another gentleman asked me that how can he export the complete GridView to Excel sheet which has paging enabled. In the article I will going to address those two questions.

GridView with CheckBoxes Auto-PostBack = true:

Let's first see that how can we select the value of the GridView columns when we check the checkbox which is contained inside the GridView control. Here is the GridView HTML code:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">

<Columns>

<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />

<asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />

<asp:TemplateField HeaderText="Select">

<ItemTemplate>

<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="True" OnCheckedChanged="CheckBox1_CheckedChanged" />

</ItemTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>

As you can see I have two bound columns and one template column which contains the CheckBox. The AutoPostBack property of the CheckBox control is set to true which means the page will reload when you select a CheckBox.

When the CheckBox is clicked the CheckBox_CheckedChanged event is fired. We need to implement this method in order to catch the row in which the CheckBox is checked.

protected void CheckBox1_CheckedChanged(object sender, EventArgs e)

{

ClearCheckBoxes();

CheckBox checkbox = (CheckBox)sender;

checkbox.Checked = true;

GridViewRow row = (GridViewRow)checkbox.NamingContainer;

DisplayMessage(row.Cells[1].Text);

}

One thing I like to point out is that when you select a different CheckBox then your first selection is not cleared. In order to make your previous selections clear you can implement a simple ClearCheckBoxes method which will iterate through the GridView control and clear all the CheckBoxes.

private void ClearCheckBoxes()

{

foreach (GridViewRow row in GridView1.Rows)

{

CheckBox ch = (CheckBox) row.FindControl("CheckBox1");

ch.Checked = false;

}

}

As, you can see that in ClearCheckBoxes method I am simply clearing all the CheckBoxes inside the GridView control. The DisplayMessage method simply assigns the CategoryName to the Label's Text property since CategoryName belongs to Cell[1].

Exporting all Pages of the GridView to an Excel File: 

Now, to answer the seconds question. Well, this is pretty straight forward simply turn off the paging when you export the GridView and turn it on again after the exportation is completed. Here is the Button click code that is used to export the entire GridView (This will export the complete GridView data containing in all the pages) to Excel sheet.

Response.Clear();

        Response.AddHeader("content-disposition",
        "attachment;filename=FileName.xls");

        Response.Charset = "";

        
// If you want the option to open the Excel file without saving than

        // comment out the line below

        // Response.Cache.SetCacheability(HttpCacheability.NoCache);

        
Response.ContentType = "application/vnd.xls";

        System.IO.StringWriter stringWrite = 
new System.IO.StringWriter();

        System.Web.UI.HtmlTextWriter htmlWrite =
        
new HtmlTextWriter(stringWrite);

        
// turn off paging 
        
GridView1.AllowPaging = false;
        BindData(); 
        

        GridView1.RenderControl(htmlWrite);

        Response.Write(stringWrite.ToString());

        Response.End();

        
// turn the paging on again 
        
GridView1.AllowPaging = true
;
        BindData();

I have made the important lines bold.

I hope you liked this article, happy coding!

If you are one of the thousands that visit GridViewGuy for your .NET articles and resources, you might be interested in making a donation. Extra cash helps pay for the hosting services and speed things up around here, and makes this website possible.

Make a Donation

Once, again thank you very much and remember its because of you FINE people that this website is up and running.

 

Export Button is a custom control that let's you export your DataGrid or TextBox data to several different formats. The control is extremely easy to use and also exposes design time features. In this article I will discuss some of the features of the Export Button and how it benefits the developer.

BUY IT NOW

 

 

By AzamSharp


Enter Comment/Feedback
  •  
  •  
  •  
  •  
  •  

Comments/Feedbacks
Subject: Export to excel
Name: prince
Date: 2/28/2007 4:26:50 AM
Comment:
Hi

thanks for the fatastic piece of code. i was struggling for past one week for this code.

i need one more help. can i use Microsoft Excel library 11.0 to export data in asp.net. if u have any code or good links please send it me...

Regards,
Prince
Subject: Remember to check the postback!!!
Name: Fabrizio Farenga
Date: 3/30/2007 1:09:34 PM
Comment:
Just a suggestion to newbies: if you want to use the code above, and if you create the GridView in the Page_Load event, remember to check the IsPostBack!

You must create the GridView only if IsPostBack!=true.

If you don't do this, the GridView will be created again when you hit the submit button, and the checkbox will be all unchecked and they return false.
Subject: HeaderText
Name: Chris
Date: 4/20/2007 8:04:59 AM
Comment:
Any idea how to export the Gridview's HeaderText property? I only get the DataField property in my Excel columns.
Subject: Error
Name: Indra
Date: 7/24/2007 11:49:06 PM
Comment:
hi,
I runt he above code for paged gridview but the thing is the data repeated twice.
knidly help.
Subject: Save directly to server hard drive
Name: Twoeyez
Date: 8/6/2007 3:36:33 AM
Comment:
how can I save the xls file directly on server's hard drive without confirmation!
Subject: RE: Save directly to server hard drive
Name: AzamSharp
Date: 8/6/2007 1:43:37 PM
Comment:
Hi Twoeyez,

Please post your question on the appropriate form. For not asking the user to save the XLS file you can simply remove the SetCache method from the response.
Subject: Gridview
Name: canan
Date: 8/31/2007 5:06:43 AM
Comment:
Thanks for all your articles, when I need help, they always help me.Especially your gridview articles are perfect. I wish you share solution files of your examples, because I sometimes need all solution file to understand what you mean. Thank you again:)
Subject: Problem
Name: Manu
Date: 8/31/2007 7:49:51 AM
Comment:
Hi,

I have a situation where instead of check box , I have radio button.
Like you have teh chekc box chnaged event, I cant get to generate teh radio button checked changed event.
If i double click the radio btoon in the gridview on teh html side, gridview selected index change event is generated not teh radio button. how can i get to generate teh radio button checked event.

Any help would be highly appreciated.
Manu
Subject: thanks
Name: G thrivikram
Date: 11/13/2007 9:11:46 PM
Comment:
Hi i used ur code its executing perfectly.
Very thanks for u.
Subject: thanks
Name: G thrivikram
Date: 11/13/2007 9:11:49 PM
Comment:
Hi i used ur code its executing perfectly.
Very thanks for u.
Subject: Doubt in DropdownList
Name: karthic
Date: 12/3/2007 11:22:34 PM
Comment:
hi all,

thanks for the checkbox checked in grinview

i need one more help from you..

i have one textbox and dropdownlist..

get value in dropdowlist which same as textbox starting letter , when only enter the value in textbox..

for eg,
suppose you enter the starting letter d,
then you get value thats starting with

Subject: RE: Doubt in DropDownList
Name: AzamSharp
Date: 12/5/2007 1:42:36 PM
Comment:
Hikarthic ,

You can use JavasScript and with each typed better trigger a method that will find the appropriate word inside the DropDownList.
Subject: Excel 2007
Name: Thomas
Date: 12/21/2007 1:37:36 AM
Comment:
Hi,
your code works fine with excel 2003. But on machines with the newer excel 2007 it doesn't work. Alle html is going into one cell...

Any hints?

Regards
Thomas
Subject: Postback after save dialog
Name: Wei
Date: 2/5/2008 1:47:56 AM
Comment:
Hi,

any alternatives that i can get postback after the save dialog. In my aspx page, i have a listbox with 3 items. The user can choose one and click on the button. The save dialog will be activated as expected. However, after that, no more postback can be done. Therefore, the user cannot choose another table to export.
Subject: issue regarding the above code
Name: Ayaskant Mishra
Date: 2/21/2008 2:12:36 AM
Comment:
hi all. when i tried the above code i got an error prompt i.e
An exception of type 'System.InvalidOperationException' occurred in System.Web.dll but was not handled in user code

Additional information: RegisterForEventValidation can only be called during Render();
pls help.thanks in advance.
Subject: hyperlinkfield
Name: newbee
Date: 3/17/2008 9:22:45 AM
Comment:
Can anyone help me understand how to export a hyperlinkfield that id dynamically created by the application can be exported to excel. Thanks.



Join WebHost4Life.com






Copyright GridViewGuy 2007-2008