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.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace checkboxvaluedatagrid
{
public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button Button1;
private DataGrid dg1=null ,dg2=null;
protected System.Web.UI.HtmlControls.HtmlForm Form1;
private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
addcolumn();
SqlDataAdapter adapter=new SqlDataAdapter("select * from
jobs","server=localhost;database=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(object savedState)
{
base.LoadViewState (savedState);
addcolumn();
}
public void addcolumn()
{
dg1=new DataGrid();
dg2=new DataGrid();
TemplateColumn tc=new TemplateColumn();
tc.ItemTemplate=new checkboxtemplate();
dg1.Columns.Add(tc);
dg2.Columns.Add(tc);
Form1.Controls.Add(dg1);
Form1.Controls.Add(dg2);
}
public class checkboxtemplate: ITemplate
{
public void InstantiateIn(Control container)
{
CheckBox cb=new CheckBox();
cb.ID="checkbox";
container.Controls.Add(cb);
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void Button1_Click(object sender, System.EventArgs e)
{
foreach(DataGridItem item in dg1.Items)
{
CheckBox myCheckbox = (CheckBox)item.Cells[0].Controls[0];
if(myCheckbox.Checked == 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.