Hi Jim,
Thanks for your feedback.
Oh, I have found out the trick.
Actually, the web server control will automatically persists its state in
viewstate, but the dynamic added controls(or columns) are not automatically
added to the page's view state, so you are obliged to add logic to the page
to make sure the persistant with each round trip.
An good way to do is to override page's LoadViewState method:
using System;
using System.Collecti ons;
using System.Componen tModel;
using System.Data;
using System.Data.Sql Client;
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 checkboxvalueda tagrid
{
public class WebForm1 : System.Web.UI.P age
{
protected System.Web.UI.W ebControls.Butt on Button1;
private DataGrid dg1=null ,dg2=null;
protected System.Web.UI.H tmlControls.Htm lForm Form1;
private void Page_Load(objec t sender, System.EventArg s e)
{
if(!IsPostBack)
{
addcolumn();
SqlDataAdapter adapter=new SqlDataAdapter( "select * from
jobs","server=l ocalhost;databa se=pubs;uid=sa; pwd=");
DataSet ds=new DataSet();
adapter.Fill(ds );
dg1.DataSource= ds;
dg1.DataBind();
dg2.DataSource= ds;
dg2.DataBind();
}
}
protected override void LoadViewState(o bject savedState)
{
base.LoadViewSt ate (savedState);
addcolumn();
}
public void addcolumn()
{
dg1=new DataGrid();
dg2=new DataGrid();
TemplateColumn tc=new TemplateColumn( );
tc.ItemTemplate =new checkboxtemplat e();
dg1.Columns.Add (tc);
dg2.Columns.Add (tc);
Form1.Controls. Add(dg1);
Form1.Controls. Add(dg2);
}
public class checkboxtemplat e: ITemplate
{
public void InstantiateIn(C ontrol container)
{
CheckBox cb=new CheckBox();
cb.ID="checkbox ";
container.Contr ols.Add(cb);
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArg s e)
{
InitializeCompo nent();
base.OnInit(e);
}
private void InitializeCompo nent()
{
this.Button1.Cl ick += new System.EventHan dler(this.Butto n1_Click);
this.Load += new System.EventHan dler(this.Page_ Load);
}
#endregion
private void Button1_Click(o bject sender, System.EventArg s e)
{
foreach(DataGri dItem item in dg1.Items)
{
CheckBox myCheckbox = (CheckBox)item. Cells[0].Controls[0];
if(myCheckbox.C hecked == true)
{
Response.Write( item.ItemIndex. ToString());
}
}
}
}
}
Note: I dynamic add 2 datagrid into the "FORM" control collection(Can not
be the page's control collection, because the checkbox column will interact
with server side)
In Button1_Click, I only retrieve the first datagrid's checkbox column
state.
It works well on my machine, if you have anything unclear, please feel free
to tell me.
Merry Christmas!!
Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! -
www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.