简体   繁体   English

如何在asp.net中为gridview创建自定义Web服务器控件

[英]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. 我希望能够在某些网格视图上添加“导出到Excel”按钮,因此我开始查找并找到自定义Web服务器控件-请参见此页面以获取示例。

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. 我正在考虑创建一个自定义的Button控件,在该控件中可以将网格视图的ID作为参数传递-我什至不知道如何做到这一点,即使有可能。

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. 请注意:我已编写了能够将网格视图导出到Excel文件的代码,并且工作正常。 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". 我需要有关如何使该代码更通用的帮助,因此可以通过网格视图将其放置在ASP中,并使网格视图可“导出”。

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? 如果我们采用一条路线,其中所有按钮都调用相同的导出方法来确定要使用的网格视图,然后将适当的数据源发送给您的Excel创建者,该怎么办? 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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