473,574 Members | 3,123 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Custom DataGridColumn DataGridItems not saving to ViewState. Not Visible on Postback

I created a custom DataGridColumn based on Marcie Robillard's MSDN
Article:

Creating Custom Columns for the ASP.NET Datagrid
http://msdn.microsoft.com/library/de...tomcolumns.asp

The problem I am having is that the data in the custom datagridcolumn
is not saved to viewstate and after postback, the column does not
contain data.

Any idea's?

I simplified the code so that the error is easy to reproduce.
Here is the code: (notice that the CustomImage that is standalone on
the page and the CustomImage that is embedded in a template column are
visible after postback.)

I can send a zip file of the project on request.

-=-=-=-=- CustomColumn.cs (begin) -=-=-=-=-
using System;
using System.Data;
using System.Web.UI.W ebControls;
using System.Web.UI;

namespace PostbackError
{
public class CustomColumn : System.Web.UI.W ebControls.Data GridColumn
{
public override void
InitializeCell( System.Web.UI.W ebControls.Tabl eCell cell, int
columnIndex, System.Web.UI.W ebControls.List ItemType itemType)
{
//if the grid is using sorting, the the header will contain a
DataGridLinkBut ton
//the functionality is set by the base class initializecell.
base.Initialize Cell (cell, columnIndex, itemType);
switch (itemType)
{
case ListItemType.It em:
case ListItemType.Al ternatingItem:
cell.DataBindin g += new EventHandler(On DataBinding);
break;
}}

private void OnDataBinding(o bject sender, EventArgs e)
{
TableCell cell = sender as TableCell;
DataGridItem dgi = cell.NamingCont ainer as DataGridItem;
DataRowView drv = dgi.DataItem as DataRowView;
//hardcoded for this example
string image = "arrow.gif" ;
if (image.Length == 0)
return;

CustomImage ri = new CustomImage();
cell.Controls.A dd(ri);
TrackViewState( );
string tooltip = "Help";
ri.ImageUrl = image;
ri.ToolTip = tooltip;
}}}
-=-=-=-=- CustomColumn.cs (end) -=-=-=-=-
-=-=-=-=- CustomImage.cs (begin) -=-=-=-=-
using System;
using System.Componen tModel;
using System.IO;
using System.Text;
using System.Text.Reg ularExpressions ;
using System.Web.UI;
using System.Web.UI.D esign;

namespace PostbackError
{
public class CustomImage : System.Web.UI.W ebControls.Imag e
{
private string _imagePath = string.Empty;

public CustomImage():b ase()
{
_imagePath = string.Empty;
}

[
Browsable(true) ,
Category("Appea rance"),
Description("Im age to be displayed when the mouse is not over the
image")
]
public new string ImageUrl
{
get { return (string)ViewSta te["riImageUrl "]; }
set { ViewState["riImageUrl "] = value; }
}

[
Browsable(true) ,
Category("Appea rance"),
Description("Im age to be displayed when the mouse is over the
image")
]
public string MouseOverImageU rl
{
get { return (string)ViewSta te["MouseOverImage Url"]; }
set { ViewState["MouseOverImage Url"] = value; }
}

[
Browsable(true) ,
Category("Navig ation"),
Description("Th e url to navigate to")
]
public string NavigateUrl
{
get { return (string)ViewSta te["NavigateUr l"]; }
set { ViewState["NavigateUr l"] = value; }
}

[
Browsable(true) ,
Category("Appea rance"),
DefaultValue(tr ue),
Description("Us e a MouseOver Image derived from the Image name.
(i.e. image.gif -> image_ovr.gif)" )
]
public bool UseMouseOverIma ge
{
get
{
string property = "UseMouseOverIm age";
if (ViewState[property] == null)
{
object obj = _GetDefaultValu e(property);
if (obj != null)
ViewState[property] = (bool)obj;
}
return (bool)ViewState[property];
}
set { ViewState["UseMouseOverIm age"] = value; }
}
override protected void OnPreRender(Eve ntArgs e)
{
base.OnPreRende r(e);
string s = base.ImageUrl;
base.ImageUrl = _imagePath + ImageUrl;
s = base.ImageUrl;
string mouseOver = _GetImageMouseO ver();
if (mouseOver != null && UseMouseOverIma ge)
{
Attributes.Add( "onmouseove r", "this.src=' " + _imagePath +
mouseOver + "'");
Attributes.Add( "onmouseout ", "this.src=' " + _imagePath + ImageUrl
+ "'");
}
}

/// <summary>
/// Render this control to the output parameter specified.
/// </summary>
/// <param name="output"> The HTML writer to write out to </param>
protected override void Render(HtmlText Writer output)
{
bool bWriteAnchor = NavigateUrl != null && NavigateUrl.Len gth > 0;
string s1 = base.ImageUrl;
base.ImageUrl = _imagePath + ImageUrl;

StringWriter sw = new StringWriter();
HtmlTextWriter buffer = new HtmlTextWriter( sw);

if (bWriteAnchor)
{
buffer.AddAttri bute(HtmlTextWr iterAttribute.H ref, NavigateUrl);
buffer.RenderBe ginTag(HtmlText WriterTag.A);
}

base.Render(buf fer);

if (bWriteAnchor)
buffer.RenderEn dTag();

string s = sw.ToString();
output.Write(s) ;
}

private object _GetDefaultValu e(string propertyName)
{
System.Componen tModel.Attribut eCollection attributes =
TypeDescriptor. GetProperties(t his)[propertyName].Attributes;
DefaultValueAtt ribute myAttribute =
(DefaultValueAt tribute)attribu tes[typeof(DefaultV alueAttribute)];
if (myAttribute != null)
return myAttribute.Val ue;
else
return null;
}

private string _GetImageMouseO ver()
{
if (MouseOverImage Url != null) return MouseOverImageU rl;

StringBuilder sb = new StringBuilder() ;
Regex re = new Regex(@"\.");
//Image should be like "media.gif" over image should be
"media_ovr. gif"
//and have a part left and right of the period
//if the entry is not in this format, then the entry is invalid
//so return null
if (ImageUrl == null) return null;

string[] sa = re.Split(ImageU rl);
if (sa.Length != 2) return null;
return sa[0] + "_ovr." + sa[1];
}
}

public class CustomImageDesi gner:ControlDes igner
{
public override string GetDesignTimeHt ml( )
{
return "<h6>" + this.ID + "</h6>";
}
}
}
-=-=-=-=- CustomImage.cs (end) -=-=-=-=-
-=-=-=-=- WebForm1.aspx (begin) -=-=-=-=-
<%@ Register TagPrefix="cust " Namespace="Post backError"
Assembly="Postb ackError" %>
<%@ Page language="c#" Codebehind="Web Form1.aspx.cs"
AutoEventWireup ="false" Inherits="Postb ackError.WebFor m1"
trace="true"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1 </title>
<meta name="GENERATOR " Content="Micros oft Visual Studio .NET 7.1">
<meta name="CODE_LANG UAGE" Content="C#">
<meta name="vs_defaul tClientScript" content="JavaSc ript">
<meta name="vs_target Schema"
content="http://schemas.microso ft.com/intellisense/ie5">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<br>
<cust:CustomIma ge id="ciTest" runat="server" ImageUrl="arrow .gif"
Border="1" />
<br>
<br>
<asp:DataGrid id="DataGrid1" runat="server" CellSpacing="1"
CellPadding="0" GridLines="None " AutoGenerateCol umns="False"
AllowSorting="T rue" Width="100%">
<Columns>
<asp:TemplateCo lumn>
<HeaderTemplate >
<asp:CheckBox id="ckSelectAll " runat="server"
AutoPostBack="f alse" />
</HeaderTemplate>
<ItemTemplate >
<asp:CheckBox id="ckSelect" runat="server" AutoPostBack="f alse"
/>
</ItemTemplate>
</asp:TemplateCol umn>
<cust:CustomCol umn HeaderText="L" ItemStyle-BackColor="#ff0 000"/>
<asp:TemplateCo lumn>
<ItemTemplate >
<cust:CustomIma ge id="ciGridImage " runat="server"
ImageUrl="arrow .gif" Border="1" />
</ItemTemplate>
</asp:TemplateCol umn>
<asp:BoundColum n DataField="col1 " HeaderText="Col 1">
<ItemStyle HorizontalAlign ="Left" />
</asp:BoundColumn >
<asp:BoundColum n DataField="col2 " HeaderText="Col 2">
<ItemStyle HorizontalAlign ="Left" />
</asp:BoundColumn >
</Columns>
</asp:DataGrid>
<asp:Button id="Button1" runat="server" Text="Button"></asp:Button>
</form>
</body>
</HTML>
-=-=-=-=- WebForm1.aspx (end) -=-=-=-=-
-=-=-=-=- WebForm1.aspx.c s (begin) -=-=-=-=-
using System;
using System.Collecti ons;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.Sess ionState;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.H tmlControls;

namespace PostbackError
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>
public class WebForm1 : System.Web.UI.P age
{
protected System.Web.UI.W ebControls.Butt on Button1;
protected PostbackError.C ustomImage ciTest;
protected System.Web.UI.W ebControls.Data Grid DataGrid1;

ICollection CreateDataSourc e()
{
DataTable dt = new DataTable();
DataRow dr;

dt.Columns.Add( new DataColumn("col 1", typeof(Int32))) ;
dt.Columns.Add( new DataColumn("col 2", typeof(string)) );

for (int i = 0; i < 5; i++)
{
dr = dt.NewRow();

dr[0] = i;
dr[1] = "Item " + i.ToString();

dt.Rows.Add(dr) ;
}

DataView dv = new DataView(dt);
return dv;
}

private void Page_Load(objec t sender, System.EventArg s e)
{

if (!IsPostBack)
{
// Load this data only once.
DataGrid1.DataS ource= CreateDataSourc e();

DataGrid1.DataB ind();
}
}

#region Web Form Designer generated code
override protected void OnInit(EventArg s e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeCompo nent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeCompo nent()
{
this.Load += new System.EventHan dler(this.Page_ Load);

}
#endregion

}
}
-=-=-=-=- WebForm1.aspx.c s (end) -=-=-=-=-
Nov 18 '05 #1
2 3182
I have similar kinda problem. Actually, I have a checkbox in my
datagrid which I created dynamically. Now when the user checks the
Checkboxes and hits submit, the Datagrid is recreated. I think i have
to add the checkbox value to ViewState. Is that correct.
Will appreciate your help.

Best regards!

go************* *****@illexcasc ade.com (Jay Walker) wrote in message news:<40******* *************** **@posting.goog le.com>...
I created a custom DataGridColumn based on Marcie Robillard's MSDN
Article:

Creating Custom Columns for the ASP.NET Datagrid
http://msdn.microsoft.com/library/de...tomcolumns.asp

The problem I am having is that the data in the custom datagridcolumn
is not saved to viewstate and after postback, the column does not
contain data.

Any idea's?

I simplified the code so that the error is easy to reproduce.
Here is the code: (notice that the CustomImage that is standalone on
the page and the CustomImage that is embedded in a template column are
visible after postback.)

I can send a zip file of the project on request.

-=-=-=-=- CustomColumn.cs (begin) -=-=-=-=-
using System;
using System.Data;
using System.Web.UI.W ebControls;
using System.Web.UI;

namespace PostbackError
{
public class CustomColumn : System.Web.UI.W ebControls.Data GridColumn
{
public override void
InitializeCell( System.Web.UI.W ebControls.Tabl eCell cell, int
columnIndex, System.Web.UI.W ebControls.List ItemType itemType)
{
//if the grid is using sorting, the the header will contain a
DataGridLinkBut ton
//the functionality is set by the base class initializecell.
base.Initialize Cell (cell, columnIndex, itemType);
switch (itemType)
{
case ListItemType.It em:
case ListItemType.Al ternatingItem:
cell.DataBindin g += new EventHandler(On DataBinding);
break;
}}

private void OnDataBinding(o bject sender, EventArgs e)
{
TableCell cell = sender as TableCell;
DataGridItem dgi = cell.NamingCont ainer as DataGridItem;
DataRowView drv = dgi.DataItem as DataRowView;
//hardcoded for this example
string image = "arrow.gif" ;
if (image.Length == 0)
return;

CustomImage ri = new CustomImage();
cell.Controls.A dd(ri);
TrackViewState( );
string tooltip = "Help";
ri.ImageUrl = image;
ri.ToolTip = tooltip;
}}}
-=-=-=-=- CustomColumn.cs (end) -=-=-=-=-
-=-=-=-=- CustomImage.cs (begin) -=-=-=-=-
using System;
using System.Componen tModel;
using System.IO;
using System.Text;
using System.Text.Reg ularExpressions ;
using System.Web.UI;
using System.Web.UI.D esign;

namespace PostbackError
{
public class CustomImage : System.Web.UI.W ebControls.Imag e
{
private string _imagePath = string.Empty;

public CustomImage():b ase()
{
_imagePath = string.Empty;
}

[
Browsable(true) ,
Category("Appea rance"),
Description("Im age to be displayed when the mouse is not over the
image")
]
public new string ImageUrl
{
get { return (string)ViewSta te["riImageUrl "]; }
set { ViewState["riImageUrl "] = value; }
}

[
Browsable(true) ,
Category("Appea rance"),
Description("Im age to be displayed when the mouse is over the
image")
]
public string MouseOverImageU rl
{
get { return (string)ViewSta te["MouseOverImage Url"]; }
set { ViewState["MouseOverImage Url"] = value; }
}

[
Browsable(true) ,
Category("Navig ation"),
Description("Th e url to navigate to")
]
public string NavigateUrl
{
get { return (string)ViewSta te["NavigateUr l"]; }
set { ViewState["NavigateUr l"] = value; }
}

[
Browsable(true) ,
Category("Appea rance"),
DefaultValue(tr ue),
Description("Us e a MouseOver Image derived from the Image name.
(i.e. image.gif -> image_ovr.gif)" )
]
public bool UseMouseOverIma ge
{
get
{
string property = "UseMouseOverIm age";
if (ViewState[property] == null)
{
object obj = _GetDefaultValu e(property);
if (obj != null)
ViewState[property] = (bool)obj;
}
return (bool)ViewState[property];
}
set { ViewState["UseMouseOverIm age"] = value; }
}
override protected void OnPreRender(Eve ntArgs e)
{
base.OnPreRende r(e);
string s = base.ImageUrl;
base.ImageUrl = _imagePath + ImageUrl;
s = base.ImageUrl;
string mouseOver = _GetImageMouseO ver();
if (mouseOver != null && UseMouseOverIma ge)
{
Attributes.Add( "onmouseove r", "this.src=' " + _imagePath +
mouseOver + "'");
Attributes.Add( "onmouseout ", "this.src=' " + _imagePath + ImageUrl
+ "'");
}
}

/// <summary>
/// Render this control to the output parameter specified.
/// </summary>
/// <param name="output"> The HTML writer to write out to </param>
protected override void Render(HtmlText Writer output)
{
bool bWriteAnchor = NavigateUrl != null && NavigateUrl.Len gth > 0;
string s1 = base.ImageUrl;
base.ImageUrl = _imagePath + ImageUrl;

StringWriter sw = new StringWriter();
HtmlTextWriter buffer = new HtmlTextWriter( sw);

if (bWriteAnchor)
{
buffer.AddAttri bute(HtmlTextWr iterAttribute.H ref, NavigateUrl);
buffer.RenderBe ginTag(HtmlText WriterTag.A);
}

base.Render(buf fer);

if (bWriteAnchor)
buffer.RenderEn dTag();

string s = sw.ToString();
output.Write(s) ;
}

private object _GetDefaultValu e(string propertyName)
{
System.Componen tModel.Attribut eCollection attributes =
TypeDescriptor. GetProperties(t his)[propertyName].Attributes;
DefaultValueAtt ribute myAttribute =
(DefaultValueAt tribute)attribu tes[typeof(DefaultV alueAttribute)];
if (myAttribute != null)
return myAttribute.Val ue;
else
return null;
}

private string _GetImageMouseO ver()
{
if (MouseOverImage Url != null) return MouseOverImageU rl;

StringBuilder sb = new StringBuilder() ;
Regex re = new Regex(@"\.");
//Image should be like "media.gif" over image should be
"media_ovr. gif"
//and have a part left and right of the period
//if the entry is not in this format, then the entry is invalid
//so return null
if (ImageUrl == null) return null;

string[] sa = re.Split(ImageU rl);
if (sa.Length != 2) return null;
return sa[0] + "_ovr." + sa[1];
}
}

public class CustomImageDesi gner:ControlDes igner
{
public override string GetDesignTimeHt ml( )
{
return "<h6>" + this.ID + "</h6>";
}
}
}
-=-=-=-=- CustomImage.cs (end) -=-=-=-=-
-=-=-=-=- WebForm1.aspx (begin) -=-=-=-=-
<%@ Register TagPrefix="cust " Namespace="Post backError"
Assembly="Postb ackError" %>
<%@ Page language="c#" Codebehind="Web Form1.aspx.cs"
AutoEventWireup ="false" Inherits="Postb ackError.WebFor m1"
trace="true"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1 </title>
<meta name="GENERATOR " Content="Micros oft Visual Studio .NET 7.1">
<meta name="CODE_LANG UAGE" Content="C#">
<meta name="vs_defaul tClientScript" content="JavaSc ript">
<meta name="vs_target Schema"
content="http://schemas.microso ft.com/intellisense/ie5">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<br>
<cust:CustomIma ge id="ciTest" runat="server" ImageUrl="arrow .gif"
Border="1" />
<br>
<br>
<asp:DataGrid id="DataGrid1" runat="server" CellSpacing="1"
CellPadding="0" GridLines="None " AutoGenerateCol umns="False"
AllowSorting="T rue" Width="100%">
<Columns>
<asp:TemplateCo lumn>
<HeaderTemplate >
<asp:CheckBox id="ckSelectAll " runat="server"
AutoPostBack="f alse" />
</HeaderTemplate>
<ItemTemplate >
<asp:CheckBox id="ckSelect" runat="server" AutoPostBack="f alse"
/>
</ItemTemplate>
</asp:TemplateCol umn>
<cust:CustomCol umn HeaderText="L" ItemStyle-BackColor="#ff0 000"/>
<asp:TemplateCo lumn>
<ItemTemplate >
<cust:CustomIma ge id="ciGridImage " runat="server"
ImageUrl="arrow .gif" Border="1" />
</ItemTemplate>
</asp:TemplateCol umn>
<asp:BoundColum n DataField="col1 " HeaderText="Col 1">
<ItemStyle HorizontalAlign ="Left" />
</asp:BoundColumn >
<asp:BoundColum n DataField="col2 " HeaderText="Col 2">
<ItemStyle HorizontalAlign ="Left" />
</asp:BoundColumn >
</Columns>
</asp:DataGrid>
<asp:Button id="Button1" runat="server" Text="Button"></asp:Button>
</form>
</body>
</HTML>
-=-=-=-=- WebForm1.aspx (end) -=-=-=-=-
-=-=-=-=- WebForm1.aspx.c s (begin) -=-=-=-=-
using System;
using System.Collecti ons;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.Sess ionState;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.H tmlControls;

namespace PostbackError
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>
public class WebForm1 : System.Web.UI.P age
{
protected System.Web.UI.W ebControls.Butt on Button1;
protected PostbackError.C ustomImage ciTest;
protected System.Web.UI.W ebControls.Data Grid DataGrid1;

ICollection CreateDataSourc e()
{
DataTable dt = new DataTable();
DataRow dr;

dt.Columns.Add( new DataColumn("col 1", typeof(Int32))) ;
dt.Columns.Add( new DataColumn("col 2", typeof(string)) );

for (int i = 0; i < 5; i++)
{
dr = dt.NewRow();

dr[0] = i;
dr[1] = "Item " + i.ToString();

dt.Rows.Add(dr) ;
}

DataView dv = new DataView(dt);
return dv;
}

private void Page_Load(objec t sender, System.EventArg s e)
{

if (!IsPostBack)
{
// Load this data only once.
DataGrid1.DataS ource= CreateDataSourc e();

DataGrid1.DataB ind();
}
}

#region Web Form Designer generated code
override protected void OnInit(EventArg s e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeCompo nent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeCompo nent()
{
this.Load += new System.EventHan dler(this.Page_ Load);

}
#endregion

}
}
-=-=-=-=- WebForm1.aspx.c s (end) -=-=-=-=-

Nov 18 '05 #2
With some some help from Microsoft Support, the issue has been
resolved.

The simplest way to fix is to have any controls associated with a
column cell be created in the InitializeCell method that is invoked
every time the CustomColumn is built regardless of whether the
CustomColumn is databound.

In the code below, child controls were being added to the cell only in
the databind event. The contents of those controls were being saved to
the viewstate fine but when the page posts back, initializecell is
called, then loadviewstate is called. the viewstate information for
the cell exists, but since no child controls were created in the
initializeCell method, there is no control to associate with the
viewstate information.
Here is a code example to demonstrate the fix:

public override void
InitializeCell( System.Web.UI.W ebControls.Tabl eCell cell, int
columnIndex, System.Web.UI.W ebControls.List ItemType itemType)
{
base.Initialize Cell (cell, columnIndex, itemType);

Control boundControl = null;

switch (itemType)
{
case ListItemType.It em:
case ListItemType.Al ternatingItem:
boundControl = cell;
//must create the control inside InitializeCell so it is available
at LoadViewState
CustomImage ci = new CustomImage();
cell.Controls.A dd(ci);
break;
}

if (boundControl != null)
boundControl.Da taBinding += new EventHandler(It emDataBinding);
}
private void ItemDataBinding (object sender, EventArgs e)
{
TableCell cell = sender as TableCell;
CustomImage ci = cell.Controls[0] as CustomImage;

if (ci == null) return;
//set some properties on ci. These will be saved/loaded from
viewstate because the ci control was created in InitializeCell

ci.ImageUrl = "arrow.gif" ;
ci.Visible = true;
}


go************* *****@illexcasc ade.com (Jay Walker) wrote in message news:<40******* *************** **@posting.goog le.com>...
I created a custom DataGridColumn based on Marcie Robillard's MSDN
Article:

Creating Custom Columns for the ASP.NET Datagrid
http://msdn.microsoft.com/library/de...tomcolumns.asp

The problem I am having is that the data in the custom datagridcolumn
is not saved to viewstate and after postback, the column does not
contain data.

Any idea's?

I simplified the code so that the error is easy to reproduce.
Here is the code: (notice that the CustomImage that is standalone on
the page and the CustomImage that is embedded in a template column are
visible after postback.)

I can send a zip file of the project on request.

-=-=-=-=- CustomColumn.cs (begin) -=-=-=-=-
using System;
using System.Data;
using System.Web.UI.W ebControls;
using System.Web.UI;

namespace PostbackError
{
public class CustomColumn : System.Web.UI.W ebControls.Data GridColumn
{
public override void
InitializeCell( System.Web.UI.W ebControls.Tabl eCell cell, int
columnIndex, System.Web.UI.W ebControls.List ItemType itemType)
{
//if the grid is using sorting, the the header will contain a
DataGridLinkBut ton
//the functionality is set by the base class initializecell.
base.Initialize Cell (cell, columnIndex, itemType);
switch (itemType)
{
case ListItemType.It em:
case ListItemType.Al ternatingItem:
cell.DataBindin g += new EventHandler(On DataBinding);
break;
}}

private void OnDataBinding(o bject sender, EventArgs e)
{
TableCell cell = sender as TableCell;
DataGridItem dgi = cell.NamingCont ainer as DataGridItem;
DataRowView drv = dgi.DataItem as DataRowView;
//hardcoded for this example
string image = "arrow.gif" ;
if (image.Length == 0)
return;

CustomImage ri = new CustomImage();
cell.Controls.A dd(ri);
TrackViewState( );
string tooltip = "Help";
ri.ImageUrl = image;
ri.ToolTip = tooltip;
}}}
-=-=-=-=- CustomColumn.cs (end) -=-=-=-=-
-=-=-=-=- CustomImage.cs (begin) -=-=-=-=-
using System;
using System.Componen tModel;
using System.IO;
using System.Text;
using System.Text.Reg ularExpressions ;
using System.Web.UI;
using System.Web.UI.D esign;

namespace PostbackError
{
public class CustomImage : System.Web.UI.W ebControls.Imag e
{
private string _imagePath = string.Empty;

public CustomImage():b ase()
{
_imagePath = string.Empty;
}

[
Browsable(true) ,
Category("Appea rance"),
Description("Im age to be displayed when the mouse is not over the
image")
]
public new string ImageUrl
{
get { return (string)ViewSta te["riImageUrl "]; }
set { ViewState["riImageUrl "] = value; }
}

[
Browsable(true) ,
Category("Appea rance"),
Description("Im age to be displayed when the mouse is over the
image")
]
public string MouseOverImageU rl
{
get { return (string)ViewSta te["MouseOverImage Url"]; }
set { ViewState["MouseOverImage Url"] = value; }
}

[
Browsable(true) ,
Category("Navig ation"),
Description("Th e url to navigate to")
]
public string NavigateUrl
{
get { return (string)ViewSta te["NavigateUr l"]; }
set { ViewState["NavigateUr l"] = value; }
}

[
Browsable(true) ,
Category("Appea rance"),
DefaultValue(tr ue),
Description("Us e a MouseOver Image derived from the Image name.
(i.e. image.gif -> image_ovr.gif)" )
]
public bool UseMouseOverIma ge
{
get
{
string property = "UseMouseOverIm age";
if (ViewState[property] == null)
{
object obj = _GetDefaultValu e(property);
if (obj != null)
ViewState[property] = (bool)obj;
}
return (bool)ViewState[property];
}
set { ViewState["UseMouseOverIm age"] = value; }
}
override protected void OnPreRender(Eve ntArgs e)
{
base.OnPreRende r(e);
string s = base.ImageUrl;
base.ImageUrl = _imagePath + ImageUrl;
s = base.ImageUrl;
string mouseOver = _GetImageMouseO ver();
if (mouseOver != null && UseMouseOverIma ge)
{
Attributes.Add( "onmouseove r", "this.src=' " + _imagePath +
mouseOver + "'");
Attributes.Add( "onmouseout ", "this.src=' " + _imagePath + ImageUrl
+ "'");
}
}

/// <summary>
/// Render this control to the output parameter specified.
/// </summary>
/// <param name="output"> The HTML writer to write out to </param>
protected override void Render(HtmlText Writer output)
{
bool bWriteAnchor = NavigateUrl != null && NavigateUrl.Len gth > 0;
string s1 = base.ImageUrl;
base.ImageUrl = _imagePath + ImageUrl;

StringWriter sw = new StringWriter();
HtmlTextWriter buffer = new HtmlTextWriter( sw);

if (bWriteAnchor)
{
buffer.AddAttri bute(HtmlTextWr iterAttribute.H ref, NavigateUrl);
buffer.RenderBe ginTag(HtmlText WriterTag.A);
}

base.Render(buf fer);

if (bWriteAnchor)
buffer.RenderEn dTag();

string s = sw.ToString();
output.Write(s) ;
}

private object _GetDefaultValu e(string propertyName)
{
System.Componen tModel.Attribut eCollection attributes =
TypeDescriptor. GetProperties(t his)[propertyName].Attributes;
DefaultValueAtt ribute myAttribute =
(DefaultValueAt tribute)attribu tes[typeof(DefaultV alueAttribute)];
if (myAttribute != null)
return myAttribute.Val ue;
else
return null;
}

private string _GetImageMouseO ver()
{
if (MouseOverImage Url != null) return MouseOverImageU rl;

StringBuilder sb = new StringBuilder() ;
Regex re = new Regex(@"\.");
//Image should be like "media.gif" over image should be
"media_ovr. gif"
//and have a part left and right of the period
//if the entry is not in this format, then the entry is invalid
//so return null
if (ImageUrl == null) return null;

string[] sa = re.Split(ImageU rl);
if (sa.Length != 2) return null;
return sa[0] + "_ovr." + sa[1];
}
}

public class CustomImageDesi gner:ControlDes igner
{
public override string GetDesignTimeHt ml( )
{
return "<h6>" + this.ID + "</h6>";
}
}
}
-=-=-=-=- CustomImage.cs (end) -=-=-=-=-
-=-=-=-=- WebForm1.aspx (begin) -=-=-=-=-
<%@ Register TagPrefix="cust " Namespace="Post backError"
Assembly="Postb ackError" %>
<%@ Page language="c#" Codebehind="Web Form1.aspx.cs"
AutoEventWireup ="false" Inherits="Postb ackError.WebFor m1"
trace="true"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1 </title>
<meta name="GENERATOR " Content="Micros oft Visual Studio .NET 7.1">
<meta name="CODE_LANG UAGE" Content="C#">
<meta name="vs_defaul tClientScript" content="JavaSc ript">
<meta name="vs_target Schema"
content="http://schemas.microso ft.com/intellisense/ie5">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<br>
<cust:CustomIma ge id="ciTest" runat="server" ImageUrl="arrow .gif"
Border="1" />
<br>
<br>
<asp:DataGrid id="DataGrid1" runat="server" CellSpacing="1"
CellPadding="0" GridLines="None " AutoGenerateCol umns="False"
AllowSorting="T rue" Width="100%">
<Columns>
<asp:TemplateCo lumn>
<HeaderTemplate >
<asp:CheckBox id="ckSelectAll " runat="server"
AutoPostBack="f alse" />
</HeaderTemplate>
<ItemTemplate >
<asp:CheckBox id="ckSelect" runat="server" AutoPostBack="f alse"
/>
</ItemTemplate>
</asp:TemplateCol umn>
<cust:CustomCol umn HeaderText="L" ItemStyle-BackColor="#ff0 000"/>
<asp:TemplateCo lumn>
<ItemTemplate >
<cust:CustomIma ge id="ciGridImage " runat="server"
ImageUrl="arrow .gif" Border="1" />
</ItemTemplate>
</asp:TemplateCol umn>
<asp:BoundColum n DataField="col1 " HeaderText="Col 1">
<ItemStyle HorizontalAlign ="Left" />
</asp:BoundColumn >
<asp:BoundColum n DataField="col2 " HeaderText="Col 2">
<ItemStyle HorizontalAlign ="Left" />
</asp:BoundColumn >
</Columns>
</asp:DataGrid>
<asp:Button id="Button1" runat="server" Text="Button"></asp:Button>
</form>
</body>
</HTML>
-=-=-=-=- WebForm1.aspx (end) -=-=-=-=-
-=-=-=-=- WebForm1.aspx.c s (begin) -=-=-=-=-
using System;
using System.Collecti ons;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.Sess ionState;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.H tmlControls;

namespace PostbackError
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>
public class WebForm1 : System.Web.UI.P age
{
protected System.Web.UI.W ebControls.Butt on Button1;
protected PostbackError.C ustomImage ciTest;
protected System.Web.UI.W ebControls.Data Grid DataGrid1;

ICollection CreateDataSourc e()
{
DataTable dt = new DataTable();
DataRow dr;

dt.Columns.Add( new DataColumn("col 1", typeof(Int32))) ;
dt.Columns.Add( new DataColumn("col 2", typeof(string)) );

for (int i = 0; i < 5; i++)
{
dr = dt.NewRow();

dr[0] = i;
dr[1] = "Item " + i.ToString();

dt.Rows.Add(dr) ;
}

DataView dv = new DataView(dt);
return dv;
}

private void Page_Load(objec t sender, System.EventArg s e)
{

if (!IsPostBack)
{
// Load this data only once.
DataGrid1.DataS ource= CreateDataSourc e();

DataGrid1.DataB ind();
}
}

#region Web Form Designer generated code
override protected void OnInit(EventArg s e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeCompo nent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeCompo nent()
{
this.Load += new System.EventHan dler(this.Page_ Load);

}
#endregion

}
}
-=-=-=-=- WebForm1.aspx.c s (end) -=-=-=-=-

Nov 18 '05 #3

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

Similar topics

1
4105
by: Lisa | last post by:
I have a web app that gets a recordset from the database and fills a grid. You can drilldown from this table to a detail table. Because the tables sometimes get huge, and because I have to go back to the database again every time I postback anyway, I wanted to disable ViewState in the grids. Just to minimize the amount of stuff that gets...
3
4554
by: RCS | last post by:
I have an app that I have different "sections" that I want to switch back and forth from, all while having the server maintain viewstate for each page. In other words, when I am on Page1.aspx and set textboxes, radio buttons, etc - that viewstate is fine. Then I have a linkbutton that does a Server.Transfer over to Page2.aspx. When I...
7
3334
by: Girish | last post by:
OK.. phew. Playing with data grids for the past few days has been fun and a huge learning experience.. My problem. I have a requirement to display a gird with a gird. Within the embedded grid, theres a requirement to show a drop down menu list (this is a control I downloaded online) in one of the columns. For the purposes of this question,...
7
2980
by: Shimon Sim | last post by:
I have a custom composite control I have following property
0
1658
by: Walter | last post by:
Hi, can someone please help me with my custom control viewstate problem....I haven't slept for hours trying to get this fixed. I am making two custom controls which will be included on a single page. For now, I will call them box1 and box2. Each box has a panel and will display a list of link buttons on the panel. When the page loads for...
1
1645
by: Andreas Bergmeier | last post by:
Hi. Is there some KB article how to use EnableEventValidation when doing customized posts? Basicly we're building a post string via javascript and issue it via means of XMLHttpRequest to the server. This worked fine in .NET 1.1 Now in ASP.NET 2.0 I get an error message: 'Invalid postback or callback argument. Event validation is enabled...
2
4000
by: paulcis | last post by:
I am trying to produce a dynamic form from a database with unknown amount of records. I need to read the values and create a new textbox for each. I need to create the textboxes at page_init stage as indicated by microsoft. But I can't seem to save the number of controls in a viewstate variable or a session variable when creating them in...
1
4604
by: Veerle | last post by:
Hi, I use the infragistics tabcontrol on several pages of my application, that looks like this: <igtab:UltraWebTab ID="MyTabPage" runat="server"> <Tabs> <igtab:Tab Key="Tab1" Text="Title for tab 1"> <ContentTemplate> Content of tab 1, can contain usercontrols or
8
4474
by: Dan | last post by:
Hi, i experimented with postback and viewstate. With this code, there are 2 dropdownlists created, one visible and with AutoPostBack true, the other not visible and no AutoPostBack, and one button . The first time, when i choose value "b" of DD1, the second DD appears. That's normal. Now, what i don't understand is when i further click on...
0
7842
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...
0
7764
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...
0
8110
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. ...
0
8273
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...
0
6514
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...
1
5658
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5336
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...
0
3794
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1102
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.