简体   繁体   中英

How can I create a custom web server control for a gridview in asp.net

Visual Studio 2008 
.Net 3.5 
C#

I have a web site that has a lot of pages with grid views. I want to be able to add an "Export to Excel" button on some of the grid views, so I started looking and found Custom Web Server Controls - see this page for an example.

This example of a custom label lets you pass in string parameters as input to the custom control:

<aspSample:WelcomeLabel ID="WelcomeLabel1" 
   runat="server" Text="Welcome" DefaultUserName="Guest">
</aspSample:WelcomeLabel>

I am not exactly sure how to get started. I am thinking that I create a custom Button control, where the id of the grid view can be passed in as a parameter - I'm just not sure how to do that, if it is even possible.

I don't think I need to create a custom grid view control... Or, maybe I am making it too complex by looking at custom controls?

Please note: I have the code written to be able to export a grid view to an Excel file and it works fine. I need help on how to make that code more generic, so I can drop it in my ASP by a grid view and let the grid view be "exportable".

Thanks in advance for pointing me in the right direction!

What if we take a route where all of your buttons call the same export method that determines which gridview to use, and then sends the appropriate datasource to your Excel creator? Not sure if it would be considered dirty, but it should be pretty easy, no custom controls involved.

Example:

Let's say we name all of our buttons something like this, so we can extract out their parent gridview

<asp:LinkButton ID="PeopleGridView_exportbutton" runat="server" onclick="excel_click" />
<asp:LinkButton ID="ShipmentsGridView_exportbutton" runat="server" onclick="excel_click" />
<asp:LinkButton ID="ProductsGridView_exportbutton" runat="server" onclick="excel_click" />

Now, we'll make that method:

protected void uxPrenatalSubmit_Click(object sender, EventArgs e){
  string callerControlID = ((Control)sender).ID;
  string gridveiwID = callerControlID.Replace("_exportbutton", "");
  GridView gv = (GridView) findControl(gridveiwID);
  myCustomExcelCreatorMethod(gv.DataSource); //your method thingie here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM