why when unchecking checkbox - checkedChanged event doesn't execute - asp.net

In my function createCheckboxes() I dynamically create checkboxes - all of them with assigned checkedChanged event.
In the event handler i test if the checkbox is checked and if so I sore the value attribute in a session.
But for example if a client decides to check one checkbox and alue is added to the session, but then he suddenly decides that he want to uncjheck that checbox - so I should delete this value from the arraylist and then from the session.
The big problem is that it seems that when unchecking the Checkedchanged event handler is never executed and this code is never executed
else if (!chk.Checked)
{
lblProba.Text += "You wll be delited";
for (int i = 0; i < element.Count; i++)
{
if (element[i].ToString().Equals(chk.InputAttributes["value"]) == true)
element.Remove(element[i]);
}
}
My full code
protected void checkChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
if (chk.Checked)
{
element.Add(chk.InputAttributes["value"]);
}
else if (!chk.Checked)
{
lblProba.Text += "You wll be delited";
for (int i = 0; i < element.Count; i++)
{
if (element[i].ToString().Equals(chk.InputAttributes["value"]) == true)
element.Remove(element[i]);
}
}
for (int t = 0; t < element.Count; t++)
{
Session["chk"]+= element[t].ToString();
}
}
protected void createCheckboxes()
{
chkddlchange = true;
int numTourists = 2;
for (int i = 0; i < numTourists; i++)
{
Label myLabel = new Label();
myLabel.ID = "lblAccomodation" + (i + 1).ToString();
myLabel.Text = "Настаняване Турист" + (i + 1).ToString();
Page.FindControl("form1").Controls.Add(myLabel);
DropDownList myDropDownList = new DropDownList();
myDropDownList.ID = "ddlTourist" + i.ToString();
Page.FindControl("form1").Controls.Add(myDropDownList);
Page.FindControl("form1").Controls.Add(new LiteralControl("<br />"));
string connectionString = "Server=localhost\\SQLEXPRESS;Database=excursion;Trusted_Connection=true";
string query =
"SELECT Extra_Charge_ID, Excursion_ID, Amout, Extra_Charge_Description FROM EXTRA_CHARGES WHERE Excursion_ID=" + mynewstring;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(query, conn);
try
{
conn.Open();
SqlDataReader rd= cmd.ExecuteReader();
int s = 0;
while (rd.Read())
{
CheckBox mycheckbox = new CheckBox();
mycheckbox.ID = "chkblextracharge" + i.ToString() + s.ToString();
mycheckbox.Text = rd["Extra_Charge_Description"].ToString();
mycheckbox.InputAttributes.Add("value", rd["Extra_Charge_ID"].ToString());
mycheckbox.AutoPostBack = true;
mycheckbox.EnableViewState =true ;
mycheckbox.CheckedChanged += new EventHandler(checkChanged);
Page.FindControl("form1").Controls.Add(mycheckbox);
s++;
}
//myche.Add(mycheckbox.Items[s].Text);
}//End of try
catch (Exception ex)
{ }
}//end of for
}
}
}

Have you mentioned Autopostback=true while creating your checkbox? If not than please do it and see if it works or not.

Related

where to check the state of dynamically created checkboxes

Hello in my programme I need to create dynamically checkboxlist with items - got from teh database.
The problem is when Clicking a button i should get the text from cn only checked checkboxes and I should redirect the user to another page
And I have difficulty with determining width of the controls are checkedore
if I checked immediately after they are added
So if I write
if (mycheckbox.Items[s].Selected==true)
after this line
Page.FindControl("form1").Controls.Add(mycheckbox);
they are not checked still so this will be always false)
On postback event (clicking the button ) - we know on postback event dynamic controls no longer exist)
here is my code
protected void ddlNumberTourists_SelectedIndexChanged(object sender, EventArgs e)
{
int numTourists = Convert.ToInt32(ddlNumberTourists.SelectedItem.Text);
for (int i = 0; i < numTourists; i++)
{
string connectionString = "Server=localhost\\SQLEXPRESS;Database=excursion;Trusted_Connection=true";
string query =
"SELECT Extra_Charge_ID, Excursion_ID, Amout, Extra_Charge_Description FROM EXTRA_CHARGES WHERE Excursion_ID=" + mynewstring;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(query, conn);
try
{
conn.Open();
SqlDataReader rd = cmd.ExecuteReader();
int s = 0;
while (rd.Read())
{
mycheckbox.ID = "chkblextracharge" + i.ToString() + s.ToString();
mycheckbox.Items.Add(rd["Extra_Charge_Description"].ToString());
Page.FindControl("form1").Controls.Add(mycheckbox);
s++;
}
}//End of try
catch (Exception ex)
{ }
}//end of for
I've implemented a client-side check using jQuery in my online Quiz engine (demo: http://webinfocentral.com): the extract from that code snippet follows:
var _rows = $(this).find('tr');
for (i = 0; i < _rows.length; i++) {
// find out if checkbox is checked
_checked = $(_rows[i]).find('input:checkbox').is(':checked');
}
conn.Open();
SqlDataReader rd = cmd.ExecuteReader();
int s = 0;
mycheckboxList = new CheckBoxList();
mycheckboxList.ID = "chkblextracharge" + i.ToString();
while (rd.Read())
{
ListItem LI = new ListItem(rd["Extra_Charge_Description"].ToString(), s.ToString());
LI.Selected = rd["Selected_Criteria"] == "TRUE";
mycheckboxList.Items.Add(LI);
s++;
}
Page.FindControl("form1").Controls.Add(mycheckboxList);

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.

when i press the button the application gives me an error "index out of range" [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
In this code I dynamically create checkboxes which I populate with data from my database.
My intention is when I press the btnProba button to show the text property only from the selected checkboxes. But it gives me an error in this row saying that index is out of range! I can't explain why.
lblProba.Text = myche[0];
public partial class FormEGN : System.Web.UI.Page
{
string mynewstring;
List<string> myche = new List<string>();
CheckBoxList mycheckbox = new CheckBoxList();
protected void Page_Load(object sender, EventArgs e)
{
mynewstring = (string)Session["id2"];
// lblProba.Text = mynewstring;
if(!IsPostBack)
{
ddlNumberTourists.Items.Add("1");
ddlNumberTourists.Items.Add("2");
ddlNumberTourists.Items.Add("3");
}
}
protected void ddlNumberTourists_SelectedIndexChanged(object sender, EventArgs e)
{
int numTourists = Convert.ToInt32(ddlNumberTourists.SelectedItem.Text);
for (int i = 0; i < numTourists; i++)
{
Label myLabel = new Label();
myLabel.ID = "lblAccomodation" + (i + 1).ToString();
myLabel.Text = "Настаняване Турист" + (i + 1).ToString();
Page.FindControl("form1").Controls.Add(myLabel);
DropDownList myDropDownList = new DropDownList();
myDropDownList.ID = "ddlTourist" + i.ToString();
Page.FindControl("form1").Controls.Add(myDropDownList);
Page.FindControl("form1").Controls.Add(new LiteralControl("<br />"));
string connectionString = "Server=localhost\\SQLEXPRESS;Database=EXCURSIONSDATABASE;Trusted_Connection=true";
string query =
"SELECT Extra_Charge_ID, Excursion_ID, Amout, Extra_Charge_Description FROM EXTRA_CHARGES WHERE Excursion_ID=" + mynewstring;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(query, conn);
try
{
conn.Open();
SqlDataReader rd = cmd.ExecuteReader();
int s = 0;
while (rd.Read())
{
// CheckBox myCheckbox = new CheckBox();
// myCheckbox.ID = "ckbExtraCharge" + i.ToString() + s.ToString();
// myCheckbox.Text = rd["Extra_Charge_Description"].ToString();
// Page.FindControl("form1").Controls.Add(myCheckbox);
// Page.FindControl("form1").Controls.Add(new LiteralControl("<br />"));
// s++;
mycheckbox.ID = "chkblextracharge" + i.ToString() + s.ToString();
mycheckbox.Items.Add(rd["Extra_Charge_Description"].ToString());
Page.FindControl("form1").Controls.Add(mycheckbox);
if (mycheckbox.Items[s].Selected == true)
{
myche.Add(mycheckbox.Items[s].Text);
}
s++;
}
}
catch (Exception ex)
{ }
}
}
protected void btnProba_Click(object sender, EventArgs e)
{
lblProba.Text = myche[0];
}
protected void btnReserve_Click(object sender, EventArgs e)
{
string num = Request.QueryString["ExcursionID"];
Response.Redirect(String.Format("ClintsInformation.aspx?Excursiondate_ID={0}",num));
}
}
}
The function ddlNumberTourists_SelectedIndexChanged is the one that set the myche when is find some selected, but the data is lost on the second call where is the
protected void btnProba_Click(object sender, EventArgs e)
{
// here is the issue
lblProba.Text = myche[0];
}
The two calls are happening on different post back.
You need to call the ddlNumberTourists_SelectedIndexChanged(object sender, EventArgs e) on button click and not on every change of the dropdownlist, eg I rename it to CheckWhatIsSelected() and here is the code:
protected void CheckWhatIsSelected()
{
int numTourists = Convert.ToInt32(ddlNumberTourists.SelectedItem.Text);
for (int i = 0; i < numTourists; i++)
{
Label myLabel = new Label();
myLabel.ID = "lblAccomodation" + (i + 1).ToString();
myLabel.Text = "??????????? ??????" + (i + 1).ToString();
Page.FindControl("form1").Controls.Add(myLabel);
DropDownList myDropDownList = new DropDownList();
myDropDownList.ID = "ddlTourist" + i.ToString();
Page.FindControl("form1").Controls.Add(myDropDownList);
Page.FindControl("form1").Controls.Add(new LiteralControl("<br />"));
string connectionString = "Server=localhost\\SQLEXPRESS;Database=EXCURSIONSDATABASE;Trusted_Connection=true";
string query =
"SELECT Extra_Charge_ID, Excursion_ID, Amout, Extra_Charge_Description FROM EXTRA_CHARGES WHERE Excursion_ID=" + mynewstring;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(query, conn);
try
{
conn.Open();
SqlDataReader rd = cmd.ExecuteReader();
int s = 0;
while (rd.Read())
{
// CheckBox myCheckbox = new CheckBox();
// myCheckbox.ID = "ckbExtraCharge" + i.ToString() + s.ToString();
// myCheckbox.Text = rd["Extra_Charge_Description"].ToString();
// Page.FindControl("form1").Controls.Add(myCheckbox);
// Page.FindControl("form1").Controls.Add(new LiteralControl("<br />"));
// s++;
mycheckbox.ID = "chkblextracharge" + i.ToString() + s.ToString();
mycheckbox.Items.Add(rd["Extra_Charge_Description"].ToString());
Page.FindControl("form1").Controls.Add(mycheckbox);
if (mycheckbox.Items[s].Selected == true)
{
myche.Add(mycheckbox.Items[s].Text);
}
s++;
}
}
catch (Exception ex)
{ }
}
}
protected void btnProba_Click(object sender, EventArgs e)
{
CheckWhatIsSelected();
if(myche.Count > 0)
lblProba.Text = myche[0];
else
lblProba.Text = "Non selected";
}
One other possible solution is to save the myche on viewstate.
Other solution using the ViewState. You use the ViewState to store your selection and you have it after the post back. Do not forget to clear your list on ddlNumberTourists_SelectedIndexChanged
List<string> myche
{
get
{
if (!(ViewState["cMyChe"] is List<string>))
{
// need to fix the memory and added to viewstate
ViewState["cMyChe"] = new List<string>();
}
return (List<string>)ViewState["cMyChe"];
}
}
protected void btnProba_Click(object sender, EventArgs e)
{
// double check if have something on the list
if(myche.Count > 0)
lblProba.Text = myche[0];
else
lblProba.Text = "Non selected";
}

Creating a Textbox dynamically in for loop

I was trying to create a table dynamically and put textboxes in it. Here in the following code, i was trying to create a textbox with a distinct name for each k. But only the last value of k is getting displayed in the textbox. I was wondering how i could give a name to Textbox so all are shown.
for (int k = 0; k < tblCols; k++)
{
TableCell tc = new TableCell();
TextBox txtCompanyName = new TextBox();
txtCompanyName.Text = dsmissing.Tables[0].Rows[tblCols- 1]["NewCompanyName"].ToString();
tc.Controls.Add(txtCompanyName);
}
Replace this line
dsmissing.Tables[0].Rows[tblCols- 1]["NewCompanyName"].ToString();
With
dsmissing.Tables[0].Rows[k]["NewCompanyName"].ToString();
I assume you are talking about ID like below.
for (int k = 0; k < tblCols; k++)
{
TableCell tc = new TableCell();
TextBox txtCompanyName = new TextBox();
txtCompanyName.Text = dsmissing.Tables[0].Rows[k]["NewCompanyName"].ToString();
txtCompanyName.ID = Guid.NewGuid().ToString("N");
tc.Controls.Add(txtCompanyName);
}
I think you may have meant to do this:
for (int k = 0; k < tblCols; k++)
{
TableCell tc = new TableCell();
TextBox txtCompanyName = new TextBox();
//txtCompanyName.Text = dsmissing.Tables[0].Rows[tblCols-1 ["NewCompanyName"].ToString();
txtCompanyName.Text = dsmissing.Tables[0].Rows[k]["NewCompanyName"].ToString();
tc.Controls.Add(txtCompanyName);
}
Surely this will work and it is easy to understand
protected void Page_Load(object sender, EventArgs e)
{
button1();
}
protected void Page_Init(object sender, EventArgs e)
{
try
{
Label lbl = new Label();
lbl.ID = "lbl_label";
lbl.Text = "Enter the values";
form1.Controls.Add(lbl);
TextBox tb = new TextBox();
tb.ID = "tbx_textbox";
form1.Controls.Add(tb);
Button bt = new Button();
bt.ID = "bt_button";
bt.Text = "click";
form1.Controls.Add(bt);
}
catch (Exception ex) { }
}
public void button1()
{
Table table = new Table();
TableRow row = null;
TableCell cell = null;
TextBox tbx1 = this.Page.FindControl("tbx_textbox") as TextBox;
try
{
int a = int.Parse(tbx1.Text);
for (int i = 0; i < a; i++)
{
row = new TableRow();
cell = new TableCell();
TextBox tx = new TextBox();
tx.ID = "box" + i.ToString();
cell.Controls.Add(tx);
row.Cells.Add(cell);
table.Rows.Add(row);
form1.Controls.Add(table);
}
}
catch (Exception ex) { }
finally
{
table = null;
}
}

Asp.net:to call event handler of dynamically generated buttons?

i have set enableviewstate property of linkbutton and label to true.also regenrating same buttons on postback in pageload event handler.but m not able to call onclick event handler of linkbutton.can u please tell me what is problem with code?
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<LinkButton> listOfLinkButton = Session["ListOfLinkButton"] as List<LinkButton>;
List<Label> listOfLabel = Session["ListOfLabel"] as List<Label>;
if(listOfLabel!=null && listOfLinkButton!=null)
{
for (int i = 0; i < listOfLinkButton.Count; i++)
{
PlaceHolder1.Controls.Add(listOfLinkButton[i]);
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
PlaceHolder1.Controls.Add(listOfLabel[i]);
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
}
}
}
protected void LinkButton_Click(object sender, EventArgs e)
{
LinkButton linkButton = sender as LinkButton;
Response.Redirect(linkButton.Attributes["LinkUrl"]);
}
protected void Button1_Click1(object sender, EventArgs e)
{
List<LinkButton> listOfLinkButton = new List<LinkButton>();
List<Label> listOfLabel = new List<Label>();
Rss rssDocumentObj = RssFileReader.GetRssDocumentData(TextBox1.Text);
for (int j = 0; j < rssDocumentObj.ListOfChannel.Count; j++)
{
LinkButton linkButton = new LinkButton();
linkButton.ID = "LinkButtonForChannelDynamicInPlaceHolder1Id" + j;
linkButton.EnableViewState = true;
linkButton.ForeColor = Color.Blue;
linkButton.Font.Bold = true;
linkButton.Font.Size = 18;
linkButton.Font.Underline = true;
linkButton.Text = rssDocumentObj.ListOfChannel[j].ChannelTitle.InnerText;
linkButton.Click += new EventHandler(LinkButton_Click);
linkButton.Attributes.Add("LinkUrl", rssDocumentObj.ListOfChannel[j].ChannelLink.InnerText);
linkButton.Attributes.Add("onmouseover", "this.style.color = '#006699'");
linkButton.Attributes.Add("onmouseout", "this.style.color = '#0000ff'");
PlaceHolder1.Controls.Add(linkButton);
listOfLinkButton.Add(linkButton);
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
Label label = new Label();
label.ID = "LabelForChannelDynamicInPlaceHolder1Id" + j;
label.EnableViewState = true;
label.ForeColor = Color.DarkSlateGray;
label.Text = rssDocumentObj.ListOfChannel[j].ChannelDescription.InnerText;
PlaceHolder1.Controls.Add(label);
listOfLabel.Add(label);
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
for (int i = 0; i < rssDocumentObj.ListOfChannel[j].ListOfItem.Count; i++)
{
LinkButton linkButtonForItem = new LinkButton();
linkButtonForItem.ID = "LinkButtonDynamicInPlaceHolder1Id" + j + " " + i;
linkButtonForItem.EnableViewState = true;
linkButtonForItem.ForeColor = Color.Blue;
linkButtonForItem.Font.Bold = true;
linkButtonForItem.Font.Size = 14;
linkButtonForItem.Font.Underline = false;
linkButtonForItem.Text = rssDocumentObj.ListOfChannel[j].ListOfItem[i].ItemTitle.InnerText;
linkButtonForItem.Click += new EventHandler(LinkButton_Click);
linkButtonForItem.Attributes.Add("LinkUrl", rssDocumentObj.ListOfChannel[j].ListOfItem[i].ItemLink.InnerText);
linkButtonForItem.Attributes.Add("onmouseover", "this.style.color = '#006699'");
linkButtonForItem.Attributes.Add("onmouseout", "this.style.color = '#0000ff'");
PlaceHolder1.Controls.Add(linkButtonForItem);
listOfLinkButton.Add(linkButtonForItem);
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
Label labelForItem = new Label();
labelForItem.ID = "LabelDynamicInPlaceHolder1Id" + i;
labelForItem.EnableViewState = true;
labelForItem.ForeColor = Color.DarkGray;
labelForItem.Text = rssDocumentObj.ListOfChannel[j].ListOfItem[i].ItemDescription.InnerText;
PlaceHolder1.Controls.Add(labelForItem);
listOfLabel.Add(labelForItem);
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
Session["ListOfLinkButton"] = listOfLinkButton;
Session["ListOfLabel"] = listOfLabel;
}
}
}
}
You are making assumptions about what aspects of that button is saved in session. Try adding the event to the button again when you restore from session state during your page load.
I got my solution by assigning event-handler to button again after retrieving it from session, but I could not understand why I need to assign it again, when its already assigned in stored session variable.

Resources