473,888 Members | 1,636 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Inheriting from a GridView

I am attempting to better automate a Pager Template within a GridView. I am
succesfully skinning a Drop Down List withing my control (the DDL is added
to my control). I correctly populate the item list that corresponds with the
number of pages, but I am unable to wire up the Selected Index Changed
event. Auto PostBack is set to true and the page is posting back when the
DDL is selected / chaged, but the event is never being called.

Any ideas?

Secon question: how can I dynamically generate the pager template that
contains the DDL?

Thanks!

>>>>

public class DataGridView : GridView {

protected override void OnRowDataBound( GridViewRowEven tArgs e) {
if (e.Row.RowType == DataControlRowT ype.Pager) {
LoadPagerTempla te(e.Row);
}

base.OnRowDataB ound(e);
}

private void LoadPagerTempla te(GridViewRow row) {
DropDownList dropDownListPag er =
(DropDownList)r ow.FindControl( "DropDownListPa ger");

if (dropDownListPa ger != null) {
for (int i = 1; i <= this.PageCount; i++) {
dropDownListPag er.Items.Add(ne w ListItem(i.ToSt ring(),
i.ToString()));
}

dropDownListPag er.SelectedInde xChanged += new
EventHandler(Dr opDownListPager _SelectedIndexC hanged);
}
}

public void DropDownListPag er_SelectedInde xChanged(object sender,
EventArgs e) {
this.PageIndex = ((DropDownList) sender).Selecte dIndex; // <- this
is never reached when I change the DDL.
this.DataBind() ;
}
}

Feb 12 '07 #1
5 3015
I am guessing that the failure of the even is somehow related to where I am
wiring it up. On the post back, does the control need to be populated before
the event fires? What method on the grid view should I be overriding?

-Andy
"Andrew Robinson" <ne****@nospam. nospamwrote in message
news:eU******** ******@TK2MSFTN GP06.phx.gbl...
>I am attempting to better automate a Pager Template within a GridView. I am
succesfully skinning a Drop Down List withing my control (the DDL is added
to my control). I correctly populate the item list that corresponds with
the number of pages, but I am unable to wire up the Selected Index Changed
event. Auto PostBack is set to true and the page is posting back when the
DDL is selected / chaged, but the event is never being called.

Any ideas?

Secon question: how can I dynamically generate the pager template that
contains the DDL?

Thanks!

>>>>>


public class DataGridView : GridView {

protected override void OnRowDataBound( GridViewRowEven tArgs e) {
if (e.Row.RowType == DataControlRowT ype.Pager) {
LoadPagerTempla te(e.Row);
}

base.OnRowDataB ound(e);
}

private void LoadPagerTempla te(GridViewRow row) {
DropDownList dropDownListPag er =
(DropDownList)r ow.FindControl( "DropDownListPa ger");

if (dropDownListPa ger != null) {
for (int i = 1; i <= this.PageCount; i++) {
dropDownListPag er.Items.Add(ne w ListItem(i.ToSt ring(),
i.ToString()));
}

dropDownListPag er.SelectedInde xChanged += new
EventHandler(Dr opDownListPager _SelectedIndexC hanged);
}
}

public void DropDownListPag er_SelectedInde xChanged(object sender,
EventArgs e) {
this.PageIndex = ((DropDownList) sender).Selecte dIndex; // <-
this is never reached when I change the DDL.
this.DataBind() ;
}
}
Feb 12 '07 #2
Hello Andy,

From your description, you're creating a custom GridView class(derived from
built-in GridView class) and want to do some customization on the
GridView's paging. However, you're meeting a problem that the
dropdownlist's SelectedIndexCh ange event handler won't get executed,
correct?

Based on the code snippet you provide, it seems you still use the the
GridView's "PagerTempl ate" to define your custom pager layout, correct? If
so, I think you can get the custom dropdownlist work in the Pagertemplate
and has "selectedIndexc hanged" event handler registered without creating a
custom GridView class. e.g.

#Here is GridView which define a custom pager template and do the custom
paging without derived from built-in GridView class

==============a spx============ ======
<asp:GridView ID="GridView1" runat="server" AllowPaging="Tr ue"
AutoGenerateCol umns="False"
DataKeyNames="i d" DataSourceID="S qlDataSource1" PageSize="2"
OnRowDataBound= "GridView1_RowD ataBound" >
<Columns>
<asp:BoundFie ld DataField="id" HeaderText="id"
InsertVisible=" False" ReadOnly="True"
SortExpression= "id" />
<asp:BoundFie ld DataField="name " HeaderText="nam e"
SortExpression= "name" />
<asp:BoundFie ld DataField="desc ription"
HeaderText="des cription" SortExpression= "descriptio n" />
</Columns>
<PagerTemplat e>
<div style="text-align:right">
<asp:DropDownLi st ID="lstPages" runat="server"
AutoPostBack="t rue"
OnSelectedIndex Changed="lstPag es_SelectedInde xChanged"
OnPreRender="ls tPages_PreRende r">
</asp:DropDownLis t>
</div>
</PagerTemplate>
</asp:GridView>
==========code behind========= ===========
public partial class nav_MyGridPage : System.Web.UI.P age
{
protected void Page_Load(objec t sender, EventArgs e)
{

}
protected void GridView1_RowDa taBound(object sender,
GridViewRowEven tArgs e)
{
if (e.Row.RowType == DataControlRowT ype.Pager)
{
DropDownList lst = e.Row.FindContr ol("lstPages") as
DropDownList;

if (lst.Items.Coun t != GridView1.PageC ount)
{
lst.Items.Clear ();
for (int i = 1; i <= GridView1.PageC ount; i++)
{
lst.Items.Add(i .ToString());
}
}
}

}

protected void lstPages_Select edIndexChanged( object sender, EventArgs e)
{
DropDownList lst = (DropDownList)s ender;

int pageindex = int.Parse(lst.S electedValue);
Response.Write( "<br/>New PageIndex: " + pageindex);

GridView1.PageI ndex = lst.SelectedInd ex;
GridView1.DataB ind();
}

protected void lstPages_PreRen der(object sender, EventArgs e)
{
DropDownList lst = (DropDownList)s ender;

lst.SelectedInd ex = GridView1.PageI ndex;

}
}
=============== =============== =====
If you still want to create a custom GridView class, I think you should put
the code( which create custom sub controls in PagerTemplate and registering
event handler dynamically) in the OnRowCreated event. This is because for
dynamic created control or event handler, they need to be created and
registered in every page request, while the "OnRowDataBound " is not
guaranteed to occur on each page reqeust. In addition, you can consider
directly hook the "InitializePage r" function of the GridView class, this
is the function that do the eariliest GridView pager row's
initialization( for the Row's cells and sub controls or template ....). You
can even discard the base class's initialize codelogic and do it yourself.
e.g.

=============== ==========
namespace ClassLibrary1
{
[DefaultProperty ("Text")]
[ToolboxData("<{ 0}:MyGridView runat=server></{0}:MyGridView> ")]
public class MyGridView : GridView
{

protected override void InitializePager (GridViewRow row, int
columnSpan, PagedDataSource pagedDataSource )
{
base.Initialize Pager(row, columnSpan, pagedDataSource );

//do your customzation on the Pager Row here(or you can comment
the above base.Initialize Pager and completely do the pager row initalize
yourself

}

protected override void OnRowCreated(Gr idViewRowEventA rgs e)
{
base.OnRowCreat ed(e);

//here is just like what you have in GridView's "RowCreated "
event handler
}

}
}
=============== =============== =========

Hope this helps some.

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead

=============== =============== =============== =====

Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.

=============== =============== =============== =====

This posting is provided "AS IS" with no warranties, and confers no rights.

Feb 13 '07 #3
Steve,

Thanks for the help. I am using this gridview on potentially 100 to 200
pages so I want to include the paging functionality within an inherited
control. I will try the two events that you suggested rather than the row
binding event that I was using. Guessing this will fix things.

Thanks,

"Steven Cheng[MSFT]" <st*****@online .microsoft.comw rote in message
news:tC******** ******@TK2MSFTN GHUB02.phx.gbl. ..
Hello Andy,

From your description, you're creating a custom GridView class(derived
from
built-in GridView class) and want to do some customization on the
GridView's paging. However, you're meeting a problem that the
dropdownlist's SelectedIndexCh ange event handler won't get executed,
correct?

Based on the code snippet you provide, it seems you still use the the
GridView's "PagerTempl ate" to define your custom pager layout, correct? If
so, I think you can get the custom dropdownlist work in the Pagertemplate
and has "selectedIndexc hanged" event handler registered without creating a
custom GridView class. e.g.

#Here is GridView which define a custom pager template and do the custom
paging without derived from built-in GridView class

==============a spx============ ======
<asp:GridView ID="GridView1" runat="server" AllowPaging="Tr ue"
AutoGenerateCol umns="False"
DataKeyNames="i d" DataSourceID="S qlDataSource1" PageSize="2"
OnRowDataBound= "GridView1_RowD ataBound" >
<Columns>
<asp:BoundFie ld DataField="id" HeaderText="id"
InsertVisible=" False" ReadOnly="True"
SortExpression= "id" />
<asp:BoundFie ld DataField="name " HeaderText="nam e"
SortExpression= "name" />
<asp:BoundFie ld DataField="desc ription"
HeaderText="des cription" SortExpression= "descriptio n" />
</Columns>
<PagerTemplat e>
<div style="text-align:right">
<asp:DropDownLi st ID="lstPages" runat="server"
AutoPostBack="t rue"
OnSelectedIndex Changed="lstPag es_SelectedInde xChanged"
OnPreRender="ls tPages_PreRende r">
</asp:DropDownLis t>
</div>
</PagerTemplate>
</asp:GridView>
==========code behind========= ===========
public partial class nav_MyGridPage : System.Web.UI.P age
{
protected void Page_Load(objec t sender, EventArgs e)
{

}
protected void GridView1_RowDa taBound(object sender,
GridViewRowEven tArgs e)
{
if (e.Row.RowType == DataControlRowT ype.Pager)
{
DropDownList lst = e.Row.FindContr ol("lstPages") as
DropDownList;

if (lst.Items.Coun t != GridView1.PageC ount)
{
lst.Items.Clear ();
for (int i = 1; i <= GridView1.PageC ount; i++)
{
lst.Items.Add(i .ToString());
}
}
}

}

protected void lstPages_Select edIndexChanged( object sender, EventArgs
e)
{
DropDownList lst = (DropDownList)s ender;

int pageindex = int.Parse(lst.S electedValue);
Response.Write( "<br/>New PageIndex: " + pageindex);

GridView1.PageI ndex = lst.SelectedInd ex;
GridView1.DataB ind();
}

protected void lstPages_PreRen der(object sender, EventArgs e)
{
DropDownList lst = (DropDownList)s ender;

lst.SelectedInd ex = GridView1.PageI ndex;

}
}
=============== =============== =====
If you still want to create a custom GridView class, I think you should
put
the code( which create custom sub controls in PagerTemplate and
registering
event handler dynamically) in the OnRowCreated event. This is because for
dynamic created control or event handler, they need to be created and
registered in every page request, while the "OnRowDataBound " is not
guaranteed to occur on each page reqeust. In addition, you can consider
directly hook the "InitializePage r" function of the GridView class, this
is the function that do the eariliest GridView pager row's
initialization( for the Row's cells and sub controls or template ....). You
can even discard the base class's initialize codelogic and do it yourself.
e.g.

=============== ==========
namespace ClassLibrary1
{
[DefaultProperty ("Text")]
[ToolboxData("<{ 0}:MyGridView runat=server></{0}:MyGridView> ")]
public class MyGridView : GridView
{

protected override void InitializePager (GridViewRow row, int
columnSpan, PagedDataSource pagedDataSource )
{
base.Initialize Pager(row, columnSpan, pagedDataSource );

//do your customzation on the Pager Row here(or you can comment
the above base.Initialize Pager and completely do the pager row initalize
yourself

}

protected override void OnRowCreated(Gr idViewRowEventA rgs e)
{
base.OnRowCreat ed(e);

//here is just like what you have in GridView's "RowCreated "
event handler
}

}
}
=============== =============== =========

Hope this helps some.

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead

=============== =============== =============== =====

Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.

=============== =============== =============== =====

This posting is provided "AS IS" with no warranties, and confers no
rights.



Feb 13 '07 #4
Thanks for your reply Andrew,

RowDatabound event/method will still be useful since you may need to do
some update on your pager whenver databinding occurs. Anyway, you can try
those methods first, if you meet any further problem, please feel free to
post here. I'll be glad to be of assistance.

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead
This posting is provided "AS IS" with no warranties, and confers no rights.

Feb 14 '07 #5
Hello Andrew,

Have you got any further progress on this issue? If there is anything else
we can help, please feel free to followup

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead

This posting is provided "AS IS" with no warranties, and confers no rights.

Feb 16 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
5680
by: theKirk | last post by:
using Visual Studio 2005 C# ASP.NET I know there has to be a simple way to do this....I want to use C# in a code behind for aspx. Populate a GridView from an xml file Add Fields to the GridView to allow entry of quantity and Y/N switch for
6
3047
by: Nalaka | last post by:
Hi, I have a gridView (grid1), which as a templateColumn. In the template column, I have put in a gridView (grid2) and a ObjectDataSource (objectDataSource2). Question is... How to I pass the current_row_key of Grid1... to the objectDataSource2 parameter? (so that the second grid, gets only the information to do with current row of grid1)
2
1817
by: Charles Law | last post by:
I want a set of controls that all have a border, like a group box. I thought I would create a base control containing just a group box from which my set of controls could inherit. Assuming that this is the right approach (please tell me if it is not), how then do I make it so that the group box cannot be moved around on my set of controls, but is also able to act as container for other controls? If I leave the modifier of the group box...
5
4845
by: Dick | last post by:
I have a GridView bound to an ObjectDataSource. I have a Button that calls GridView.DataBind. I want the row that is selected before the DataBind to still be selected afterwards. This happens automatically if the data doesn't change. But if records have been added or deleted then it looks as if some code is necessary: I've done this by using GridView.SelectedValue to get the key value of the currently selected Row and then by itterating...
1
11724
by: WebMatrix | last post by:
Hi, I started a new web application which so far has several grdiviews displaying data. I find myself reimplementing the same logic (copy/pasting really) in grid's event ItemDataBound and RowCreated and Sorting events to add certain effects. For example inserting sorting direction image to the column header. I want to create one custom grid view that implement all this logic to be reused through out this app, so I wont need to copy...
2
13205
by: antonyliu2002 | last post by:
I've been googling for some time, and could not find the solution to this problem. I am testing the paging feature of gridview. I have a very simple web form on which the user can select a few fields to be included in the table, which is to be bound to the gridview. The web form looks like so (Don't worry about the stupidity of this web form for now.):
0
1004
by: =?Utf-8?B?UGhpbGlw?= | last post by:
I am referencing external controls defined in web.config system.web/pages/controls... illustrated as follows... <pages validateRequest="false" enableViewStateMac="true" enableEventValidation="false"> <controls> <add tagPrefix="slcms" namespace="SLCMS.CustomControls.GridView" assembly="SLCMS"/> <add tagPrefix="slcms" namespace="SLCMS.CustomControls.WaitScreen"
6
5774
by: RobertTheProgrammer | last post by:
Hi folks, Here's a weird problem... I have a nested GridView setup (i.e. a GridView within a GridView), and within the nested GridView I have a DropDownList item which has the OnSelectedIndexChanged event set on it. This triggers just fine, but within the codebehind of the OnSelectedIndexChanged event, I need to scan through all the entries in the nested GridView (to see if the user changed a value to an already existing value in the...
3
5251
by: Peter | last post by:
I have a GridView which is populated by List<ofObjects> Does anyone have example of how to sort the columns of this GridView? I have found examples without DataSourceControl but these use DataTable, I am using List of Objects. Here's one example: http://ryanolshan.com/technology/gridview-without-datasourcecontrol-datasource/
0
9961
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9800
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11178
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10777
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10438
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9597
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
7148
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
6014
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4642
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.