how to rectreate this dynamic controls - asp.net

try to make a simple application in which I have a dropdown list with tems - numbers from 1 to 4.
Depending on the number the user choose - I create dynamically this number of checkboxes with binded checkedchanged event. So when the user checks some of the checkboxes so checkedchanged event is raised and I store the text of the checked checkbox in session and then when I click a button I want to see the text only from the checked checkboxes.
But it seems that in the checkedchanged event handler I should recreate the dynamic cotrol but I haven't found a solution. Thank you in advance.
public partial class proba : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
dd1.Items.Add("1");
dd1.Items.Add("2");
dd1.Items.Add("3");
dd1.Items.Add("4");
}
protected void dd1_SelectedIndexChanged1(object sender, EventArgs e)
{
int numTourists = Convert.ToInt32(dd1.SelectedItem.Text);
for (int i = 0; i < numTourists; i++)
{
CheckBox chk = new CheckBox();
chk.ID = "chk" + i;
chk.Text = "box" + i;
chk.AutoPostBack = true;
chk.CheckedChanged += new EventHandler(checkChanged);
Page.FindControl("form1").Controls.Add(chk);
}
}
protected void checkChanged(object sender, EventArgs e)
{
// here I should recteate the control
CheckBox chk = (CheckBox)sender;
lblpr.Text += chk.Text;
Srolession["chk"] = chk.Text;
}

static bool chkddlchange=false; //define this....to check you Drop Changed Or Not.
protected void Page_Load(object sender, EventArgs e)
{
dd1.Items.Add("1");
dd1.Items.Add("2");
dd1.Items.Add("3");
dd1.Items.Add("4");
if(Page.IsPostBack && chkddl==true)
{
int numTourists = Convert.ToInt32(dd1.SelectedItem.Text);
chkddl=true;//make true so you can know that you ddlindex is changed..
for (int i = 0; i < numTourists; i++)
{
CheckBox chk = new CheckBox();
chk.ID = "chk" + i;
chk.Text = "box" + i;
chk.AutoPostBack = true;
chk.CheckedChanged += new EventHandler(checkChanged);
Page.FindControl("form1").Controls.Add(chk);
}
}
}
protected void dd1_SelectedIndexChanged1(object sender, EventArgs e)
{
int numTourists = Convert.ToInt32(dd1.SelectedItem.Text);
chkddl=true;//make true so you can know that you ddlindex is changed..you have to
checkboxex on page load
for (int i = 0; i < numTourists; i++)
{
CheckBox chk = new CheckBox();
chk.ID = "chk" + i;
chk.Text = "box" + i;
chk.AutoPostBack = true;
chk.CheckedChanged += new EventHandler(checkChanged);
Page.FindControl("form1").Controls.Add(chk);
}
}

Related

Paging With Repeater

I want to do paging in repeater control. I am using xml as a database with linq. So please give me suggestion how can do it.
I try this code but its not working
public int RowCount
{
get
{
return (int)ViewState["RowCount"];
}
set
{
ViewState["RowCount"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FetchData(5, 0);
}
else
{
PlaceHolder1.Controls.Clear();
CreatePagingControl();
}
}
private void FetchData(int take,int pagesize)
{
var doc = XDocument.Load(Server.MapPath("~/BlogContent.xml"));
var result = doc.Descendants("post").Where(x => x.Element("id") != null).Take(take).Skip(pageSize)
.Select(x => new
{
id = x.Element("id").Value,
title = x.Element("title").Value,
Description = x.Element("Discription").Value,
dt = x.Element("dt").Value,
mnt = x.Element("mnt").Value,
yr = x.Element("yr").Value,
postdate = x.Element("PostDate").Value
}).OrderByDescending(x => x.id);
PagedDataSource page = new PagedDataSource();
page.AllowPaging = true;
page.AllowCustomPaging = true;
page.DataSource = result;
page.PageSize = 10;
if (!IsPostBack)
{
RowCount = result.Count();
}
}
private void CreatePagingControl()
{
for (int i = 0; i < (RowCount / 10) + 1; i++)
{
LinkButton lnk = new LinkButton();
lnk.Click += new EventHandler(lbl_click);
lnk.ID = "lnkPage" + (i + 1).ToString();
lnk.Text = (i + 1).ToString();
PlaceHolder1.Controls.Add(lnk);
Label spacer = new Label();
spacer.Text = " ";
PlaceHolder1.Controls.Add(spacer);
}
}
void lbl_click(object sender, EventArgs e)
{
LinkButton lnk = sender as LinkButton;
int currentPage = int.Parse(lnk.Text);
int take = currentPage * 10;
int skip = currentPage == 1 ? 0 : take - 10;
FetchData(take, skip);
}
When i am using this code the previous and next buttons are working but data on repeater is not changing
Have a look at :
void lbl_click(object sender, EventArgs e)
{
LinkButton lnk = sender as LinkButton;
int currentPage = int.Parse(lnk.Text);
int take = currentPage * 10;
int skip = currentPage == 1 ? 0 : take - 10;
FetchData(take, skip);
}
What you are saying is that you will display 10 times the number of the currentpage in rows. For instance if you are in page 4 you are going to display 40 rows, whereas in page 5 you will display 50 rows.
Then you dictate how many rows to skip, so in first page you will skip none, but in page 4 you will skip 40 - 10 = 30 rows. What you should do is take always a predefined set of rows, ie 10 and then the skip to be a variable.
For instance you should have your code as:
void lbl_click(object sender, EventArgs e)
{
LinkButton lnk = sender as LinkButton;
int currentPage = int.Parse(lnk.Text);
int take = 10;
int skip = (currentPage - 1) * 10;
FetchData(take, skip);
}
In page 1 you will skip 0 rows, in page 2 10 rows etc.
You could even take under consideration on having the take number in a user defined variable...
Edit
You should also check your Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FetchData(5, 0);
}
else
{
PlaceHolder1.Controls.Clear();
CreatePagingControl();
}
}
In the initial load of data you take the five first rows and skip 0. If you change that to
FetchData(10, 0);
you should be ok.
Giannis

Custom GridView Server Control DataBind causes duplicate control ID's error

OK. I've long used this site as a reference, but I've now hit a wall of my own.
I am creating a custom server control which inherits from the System.Web.UI.WebControls.GridView class. It's purpose is simply to display a grid with a very defined format. It binds and loads the data fine, but trying to activate any of the paging throws an exception saying "Multiple controls with the same ID 'lblHdrText_2' were found. FindControl requires that controls have unique IDs.".
I could just throw the event out to the user and let them do the paging, but one of the goals was to have this control be able to handle its own paging, just like the GridView control already does.
I'm having the same problem for sorting and altering the page size as well. Basically anytime I call "DataBind" within the control after it has already been rendered.
Here's the code to handle those events:
protected void OnFirstPageClicked(EventArgs e)
{
if (this.FirstPageClicked != null)
this.FirstPageClicked.Invoke(this, e);
GridViewPageEventArgs pgea = new GridViewPageEventArgs(0);
this.OnPageIndexChanging(pgea);
if (pgea.Cancel)
return;
this.PageIndex = 0;
this.RefreshData();
this.OnPageIndexChanged(e);
}
protected void OnLastPageClicked(EventArgs e)
{
if (this.LastPageClicked != null)
this.LastPageClicked.Invoke(this, e);
GridViewPageEventArgs pgea = new GridViewPageEventArgs(this.PageCount - 1);
this.OnPageIndexChanging(pgea);
if (pgea.Cancel)
return;
this.PageIndex = this.PageCount - 1;
this.RefreshData();
this.OnPageIndexChanged(e);
}
protected void OnPreviousPageClicked(EventArgs e)
{
if (this.PageIndex > 0)
{
if (this.PreviousPageClicked != null)
this.PreviousPageClicked.Invoke(this, e);
GridViewPageEventArgs pgea = new GridViewPageEventArgs(this.PageIndex++);
this.OnPageIndexChanging(pgea);
if (pgea.Cancel)
return;
this.PageIndex--;
this.RefreshData();
this.OnPageIndexChanged(e);
}
}
protected void OnNextPageClicked(EventArgs e)
{
if (this.PageIndex < this.PageCount - 1)
{
if (this.NextPageClicked != null)
this.NextPageClicked.Invoke(this, e);
GridViewPageEventArgs pgea = new GridViewPageEventArgs(this.PageIndex++);
this.OnPageIndexChanging(pgea);
if (pgea.Cancel)
return;
this.PageIndex++;
this.RefreshData();
this.OnPageIndexChanged(e);
}
}
protected void OnPageSizeChanged(EventArgs e)
{
this.RefreshData();
if (this.PageSizeChanged != null)
this.PageSizeChanged.Invoke(this, e);
}
protected override void OnDataBound(EventArgs e)
{
base.OnDataBound(e);
}
private void RefreshData()
{
this.DataBind();
}
private void imgPg_OnCommand(object sender, CommandEventArgs e)
{
switch (e.CommandName)
{
case "FirstPage":
this.OnFirstPageClicked(EventArgs.Empty);
break;
case "LastPage":
this.OnLastPageClicked(EventArgs.Empty);
break;
case "PrevPage":
this.OnPreviousPageClicked(EventArgs.Empty);
break;
case "NextPage":
this.OnNextPageClicked(EventArgs.Empty);
break;
}
}
private void drpPageSz_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList drpPgSz = (sender as DropDownList);
if (drpPgSz != null)
{
this.PageSize = int.Parse(drpPgSz.SelectedValue);
this.OnPageSizeChanged(e);
}
else
throw new Exception("Unable to determine page size: cannot cast sender as DropDownList.");
}
The actual event handlers are at the bottom. The "RefreshData" method is just there because I was experimenting with different ways of clearing the controls from the grid before I called "DataBind". So far, everything I've tried results in the entire grid not rendering after postback.
I am doing quite a bit with the Render and CreateChildControls, but the header generation itself is completely internal to the System.Web.UI.WebControls.GridView control. Here's my rendering code, if it helps at all:
protected override void OnPreRender(EventArgs e)
{
Control link = this.Page.Header.FindControl("CustomGridViewCss");
if (link == null)
{
System.Web.UI.HtmlControls.HtmlLink newLink = new System.Web.UI.HtmlControls.HtmlLink();
newLink.ID = "CustomGridViewCss";
newLink.Attributes.Add("href", this.Page.ClientScript.GetWebResourceUrl(typeof(ITCWebToolkit.Web.UI.Controls.GridView), "ITCWebToolkit.Web.UI.Controls.style.CustomGridView.css"));
newLink.Attributes.Add("type", "text/css");
newLink.Attributes.Add("rel", "stylesheet");
this.Page.Header.Controls.Add(newLink);
}
base.OnPreRender(e);
this.EnsureChildControls();
}
protected override void Render(HtmlTextWriter writer)
{
if (this._imgFPg != null)
this.Page.ClientScript.RegisterForEventValidation(this._imgFPg.UniqueID);
if (this._imgPrevPg != null)
this.Page.ClientScript.RegisterForEventValidation(this._imgPrevPg.UniqueID);
if (this._imgNextPg != null)
this.Page.ClientScript.RegisterForEventValidation(this._imgNextPg.UniqueID);
if (this._imgLastPg != null)
this.Page.ClientScript.RegisterForEventValidation(this._imgLastPg.UniqueID);
if (this._drpPageSz != null)
this.Page.ClientScript.RegisterForEventValidation(this._drpPageSz.UniqueID);
if (this.HeaderRow != null)
for (int i = 1; i < this.HeaderRow.Cells.Count - 2; i++)
if (i < this.Columns.Count && this.Columns[i] is SortableField && ((this.Columns[i] as SortableField).ShowSort))
{
ImageButton img = (this.HeaderRow.Cells[i].FindControl("imgSort_" + i.ToString()) as ImageButton);
if (img != null)
this.Page.ClientScript.RegisterForEventValidation(img.UniqueID);
}
base.Render(writer);
}
protected override Table CreateChildTable()
{
this.PagerSettings.Visible = false;
this.GridLines = GridLines.None;
Table tbl = base.CreateChildTable();
tbl.Attributes.Add("name", this.UniqueID);
return tbl;
}
protected override int CreateChildControls(System.Collections.IEnumerable dataSource, bool dataBinding)
{
this.GridLines = GridLines.None;
int iCount = base.CreateChildControls(dataSource, dataBinding);
// Modify footer row
System.Web.UI.WebControls.GridViewRow ftr = this.FooterRow;
// NOTE: We're modifying the footer first, because we're looking at the
// total number of rows in the header for the ColSpan property we
// use in the footer and we want the row count *before* we modify
// the header.
ftr.Cells.Clear();
this.BuildFooter(this.FooterRow);
// Modify Header Row
System.Web.UI.WebControls.GridViewRow hdr = this.HeaderRow;
hdr.CssClass = "GridViewHeader";
for (int c = 0; c < hdr.Cells.Count; c++)
{
hdr.Cells[c].CssClass = "GridViewHeaderTC";
if (c > 0)
hdr.Cells[c].Style.Add("border-left", "solid 1px #ccccd3");
if (c < this.Columns.Count && this.Columns[c] is SortableField && ((this.Columns[c] as SortableField).ShowSort))
{
hdr.Cells[c].Controls.Clear();
Label lblHdrText = new Label();
lblHdrText.ID = "lblHdrText_" + c.ToString();
lblHdrText.Text = hdr.Cells[c].Text;
hdr.Cells[c].Controls.Add(lblHdrText);
ImageButton imgSort = new ImageButton();
imgSort.ID = "imgSort_" + c.ToString();
imgSort.CssClass = "GridViewHeaderSort";
imgSort.ImageUrl = this.Page.ClientScript.GetWebResourceUrl(typeof(ITCWebToolkit.Web.UI.Controls.GridView), "ITCWebToolkit.Web.UI.Controls.images.gridView.Sort.png");
imgSort.AlternateText = "";
imgSort.CommandArgument = (this.Columns[c] as BoundField).DataField;
imgSort.CommandName = "Sort";
imgSort.Command += new CommandEventHandler(this.imgSort_OnCommand);
hdr.Cells[c].Controls.Add(imgSort);
imgSort.Attributes.Add("name", imgSort.UniqueID);
}
}
TableCell tdTL = new TableCell();
tdTL.Style.Add(HtmlTextWriterStyle.Width, "6px");
tdTL.CssClass = "GridViewHeaderTL";
hdr.Cells.AddAt(0, tdTL);
TableCell tdTR = new TableCell();
tdTR.Style.Add(HtmlTextWriterStyle.Width, "6px");
tdTR.Style.Add("border-left", "1px solid #ccccd3;");
tdTR.CssClass = "GridViewHeaderTR";
hdr.Cells.Add(tdTR);
// Modify individual rows
for (int i = 0; i < this.Rows.Count; i++)
{
System.Web.UI.WebControls.GridViewRow tr = this.Rows[i];
tr.CssClass = (i % 2 == 0) ? "GridViewLineAlt" : "GridViewLine";
for (int c = 0; c < tr.Cells.Count - 1; c++)
tr.Cells[c].Style.Add("border-right", "solid 1px #ccccd3");
TableCell tdL = new TableCell();
tdL.CssClass = "GridViewLineLeft";
tr.Cells.AddAt(0, tdL);
TableCell tdR = new TableCell();
tdR.CssClass = "GridViewLineRight";
tr.Cells.Add(tdR);
}
return iCount;
}
protected void BuildFooter(GridViewRow tr)
{
TableCell tdBL = new TableCell();
tdBL.Style.Add(HtmlTextWriterStyle.Width, "6px");
tdBL.CssClass = "GridViewFooterBL";
tr.Cells.Add(tdBL);
int colCount = this.HeaderRow.Cells.Count;
TableCell td = new TableCell();
td.ID = "tdFooterControls";
td.CssClass = "GridViewFooterBC";
td.ColumnSpan = colCount;
this._spanPgBtns = new Label();
this._spanPgBtns.ID = "spanPgButtons";
this._spanPgBtns.Style.Add("float", "right");
this._spanPgBtns.Style.Add("margin-right", "20px");
this._imgFPg = new ImageButton();
this._imgFPg.ID = "imgFPg";
this._imgFPg.CssClass = "FirstPg";
this._imgFPg.ImageUrl = this.Page.ClientScript.GetWebResourceUrl(typeof(ITCWebToolkit.Web.UI.Controls.GridView), "ITCWebToolkit.Web.UI.Controls.images.gridView.FstPg.png");
this._imgFPg.ImageAlign = ImageAlign.Middle;
this._imgFPg.CommandName = "FirstPage";
this._imgFPg.Command += new CommandEventHandler(this.imgPg_OnCommand);
this._spanPgBtns.Controls.Add(this._imgFPg);
this._imgPrevPg = new ImageButton();
this._imgPrevPg.ID = "imgPrevPg";
this._imgPrevPg.CssClass = "PrevPg";
this._imgPrevPg.ImageUrl = this.Page.ClientScript.GetWebResourceUrl(typeof(ITCWebToolkit.Web.UI.Controls.GridView), "ITCWebToolkit.Web.UI.Controls.images.gridView.PrevPg.png");
this._imgPrevPg.ImageAlign = ImageAlign.Middle;
this._imgPrevPg.CommandName = "PrevPage";
this._imgPrevPg.Command += new CommandEventHandler(this.imgPg_OnCommand);
this._spanPgBtns.Controls.Add(this._imgPrevPg);
Label lblPageNum = new Label();
lblPageNum.ID = "lblPageNum";
lblPageNum.Width = new Unit("50px");
lblPageNum.Text = string.Format("{0} / {1}", this.PageIndex + 1, this.PageCount);
lblPageNum.Style.Add(HtmlTextWriterStyle.TextAlign, "center");
this._spanPgBtns.Controls.Add(lblPageNum);
this._imgNextPg = new ImageButton();
this._imgNextPg.ID = "imgNextPg";
this._imgNextPg.CssClass = "NextPg";
this._imgNextPg.ImageUrl = this.Page.ClientScript.GetWebResourceUrl(typeof(ITCWebToolkit.Web.UI.Controls.GridView), "ITCWebToolkit.Web.UI.Controls.images.gridView.NextPg.png");
this._imgNextPg.ImageAlign = ImageAlign.Middle;
this._imgNextPg.CommandName = "NextPage";
this._imgNextPg.Command += new CommandEventHandler(this.imgPg_OnCommand);
this._spanPgBtns.Controls.Add(this._imgNextPg);
this._imgLastPg = new ImageButton();
this._imgLastPg.ID = "imgLastPg";
this._imgLastPg.CssClass = "LastPg";
this._imgLastPg.ImageUrl = this.Page.ClientScript.GetWebResourceUrl(typeof(ITCWebToolkit.Web.UI.Controls.GridView), "ITCWebToolkit.Web.UI.Controls.images.gridView.LstPg.png");
this._imgLastPg.ImageAlign = ImageAlign.Middle;
this._imgLastPg.CommandName = "LastPage";
this._imgLastPg.Command += new CommandEventHandler(this.imgPg_OnCommand);
this._spanPgBtns.Controls.Add(this._imgLastPg);
td.Controls.Add(this._spanPgBtns);
Label spanPageSz = new Label();
spanPageSz.ID = "spanPageSz";
spanPageSz.Style.Add("margin-left", "20px");
this._drpPageSz = new DropDownList();
this._drpPageSz.ID = "drpPageSzSelect";
this._drpPageSz.AutoPostBack = true;
this._drpPageSz.SelectedIndexChanged += new EventHandler(drpPageSz_SelectedIndexChanged);
this._drpPageSz.Items.Add(new ListItem("10", "10"));
this._drpPageSz.Items.Add(new ListItem("25", "25"));
this._drpPageSz.Items.Add(new ListItem("50", "50"));
this._drpPageSz.Items.Add(new ListItem("100", "100"));
spanPageSz.Controls.Add(this._drpPageSz);
td.Controls.Add(spanPageSz);
Label lblRecVis = new Label();
lblRecVis.ID = "lblRecordsCount";
lblRecVis.Style.Add("margin-left", "20px");
lblRecVis.Text = string.Format("Displaying {0} of {1} records.", Math.Min(this.PageSize, this.Rows.Count - (this.PageIndex * this.PageSize)), this.Rows.Count);
lblRecVis.Text = "Total Record Display";
td.Controls.Add(lblRecVis);
tr.Cells.Add(td);
TableCell tdBR = new TableCell();
tdBR.Style.Add(HtmlTextWriterStyle.Width, "6px");
tdBR.CssClass = "GridViewFooterBR";
tr.Cells.Add(tdBR);
this._imgFPg.Attributes.Add("name", this._imgFPg.UniqueID);
this._imgPrevPg.Attributes.Add("name", this._imgPrevPg.UniqueID);
this._imgNextPg.Attributes.Add("name", this._imgNextPg.UniqueID);
this._imgLastPg.Attributes.Add("name", this._imgLastPg.UniqueID);
this._drpPageSz.Attributes.Add("name", this._drpPageSz.UniqueID);
}
I'm only about 6/10 on custom server controls, so I'm sure there's at least one thing I'm doing wrong here :)
Thanks in advance for any help!
OK. I finally found a reference and answered my own question. The trick is in overriding the "PerformSelect" method and handling DataSource vs DataSourceID there.
Details on how to do this can be found on this MSDN page:
http://msdn.microsoft.com/en-us/library/ms366539(v=vs.90).aspx
Look for the section titled "Initiate Data Retrieval" a little over half-way down.

Problem with page lifecycle

The qustion was modified by me to show a complete picture.
I have a basic question:
code behind:
protected void Page_Load(object sender, EventArgs e)
{
int firstPageIndex = 0;
int lastPageIndex = 5;
if (TotalPageNumber > 5)
{
if ((TotalPageNumber - PageIndex) <= 5)
firstPageIndex = TotalPageNumber - 5;
firstPageIndex = PageIndex < 3 ? 0 : PageIndex - 2;
}
else
{
firstPageIndex = 0;
lastPageIndex = TotalPageNumber;
}
for (int i = firstPageIndex; i < firstPageIndex + lastPageIndex; i++)
{
LinkButton lnk = new LinkButton();
lnk.CommandArgument = i.ToString();
lnk.Click += new EventHandler(lblPageNumber_Click);
lnk.ID = "lnkPage" + (i + 1).ToString();
lnk.Text = (i + 1).ToString();
plcPagerHolder.Controls.Add(lnk);
} }
int _pageIndex;
public int PageIndex
{
get
{
object objPage = ViewState["_pageIndex"];
if (objPage == null)
{
_pageIndex = 0;
}
else
{
_pageIndex = (int)objPage;
}
return _pageIndex;
}
set {ViewState["_pageIndex"] = value; }
}
protected void lnkPagerNext_Click(object sender, EventArgs e)
{
PageIndex = PageIndex == TotalPageNumber - 1 ? 0 : PageIndex + 1;
}
The problem is with Page_Load event, I expect to get new PageIndex after the linkbutton is clicked.
Update:
My Foo adds new controls to the page, based on provide Page index so I guess I can't put it in Prerender.
Two options
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Foo (PageIndex);
}
}
protected void LinkButton_Click(object sender, EventArgs e)
{
PageIndex = int.Parse(((LinkButton)sender).CommandArgument);
Foo (PageIndex);
}
or
protected void Page_PreRender(object sender, EventArgs e)
{
Foo (PageIndex);
}
you can place Foo (PageIndex) in Page_LoadComplete event instead of Page_Load, i.e.
protected void Page_LoadComplete(object sender, EventArgs e)
{
Foo (PageIndex);
}
LoadComplete event is raised after Control events.
Edit:
LoadComplete is the earliest place where you can safely access new pageindex and also you can add there another controls, but that is possible also in PreRender.
And you will, but Page_Load gets called before the event handler for the linkbutton .. so, you can't really expect it to be changed yet.

asp.net - GridView dynamic footer row creation problem

I am able to create BoundFields and Footer-rows dynamically like this in my GridView:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
CreateGridView();
}
}
private void CreateGridView()
{
GridView1.Columns.Clear();
DataTable dataTable = Book.GetBooksDataSet().Tables[0];
CommandField cf = new CommandField();
cf.ShowEditButton = true;
GridView1.Columns.Add(cf);
int colCount = 1;
foreach (DataColumn c in dataTable.Columns)
{
BoundField boundField = new BoundField();
boundField.DataField = c.ColumnName;
boundField.HeaderText = c.ColumnName;
//boundField.FooterText = "---";
if (colCount == 3 || colCount == 5)
{
boundField.ReadOnly = true;
}
GridView1.Columns.Add(boundField);
colCount++;
}
GridView1.ShowFooter = true;
GridView1.DataSource = dataTable;
GridView1.DataBind();
GridViewRow footerRow = GridView1.FooterRow;
Button b = new Button();
b.Text = "Add New";
int i = 0;
footerRow.Cells[i].Controls.Add(b);
foreach (DataColumn c in dataTable.Columns)
{
++i;
TextBox tb = new TextBox();
footerRow.Cells[i].Controls.Add(tb);
}
}
....................................
....................................
....................................
}
But the problem is, when I click the "Add New" - button, it disappears instantly. And, also I am unable to add any event handler to it. Or intercept its actions like this:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "Edit")
{
GridView1.EditIndex = index;
GridViewRow selectedRow = ((GridView)e.CommandSource).Rows[index];
//We can get cell data like this
string id = selectedRow.Cells[1].Text;
string isbn = selectedRow.Cells[2].Text;
//This is necessary to GridView to be showed up.
CreateGridView();
}
else if (e.CommandName == "Update")
{
LinkButton updateButton = (LinkButton)e.CommandSource;
DataControlFieldCell dcfc = (DataControlFieldCell)updateButton.Parent;
GridViewRow gvr = (GridViewRow)dcfc.Parent;
//The update...................
//Update grid-data to database
UpdateDataInTheDatabase(gvr.Cells[1].Controls);
//Grid goes back to normal
GridView1.EditIndex = -1;
//This is necessary to GridView to be showed up.
CreateGridView();
}
}
One more thing, I have seen some solutions that suggests to handle the GridView's rowBound event. But I need to do it from within Page_load event handler, or in, GridView1_RowCommand event handler.
Dynamically created controls mus be re-created on every postback. Your "Add New" button causes a postback so the dynamically created footer disappears. Is there a reason this grid has to be created dynamically? From the code you posted it appears that you could do this in markup instead. If not, you'll have to re-create the dynamic controls on every postback.
Edited to add:
I played with this a little bit and what's below works in that the grid doesn't disappear and events are handled, but it doesn't actually do anything. Hope this helps.
Markup:
<p><asp:Literal ID="Literal1" runat="server" /></p>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
OnRowCommand="GridView1_RowCommand"
OnRowEditing="GridView1_RowEditing"/>
Code:
protected void Page_Load(object sender, EventArgs e)
{
BindGridView();
}
private DataTable GetBooksDataTable()
{
var dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Title", typeof(string));
dt.Columns.Add("Author", typeof(string));
for (int index = 0; index < 10; index++)
{
dt.Rows.Add(index, "Title" + index, "Author" + index);
}
return dt;
}
private void BindGridView()
{
var dt = GetBooksDataTable();
GridView1.Columns.Clear();
GridView1.ShowFooter = true;
var cf = new CommandField();
cf.HeaderText = "Action";
cf.ShowEditButton = true;
GridView1.Columns.Add(cf);
for (int index = 0; index < dt.Columns.Count; index++)
{
var boundField = new BoundField();
boundField.DataField = dt.Columns[index].ColumnName;
boundField.HeaderText = dt.Columns[index].ColumnName;
GridView1.Columns.Add(boundField);
}
GridView1.DataSource = dt;
GridView1.DataBind();
var footer = GridView1.FooterRow;
var b = new LinkButton();
b.Text = "Add New";
b.CommandName = "Add New";
footer.Cells[0].Controls.Add(b);
for (int index = 1; index < dt.Columns.Count + 1; index++)
{
var tb = new TextBox();
footer.Cells[index].Controls.Add(tb);
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
Literal1.Text = e.CommandName;
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
Literal1.Text = "Editing row index " + e.NewEditIndex.ToString();
}
Move your code from Page_Load to Page_Init. Things added in the Page_Load last only for the lifecycle of one postback.
You'd then be able to add eventhandlers, intercept events etc.

Disable a checkbox created at runtime

In my asp.net application i have created checkboxes at runtime. I want to disable the checked checkbox when i click on a button. How do I achieve this? Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 12; i++)
{
tr = new TableRow();
tr.BorderStyle = BorderStyle.Groove;
for (int j = 0; j < 18; j++)
{
tc = new TableCell();
tc.BorderStyle = BorderStyle.Groove;
ch = new CheckBox();
tc.Controls.Add(ch);
tr.Cells.Add(tc);
}
Table1.Rows.Add(tr);
}
if(!IsPostBack)
{
form1.Controls.Add(ch);
mRoleCheckBoxList.Add("RoleName", ch);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
IDictionaryEnumerator RoleCheckBoxEnumerator = mRoleCheckBoxList.GetEnumerator();
while (RoleCheckBoxEnumerator.MoveNext())
{
CheckBox RoleCheckBox = (CheckBox)RoleCheckBoxEnumerator.Value;
string BoxRoleName = (string)RoleCheckBox.Text;
if (RoleCheckBox.Checked == true)
{
RoleCheckBox.Enabled = false;
break;
}
}
}
One rule-of-thumb while dealing with dynamically generated user controls is that you have to add them to the container on EVERY POSTBACK.
Just modify your code to generate the controls on every postback, and your code will start working like a charm!
EDIT
I am unsure what the ch variable is. I have assumed that its a checkbox. If I am correct, then all you have to do is to modify these lines
if(!IsPostBack)
{
form1.Controls.Add(ch);
mRoleCheckBoxList.Add("RoleName", ch);
}
to this
//if(!IsPostBack)
{
form1.Controls.Add(ch);
mRoleCheckBoxList.Add("RoleName", ch);
}
EDIT 2
This is the code for generating 10 checkboxes dynamically -
protected void Page_Init(object sender, EventArgs e)
{
CheckBox c = null;
for (int i = 0; i < 10; i++)
{
c = new CheckBox();
c.ID = "chk" + i.ToString();
c.Text = "Checkbox " + (i + 1).ToString();
container.Controls.Add(c);
}
}
Check the checkboxes when the page renders on the client side, click the button. This will cause a postback and the checkboxes will be generated again. In the click event of the button, you'll be able to find the checkboxes like this -
protected void Button1_Click(object sender, EventArgs e)
{
CheckBox c = null;
for (int i = 0; i < 10; i++)
{
c = container.FindControl("chk" + i.ToString()) as CheckBox;
//Perform your relevant checks here, and disable the checkbox.
}
}
I hope this is clear.
Maybe
RoleCheckBox.Parent.Controls.Remove(RoleCheckBox);
You are not getting a proper reference to your checkboxes - mRoleCheckBoxList is not mentioned as part of your checkbox creation.
Try the following in your button event handler:
foreach (TableRow row in Table1.Rows)
foreach (TableCell cell in row.Cells)
{
CheckBox check = (CheckBox)cell.Controls[0];
if (check.Checked) check.Enabled = false;
}
Always when creating dynamic controls in .Net create them here:
protected override void CreateChildControls()
{
base.CreateChildControls();
this.CreateDynamicControls();
} //eof method
and in the PostBack find the them either from the event trigger or from a non-dynamic control:
/// <summary>
/// Search for a control within the passed root control by the control id passed as string
/// </summary>
/// <param name="root">the upper control to start to search for</param>
/// <param name="id">the id of the control as string</param>
/// <returns></returns>
public virtual Control FindControlRecursively(Control root, string id)
{
try
{
if (root.ID == id)
{
return root;
} //eof if
foreach (Control c in root.Controls)
{
Control t = this.FindControlRecursively( c, id);
if (t != null)
{
return t;
} //eof if
} //eof foreach
} //eof try
catch (Exception e)
{
return null;
} //eof catch
return null;
} //eof method

Resources