Here's a class that extends the standard GridView. The code is not entirely made by me. It's basicaly a lot snippets from other posts/articles/blogs polished and combined into a single class:
#region Using directives
using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
#endregion
namespace MyWebControls
{
public class GridViewEx : GridView
{
#region Properties
/// <summary>
/// When true and the GridView is inside a container with overflow this will make the header fixed.
/// Only the rest of the rows will scroll.
/// </summary>
/// <remarks>
/// Works only in IE.
/// </remarks>
[Category("Behaviour")]
[Themeable(true)]
[Bindable(false)]
[DefaultValue(false)]
public bool FreezeHeader
{
get
{
if (ViewState["FreezeHeader"] == null)
return false;
return (bool)ViewState["FreezeHeader"];
}
set
{
ViewState["FreezeHeader"] = value;
}
}
[Category("Behaviour")]
[Themeable(true)]
[Bindable(BindableSupport.No)]
[DefaultValue(false)]
public bool ShowWhenEmpty
{
get
{
if (ViewState["ShowWhenEmpty"] == null)
return false;
return (bool)ViewState["ShowWhenEmpty"];
}
set
{
ViewState["ShowWhenEmpty"] = value;
}
}
protected GridViewRow _footerRow2;
public override GridViewRow FooterRow
{
get
{
GridViewRow f = base.FooterRow;
if (f != null)
return f;
else
return _footerRow2;
}
}
protected GridViewRow _headerRow2;
public override GridViewRow HeaderRow
{
get
{
GridViewRow h = base.HeaderRow;
if (h != null)
return h;
else
return this._headerRow2;
}
}
[Bindable(BindableSupport.Yes, BindingDirection.OneWay)]
public override string Caption
{
get
{
return base.Caption;
}
set
{
base.Caption = value;
}
}
/// <summary>
/// Enable/Disable MultiColumn Sorting.
/// </summary>
[
Description("Whether Sorting On more than one column is enabled"),
Category("Behavior"),
DefaultValue("false"),
]
public bool AllowMultiColumnSorting
{
get
{
object o = ViewState["EnableMultiColumnSorting"];
return (o != null ? (bool)o : false);
}
set
{
AllowSorting = true;
ViewState["EnableMultiColumnSorting"] = value;
}
}
/// <summary>
/// Get or Set Image location to be used to display Ascending Sort order.
/// </summary>
[
Description("Image to display for Ascending Sort"),
Category("Misc"),
Editor("System.Web.UI.Design.UrlEditor", typeof(System.Drawing.Design.UITypeEditor)),
DefaultValue(""),
]
public string SortAscImageUrl
{
get
{
object o = ViewState["SortImageAsc"];
return (o != null ? o.ToString() : "");
}
set
{
ViewState["SortImageAsc"] = value;
}
}
/// <summary>
/// Get or Set Image location to be used to display Ascending Sort order.
/// </summary>
[
Description("Image to display for Descending Sort"),
Category("Misc"),
Editor("System.Web.UI.Design.UrlEditor", typeof(System.Drawing.Design.UITypeEditor)),
DefaultValue(""),
]
public string SortDescImageUrl
{
get
{
object o = ViewState["SortImageDesc"];
return (o != null ? o.ToString() : "");
}
set
{
ViewState["SortImageDesc"] = value;
}
}
public DataControlRowState? RowState
{
get
{
return (DataControlRowState?)ViewState["RowState"];
}
set
{
ViewState["RowState"] = value;
}
}
#endregion
#region Life Cycle
protected override void OnSorting(GridViewSortEventArgs e)
{
if (AllowMultiColumnSorting)
e.SortExpression = GetSortExpression(e);
base.OnSorting(e);
}
protected override void OnRowCreated(GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
if (SortExpression != String.Empty)
DisplaySortOrderImages(SortExpression, e.Row);
}
base.OnRowCreated(e);
}
protected override GridViewRow CreateRow(int rowIndex, int dataSourceIndex, DataControlRowType rowType, DataControlRowState rowState)
{
if (RowState.HasValue)
return base.CreateRow(rowIndex, dataSourceIndex, rowType, RowState.Value);
else
return base.CreateRow(rowIndex, dataSourceIndex, rowType, rowState);
}
#endregion
#region Protected Methods
/// <summary>
/// Get Sort Expression by Looking up the existing Grid View Sort Expression
/// </summary>
protected string GetSortExpression(GridViewSortEventArgs e)
{
string[] sortColumns = null;
string sortAttribute = SortExpression;
//Check to See if we have an existing Sort Order already in the Grid View.
//If so get the Sort Columns into an array
if (sortAttribute != String.Empty)
{
sortColumns = sortAttribute.Split(",".ToCharArray());
}
//if User clicked on the columns in the existing sort sequence.
//Toggle the sort order or remove the column from sort appropriately
if (sortAttribute.IndexOf(e.SortExpression) > 0 || sortAttribute.StartsWith(e.SortExpression))
sortAttribute = ModifySortExpression(sortColumns, e.SortExpression);
else
sortAttribute += String.Concat(",", e.SortExpression, " ASC ");
return sortAttribute.TrimStart(",".ToCharArray()).TrimEnd(",".ToCharArray());
}
public void SaveAll()
{
for (int i = 0; i < this.Rows.Count; i++)
{
this.UpdateRow(i, false);
}
}
/// <summary>
/// Toggle the sort order or remove the column from sort appropriately
/// </summary>
protected string ModifySortExpression(string[] sortColumns, string sortExpression)
{
string ascSortExpression = String.Concat(sortExpression, " ASC ");
string descSortExpression = String.Concat(sortExpression, " DESC ");
for (int i = 0; i < sortColumns.Length; i++)
{
if (ascSortExpression.Equals(sortColumns[i]))
{
sortColumns[i] = descSortExpression;
}
else if (descSortExpression.Equals(sortColumns[i]))
{
Array.Clear(sortColumns, i, 1);
}
}
return String.Join(",", sortColumns).Replace(",,", ",").TrimStart(",".ToCharArray());
}
/// <summary>
/// Lookup the Current Sort Expression to determine the Order of a specific item.
/// </summary>
protected void SearchSortExpression(string[] sortColumns, string sortColumn, out string sortOrder, out int sortOrderNo)
{
sortOrder = "";
sortOrderNo = -1;
for (int i = 0; i < sortColumns.Length; i++)
{
if (sortColumns[i].StartsWith(sortColumn))
{
sortOrderNo = i + 1;
if (AllowMultiColumnSorting)
sortOrder = sortColumns[i].Substring(sortColumn.Length).Trim();
else
sortOrder = ((SortDirection == SortDirection.Ascending) ? "ASC" : "DESC");
}
}
}
/// <summary>
/// Display a graphic image for the Sort Order along with the sort sequence no.
/// </summary>
protected void DisplaySortOrderImages(string sortExpression, GridViewRow dgItem)
{
string[] sortColumns = sortExpression.Split(",".ToCharArray());
for (int i = 0; i < dgItem.Cells.Count; i++)
{
if (dgItem.Cells[i].Controls.Count > 0 && dgItem.Cells[i].Controls[0] is LinkButton)
{
string sortOrder;
int sortOrderNo;
string column = ((LinkButton)dgItem.Cells[i].Controls[0]).CommandArgument;
SearchSortExpression(sortColumns, column, out sortOrder, out sortOrderNo);
if (sortOrderNo > 0)
{
string sortImgLoc = (sortOrder.Equals("ASC") ? SortAscImageUrl : SortDescImageUrl);
if (sortImgLoc != String.Empty)
{
Image imgSortDirection = new Image();
imgSortDirection.ImageUrl = sortImgLoc;
dgItem.Cells[i].Controls.Add(imgSortDirection);
//Label lblSortOrder = new Label();
//lblSortOrder.Font.Size = FontUnit.Small;
//lblSortOrder.Text = sortOrderNo.ToString();
//dgItem.Cells[i].Controls.Add(lblSortOrder);
}
else
{
//Label lblSortDirection = new Label();
//lblSortDirection.Font.Size = FontUnit.XSmall;
//lblSortDirection.Font.Name = "webdings";
//lblSortDirection.EnableTheming = false;
//lblSortDirection.Text = (sortOrder.Equals("ASC") ? "5" : "6");
//dgItem.Cells[i].Controls.Add(lblSortDirection);
if (AllowMultiColumnSorting)
{
Literal litSortSeq = new Literal();
litSortSeq.Text = sortOrderNo.ToString();
dgItem.Cells[i].Controls.Add(litSortSeq);
}
}
}
}
}
}
protected override int CreateChildControls(System.Collections.IEnumerable dataSource, bool dataBinding)
{
int numRows = base.CreateChildControls(dataSource, dataBinding);
//no data rows created, create empty table if enabled
if (numRows == 0 && ShowWhenEmpty)
{
//create table
Table table = new Table();
table.ID = this.ID;
//convert the exisiting columns into an array and initialize
DataControlField[] fields = new DataControlField[this.Columns.Count];
this.Columns.CopyTo(fields, 0);
if (this.ShowHeader)
{
//create a new header row
_headerRow2 = base.CreateRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
this.InitializeRow(_headerRow2, fields);
table.Rows.Add(_headerRow2);
}
//create the empty row
GridViewRow emptyRow = new GridViewRow(-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
TableCell cell = new TableCell();
cell.ColumnSpan = this.Columns.Count;
cell.Width = Unit.Percentage(100);
if (!String.IsNullOrEmpty(EmptyDataText))
cell.Controls.Add(new LiteralControl(EmptyDataText));
if (this.EmptyDataTemplate != null)
EmptyDataTemplate.InstantiateIn(cell);
emptyRow.Cells.Add(cell);
table.Rows.Add(emptyRow);
if (this.ShowFooter)
{
//create footer row
_footerRow2 = base.CreateRow(-1, -1, DataControlRowType.Footer, DataControlRowState.Normal);
this.InitializeRow(_footerRow2, fields);
table.Rows.Add(_footerRow2);
}
this.Controls.Clear();
this.Controls.Add(table);
}
//does not work on Gecko
if (this.FreezeHeader && this.HeaderRow != null)
{
this.HeaderRow.Style["top"] = "expression(this.offsetParent.scrollTop)";
this.HeaderRow.Style["position"] = "relative";
this.HeaderRow.Style["zindex"] = "2";
}
return numRows;
}
#endregion
}
}
Entra features added are:
Posibility to freeze the header (when the grid is placed in a container with overflow:scroll or auto)
Show the header/footer rows even when the datasource is empty.
Show images in the header that indicate the sort column and sort direction.
Caption property is bindable
Buld Editing (set RowState to Edit then call SaveAll())
Sort by multiple columns (not properly implemented yet as I didn't need it)
Please post any suggestions and/or bugs that you can find here. Also, anyone who has made something that's not included here and is willing to share is more than welcomed to to so :D
This is a great class indeed, thanks for supplying it!
However, if I try fetching text from a code-behind function inside the EmptyDataTemplate it doesn't show the text. When debugging it enters the function and returns the text, but it doesn't get displayed. When using the asp:GridView the text shows up nicely
(but of course without the header and footer).
I think you would be more comfortable with a solution like
1 //create the empty row
2 GridViewRow emptyRow = new GridViewRow(-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
3 //add row to table
4 tbl.Rows.Add(emptyRow);
5 //initialize row
6 InitializeRow(emptyRow, fields);
This way you could use the standard methods of the GridView without having to rewrite everything.
Additionaly I came up with one problem concerning the line
1 Table table = new Table();
2 table.ID = this.ID;
I wouldn't do that, because this changes the IDs of the controls within the grid. The method of the GridView (CreateChildControls) creates the table as "ctl00" and changing the ID could cause problems on postbacks.
kind regards,
Chris
Never underestimate the power of stupid people in large groups
I've used part of this customcontrol in the past to make a footerrow with insert functionality display/work when the gridview is empty. This has always worked great. Buttons and textboxes in the footer cuold always be used normaly when an empty gridview
was encountered.
Now I've got some search functionalty embedded in the header and I'm using this customcontrol to show the gridview when it is empty.
This time it's not working though.
When an empty gridview is returned after a search has been done, the searchbutton and textboxes are shown. The sort-links returned by the GetHeader are not however. It seems the header never gets initialized properly when a search doesn't have any results.
When a new search is performed after an empty search, a postback occurs, but the RowCommand is never called.
I've found that the properties HeaderText and SortExpression of the templatefield are not used when the templatefield contains a HeaderTemplate. Therefor the build-in functionality of sorting could not be used. The GetHeader function is for creating the
sort-link in the header.
Because the search-textboxes are within the gridview, they do not automatically persist their value during postbacks. I've come up with a way to dynamically build and fill the filter parameters and expression and use this to persist (re-fill) the search
fields.
I'm using caching and filterparameters to fill and search the data in the gridview.
My Code:
protected override int CreateChildControls:
Same as above (minus FreezeHeader, I'm using only the ShowWhenEmpty functionality)
SelectMethod (because of caching only called when necessary): public DataSet gvOrderList_Select(string sort) { string sql = "SELECT O.*, OS.Status AS StatusNaam, K.Achternaam FROM (ORDER O LEFT JOIN OrderStatus OS ON O.Status = OS.Id) LEFT JOIN Klant K ON O.KlantId = K.Id";
if (!string.IsNullOrEmpty(sort)) { if (sort.Contains("IngangsDatum")) sort = sort.Replace("IngangsDatum", "O.IngangsDatum"); if (sort.Contains("Status")) sort = sort.Replace("Status", "O.Status"); sql += " ORDER BY " + sort + ";"; } else sql += " ORDER BY O.IngangsDatum DESC;";
Hmm. No matter what I tried, I could not get the code to work.
Here's what I did:
Started a new web project, created a folder called MyWebControls, and added a Web User Control to that. In the code-behind, I pasted the code code, and corrected where appropriate (The EXPRESSION BLOCKED).
Got this:
Error 1 Make sure that the class defined in this code file matches the 'inherits' attribute, and that it extends the correct base class (e.g. Page or UserControl). C:\Documents
and Settings\..WebSite4\MyWebControls\GridViewExample.ascx.cs 1 33 C:\...\WebSite4\
I tried messing around in the ASPX file, by adding the MyWebControls namespace to the inherits bit:
Missing partial modifier on declaration of type 'GridViewExample'; another partial declaration of this type exists
Could anyone try to either give me a more detailed description of steps to take, or just specifying where I went wrong? It's been some time since I messed with
ASP.NET, and I probably am overlooking something real easy. However, I have spent quite a bit of time on this already, and am hoping someone can give me a proper kick in the right direction.
CISCBrain
Member
97 Points
22 Posts
GridViewEx
Jul 28, 2006 01:06 PM|LINK
Here's a class that extends the standard GridView. The code is not entirely made by me. It's basicaly a lot snippets from other posts/articles/blogs polished and combined into a single class:
#region Using directives using System; using System.ComponentModel; using System.Web.UI; using System.Web.UI.WebControls; #endregion namespace MyWebControls { public class GridViewEx : GridView { #region Properties /// <summary> /// When true and the GridView is inside a container with overflow this will make the header fixed. /// Only the rest of the rows will scroll. /// </summary> /// <remarks> /// Works only in IE. /// </remarks> [Category("Behaviour")] [Themeable(true)] [Bindable(false)] [DefaultValue(false)] public bool FreezeHeader { get { if (ViewState["FreezeHeader"] == null) return false; return (bool)ViewState["FreezeHeader"]; } set { ViewState["FreezeHeader"] = value; } } [Category("Behaviour")] [Themeable(true)] [Bindable(BindableSupport.No)] [DefaultValue(false)] public bool ShowWhenEmpty { get { if (ViewState["ShowWhenEmpty"] == null) return false; return (bool)ViewState["ShowWhenEmpty"]; } set { ViewState["ShowWhenEmpty"] = value; } } protected GridViewRow _footerRow2; public override GridViewRow FooterRow { get { GridViewRow f = base.FooterRow; if (f != null) return f; else return _footerRow2; } } protected GridViewRow _headerRow2; public override GridViewRow HeaderRow { get { GridViewRow h = base.HeaderRow; if (h != null) return h; else return this._headerRow2; } } [Bindable(BindableSupport.Yes, BindingDirection.OneWay)] public override string Caption { get { return base.Caption; } set { base.Caption = value; } } /// <summary> /// Enable/Disable MultiColumn Sorting. /// </summary> [ Description("Whether Sorting On more than one column is enabled"), Category("Behavior"), DefaultValue("false"), ] public bool AllowMultiColumnSorting { get { object o = ViewState["EnableMultiColumnSorting"]; return (o != null ? (bool)o : false); } set { AllowSorting = true; ViewState["EnableMultiColumnSorting"] = value; } } /// <summary> /// Get or Set Image location to be used to display Ascending Sort order. /// </summary> [ Description("Image to display for Ascending Sort"), Category("Misc"), Editor("System.Web.UI.Design.UrlEditor", typeof(System.Drawing.Design.UITypeEditor)), DefaultValue(""), ] public string SortAscImageUrl { get { object o = ViewState["SortImageAsc"]; return (o != null ? o.ToString() : ""); } set { ViewState["SortImageAsc"] = value; } } /// <summary> /// Get or Set Image location to be used to display Ascending Sort order. /// </summary> [ Description("Image to display for Descending Sort"), Category("Misc"), Editor("System.Web.UI.Design.UrlEditor", typeof(System.Drawing.Design.UITypeEditor)), DefaultValue(""), ] public string SortDescImageUrl { get { object o = ViewState["SortImageDesc"]; return (o != null ? o.ToString() : ""); } set { ViewState["SortImageDesc"] = value; } } public DataControlRowState? RowState { get { return (DataControlRowState?)ViewState["RowState"]; } set { ViewState["RowState"] = value; } } #endregion #region Life Cycle protected override void OnSorting(GridViewSortEventArgs e) { if (AllowMultiColumnSorting) e.SortExpression = GetSortExpression(e); base.OnSorting(e); } protected override void OnRowCreated(GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.Header) { if (SortExpression != String.Empty) DisplaySortOrderImages(SortExpression, e.Row); } base.OnRowCreated(e); } protected override GridViewRow CreateRow(int rowIndex, int dataSourceIndex, DataControlRowType rowType, DataControlRowState rowState) { if (RowState.HasValue) return base.CreateRow(rowIndex, dataSourceIndex, rowType, RowState.Value); else return base.CreateRow(rowIndex, dataSourceIndex, rowType, rowState); } #endregion #region Protected Methods /// <summary> /// Get Sort Expression by Looking up the existing Grid View Sort Expression /// </summary> protected string GetSortExpression(GridViewSortEventArgs e) { string[] sortColumns = null; string sortAttribute = SortExpression; //Check to See if we have an existing Sort Order already in the Grid View. //If so get the Sort Columns into an array if (sortAttribute != String.Empty) { sortColumns = sortAttribute.Split(",".ToCharArray()); } //if User clicked on the columns in the existing sort sequence. //Toggle the sort order or remove the column from sort appropriately if (sortAttribute.IndexOf(e.SortExpression) > 0 || sortAttribute.StartsWith(e.SortExpression)) sortAttribute = ModifySortExpression(sortColumns, e.SortExpression); else sortAttribute += String.Concat(",", e.SortExpression, " ASC "); return sortAttribute.TrimStart(",".ToCharArray()).TrimEnd(",".ToCharArray()); } public void SaveAll() { for (int i = 0; i < this.Rows.Count; i++) { this.UpdateRow(i, false); } } /// <summary> /// Toggle the sort order or remove the column from sort appropriately /// </summary> protected string ModifySortExpression(string[] sortColumns, string sortExpression) { string ascSortExpression = String.Concat(sortExpression, " ASC "); string descSortExpression = String.Concat(sortExpression, " DESC "); for (int i = 0; i < sortColumns.Length; i++) { if (ascSortExpression.Equals(sortColumns[i])) { sortColumns[i] = descSortExpression; } else if (descSortExpression.Equals(sortColumns[i])) { Array.Clear(sortColumns, i, 1); } } return String.Join(",", sortColumns).Replace(",,", ",").TrimStart(",".ToCharArray()); } /// <summary> /// Lookup the Current Sort Expression to determine the Order of a specific item. /// </summary> protected void SearchSortExpression(string[] sortColumns, string sortColumn, out string sortOrder, out int sortOrderNo) { sortOrder = ""; sortOrderNo = -1; for (int i = 0; i < sortColumns.Length; i++) { if (sortColumns[i].StartsWith(sortColumn)) { sortOrderNo = i + 1; if (AllowMultiColumnSorting) sortOrder = sortColumns[i].Substring(sortColumn.Length).Trim(); else sortOrder = ((SortDirection == SortDirection.Ascending) ? "ASC" : "DESC"); } } } /// <summary> /// Display a graphic image for the Sort Order along with the sort sequence no. /// </summary> protected void DisplaySortOrderImages(string sortExpression, GridViewRow dgItem) { string[] sortColumns = sortExpression.Split(",".ToCharArray()); for (int i = 0; i < dgItem.Cells.Count; i++) { if (dgItem.Cells[i].Controls.Count > 0 && dgItem.Cells[i].Controls[0] is LinkButton) { string sortOrder; int sortOrderNo; string column = ((LinkButton)dgItem.Cells[i].Controls[0]).CommandArgument; SearchSortExpression(sortColumns, column, out sortOrder, out sortOrderNo); if (sortOrderNo > 0) { string sortImgLoc = (sortOrder.Equals("ASC") ? SortAscImageUrl : SortDescImageUrl); if (sortImgLoc != String.Empty) { Image imgSortDirection = new Image(); imgSortDirection.ImageUrl = sortImgLoc; dgItem.Cells[i].Controls.Add(imgSortDirection); //Label lblSortOrder = new Label(); //lblSortOrder.Font.Size = FontUnit.Small; //lblSortOrder.Text = sortOrderNo.ToString(); //dgItem.Cells[i].Controls.Add(lblSortOrder); } else { //Label lblSortDirection = new Label(); //lblSortDirection.Font.Size = FontUnit.XSmall; //lblSortDirection.Font.Name = "webdings"; //lblSortDirection.EnableTheming = false; //lblSortDirection.Text = (sortOrder.Equals("ASC") ? "5" : "6"); //dgItem.Cells[i].Controls.Add(lblSortDirection); if (AllowMultiColumnSorting) { Literal litSortSeq = new Literal(); litSortSeq.Text = sortOrderNo.ToString(); dgItem.Cells[i].Controls.Add(litSortSeq); } } } } } } protected override int CreateChildControls(System.Collections.IEnumerable dataSource, bool dataBinding) { int numRows = base.CreateChildControls(dataSource, dataBinding); //no data rows created, create empty table if enabled if (numRows == 0 && ShowWhenEmpty) { //create table Table table = new Table(); table.ID = this.ID; //convert the exisiting columns into an array and initialize DataControlField[] fields = new DataControlField[this.Columns.Count]; this.Columns.CopyTo(fields, 0); if (this.ShowHeader) { //create a new header row _headerRow2 = base.CreateRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal); this.InitializeRow(_headerRow2, fields); table.Rows.Add(_headerRow2); } //create the empty row GridViewRow emptyRow = new GridViewRow(-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal); TableCell cell = new TableCell(); cell.ColumnSpan = this.Columns.Count; cell.Width = Unit.Percentage(100); if (!String.IsNullOrEmpty(EmptyDataText)) cell.Controls.Add(new LiteralControl(EmptyDataText)); if (this.EmptyDataTemplate != null) EmptyDataTemplate.InstantiateIn(cell); emptyRow.Cells.Add(cell); table.Rows.Add(emptyRow); if (this.ShowFooter) { //create footer row _footerRow2 = base.CreateRow(-1, -1, DataControlRowType.Footer, DataControlRowState.Normal); this.InitializeRow(_footerRow2, fields); table.Rows.Add(_footerRow2); } this.Controls.Clear(); this.Controls.Add(table); } //does not work on Gecko if (this.FreezeHeader && this.HeaderRow != null) { this.HeaderRow.Style["top"] = "expression(this.offsetParent.scrollTop)"; this.HeaderRow.Style["position"] = "relative"; this.HeaderRow.Style["zindex"] = "2"; } return numRows; } #endregion } }hansgh
Member
20 Points
4 Posts
Re: GridViewEx
Aug 15, 2006 07:21 PM|LINK
This is a great class indeed, thanks for supplying it!
However, if I try fetching text from a code-behind function inside the EmptyDataTemplate it doesn't show the text. When debugging it enters the function and returns the text, but it doesn't get displayed. When using the asp:GridView the text shows up nicely (but of course without the header and footer).
Example:
<EmptyDataTemplate>
<asp:Label id="lblNoData" runat="server" Text='<%# GetNoMessagesText() %>' SkinID="Info"></asp:Label> </EmptyDataTemplate>Do you have any idea why this is and if it can be fixed?
CISCBrain
Member
97 Points
22 Posts
Re: GridViewEx
Aug 17, 2006 12:29 PM|LINK
<div> GridViewRow emptyRow;
emptyRow = new GridViewRow(-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
TableCell cell = new TableCell();
cell.ColumnSpan = this.Columns.Count;
cell.Width = Unit.Percentage(100);
if (!String.IsNullOrEmpty(EmptyDataText))
cell.Controls.Add(new LiteralControl(EmptyDataText));
if (this.EmptyDataTemplate != null)
EmptyDataTemplate.InstantiateIn(cell);
emptyRow.Cells.Add(cell); </div>
Just use the already initialized row:
<div class='code'> emptyRow = this.Controls[0].Controls[0] as GridViewRow; </div>
The row is already initialized because of the call to base.CreateChildControls().
hansgh
Member
20 Points
4 Posts
Re: GridViewEx
Aug 18, 2006 01:53 PM|LINK
Thanks, that did the trick.
I ended up rewriting it a bit so it now looks like this:
//create the empty row GridViewRow emptyRow; if (this.EmptyDataTemplate != null) emptyRow = this.Controls[0].Controls[0] as GridViewRow; else { emptyRow = new GridViewRow(-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal); TableCell cell = new TableCell(); cell.ColumnSpan = this.Columns.Count; cell.Width = Unit.Percentage(100); if (!String.IsNullOrEmpty(EmptyDataText)) cell.Controls.Add(new LiteralControl(EmptyDataText)); emptyRow.Cells.Add(cell); } table.Rows.Add(emptyRow);lc_
Member
17 Points
10 Posts
Re: GridViewEx
Oct 19, 2006 12:29 PM|LINK
Hi there,
I think you would be more comfortable with a solution like
I wouldn't do that, because this changes the IDs of the controls within the grid. The method of the GridView (CreateChildControls) creates the table as "ctl00" and changing the ID could cause problems on postbacks.
kind regards,
Chris
deur_h
Member
5 Points
1 Post
Re: GridViewEx
Nov 20, 2006 04:10 PM|LINK
Hi,
I've used part of this customcontrol in the past to make a footerrow with insert functionality display/work when the gridview is empty. This has always worked great. Buttons and textboxes in the footer cuold always be used normaly when an empty gridview was encountered.
Now I've got some search functionalty embedded in the header and I'm using this customcontrol to show the gridview when it is empty.
This time it's not working though.
When an empty gridview is returned after a search has been done, the searchbutton and textboxes are shown. The sort-links returned by the GetHeader are not however. It seems the header never gets initialized properly when a search doesn't have any results. When a new search is performed after an empty search, a postback occurs, but the RowCommand is never called.
I've found that the properties HeaderText and SortExpression of the templatefield are not used when the templatefield contains a HeaderTemplate. Therefor the build-in functionality of sorting could not be used. The GetHeader function is for creating the sort-link in the header.
Because the search-textboxes are within the gridview, they do not automatically persist their value during postbacks. I've come up with a way to dynamically build and fill the filter parameters and expression and use this to persist (re-fill) the search fields.
I'm using caching and filterparameters to fill and search the data in the gridview.
My Code:
hercules
Member
2 Points
1 Post
Re: GridViewEx
Feb 02, 2007 08:38 PM|LINK
e.SortBLOCKED EXPRESSION is undefined, it does not seem to come with the GridViewEventArgs,
let me know what the space stands for in the middle or if a function or property is missing.
GridViewEx
ViagraFalls
Member
248 Points
56 Posts
Re: GridViewEx
Aug 07, 2007 09:23 AM|LINK
The line should be:
ViagraFalls
Member
248 Points
56 Posts
Re: GridViewEx
Aug 07, 2007 08:49 PM|LINK
Hmm. No matter what I tried, I could not get the code to work.
Here's what I did:
Started a new web project, created a folder called MyWebControls, and added a Web User Control to that. In the code-behind, I pasted the code code, and corrected where appropriate (The EXPRESSION BLOCKED).
Got this:
Error 1 Make sure that the class defined in this code file matches the 'inherits' attribute, and that it extends the correct base class (e.g. Page or UserControl). C:\Documents and Settings\..WebSite4\MyWebControls\GridViewExample.ascx.cs 1 33 C:\...\WebSite4\
I tried messing around in the ASPX file, by adding the MyWebControls namespace to the inherits bit:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="GridViewExample.ascx.cs" Inherits="MyWebControls_GridViewEx" %>
At times I got this error:
Missing partial modifier on declaration of type 'GridViewExample'; another partial declaration of this type exists
Could anyone try to either give me a more detailed description of steps to take, or just specifying where I went wrong? It's been some time since I messed with ASP.NET, and I probably am overlooking something real easy. However, I have spent quite a bit of time on this already, and am hoping someone can give me a proper kick in the right direction.
Thanks!
Peter
ViagraFalls
Member
248 Points
56 Posts
Re: GridViewEx
Aug 07, 2007 09:03 PM|LINK
Doh. I think I just figured it out. Instead of creating it as a Web User Control, it helps if I create it as a Web Control Library.