Disable a checkbox created at runtime - asp.net-2.0

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

Related

asp.net gridview outside button to save

I have gridview built dynamically at run-time bind to datatable, and button to save gridview data placed outside gridview
1- Create GridView
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CreateGrid();
}
}
void CreateGrid()
{
int nTransID = Convert.ToInt32(Session["trans_id"]);
//
string strSQL = #"EXEC [dbo].[sp_GetTransaction] " + nTransID;
DataTable dtData = clsGlobal.GetDataTable(strSQL);
//
if (ViewState["dtTransDetail"] == null) ViewState.Add("dtTransDetail", dtData);
else ViewState["dtTransDetail"] = dtData;
//
foreach (DataColumn dc in dtData.Columns)
{
if (dc.ColumnName.Contains("!;"))
{
TemplateField tField = new TemplateField();
tField.ItemTemplate = new AddTemplateToGridView(ListItemType.Item, dc.ColumnName);
//\\ --- template contain textbox
tField.HeaderText = dc.ColumnName;
GridView1.Columns.Add(tField);
}
}
}
This is my template class:
public class AddTemplateToGridView : ITemplate
{
ListItemType _type;
string _colName;
public AddTemplateToGridView(ListItemType type, string colname)
{
_type = type;
_colName = colname;
}
void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
switch (_type)
{
case ListItemType.Item:
TextBox text = new TextBox();
text.ID = "txtAmount";
text.DataBinding += new EventHandler(txt_DataBinding);
container.Controls.Add(text);
break;
}
}
void txt_DataBinding(object sender, EventArgs e)
{
TextBox textBox = (TextBox)sender;
GridViewRow container = (GridViewRow)textBox.NamingContainer;
object dataValue = DataBinder.Eval(container.DataItem, _colName);
if (dataValue != DBNull.Value)
{
textBox.Text = dataValue.ToString();
}
}
}
So i have a gridview with textboxe's all open to edit at once
The problem is, when i click on Save button "which is outside gridview" all textboxe's gone
protected void btnSave_Command(object sender, CommandEventArgs e)
{
for (int nRow = 0; nRow < GridView1.Rows.Count; nRow++)
{
for (int nCol = 0; nCol < GridView1.Columns.Count; nCol++)
{
if (GridView1.Rows[nRow].Cells[nCol].Controls.Count == 0) continue;
//\\ --- Controls.Count always = 0
//\\ --- However each cell contain textbox
//\\ --- textbox disappear after save button clicked
TextBox txt = (TextBox)GridView1.Rows[nRow].Cells[nCol].Controls[0];
}
}
}
It looks like you are not creating the GridView after a postback, and the Save button is causing a postback. You need to dynamically create the GridView on each page load. Also, I have found this documentation on the ASP.NET page lifecycle helpful on numerous occasions.
In the documentation, you will see the slightly unintuitive reason why your code isn't working as you would like - btnSave_Command is not run until after a postback and Page_Load.

how to use updatepanel with AsyncRefresh event

I developing an asp.net web application.In that application i am using asyncRefresh event
for continuously updating the value.If i am using updatepanel the asyncRefresh event won't get the focus.Without updatepanel evet getting the focus.I want to use asynRefresh event with updatepanel.Any one Please help for this problem.
Thanks&Regards
Lijo Thomas
protected void Page_Load(object sender, EventArgs e)
{
object et = Request.Form["__EVENTTARGET"] as object;
if (et != null)
{
Control c = Page.FindControl(et.ToString());
if (c != null)
{
ScriptManager.GetCurrent(this).SetFocus(GetUniqueIdSmart(c));
}
}
}
protected static string GetUniqueIdSmart(Control control)
{
string id = control.UniqueID.Replace('$', '_');
string controlIDSuffix = "";
RadioButtonList rbl = control as RadioButtonList;
if (rbl != null)
{
controlIDSuffix = "_0";
int t = 0;
foreach (ListItem li in rbl.Items)
{
if (li.Selected)
{
controlIDSuffix = "_" + t.ToString();
break;
}
t++;
}
}
else if (control is CheckBoxList)
{
controlIDSuffix = "_0";
}
id += controlIDSuffix;
return id;
}

showing submit query after deleting the image from datalist

I have the following code and some images listed in a DataList:
protected void btnDel_Click(object sender, EventArgs e)
{
if (Id != 0)
{
BaseClass.Delete(Id1);
string path = Path.Combine(GetDirectory(Name), Name);
File.Delete(path);
}
}
public void BindImages()
{
path = BaseClass.GetAllImages(PId);
for (int i = 0; i < path.Count; i++)
{
ArrayList lst = path[i];
tb.Rows.Add(Convert.ToInt32(lst[0]), lst[1].ToString(),
lst[2].ToString(), i);
}
dlst1.DataSource = tb;
dlst1.DataBind();
}
When I click on the delete button for an image the image is removed but when I rebind the DataList the images are being duplicated.
I am binding the DataList in my PageLoad method.
You have to use IsPostBack boolean property in the Page_Load handler.
protected void page_load()
{
if(!IsPostBack)
{
BindImages();
}
}

Programmatically created CheckBoxList not firing when "unchecked"

I'm using ASP.NET and C#. I'm programmtically creating a checkboxlist. When I check an item, the SelectedIndexChanged event is firing. But, when I uncheck the item, the event is not fired. I'm binding the items on every postback and autopostback is set to true. Where am I going wrong? Here's the code -
page_load
{
var cblUser = new CheckBoxList();
cblUser.AutoPostBack = true;
cblUser.SelectedIndexChanged += cblUser_SelectedIndexChanged;
var list = DAL.GetUsers();
foreach (var user in list)
{
cblUser.Items.Add(new ListItem(user.Name, user.Id));
}
}
Thank you.
Update #1: Actual code -
public partial class CategoriesAccordion : UserControl
{
public List<Community> AllCommunities
{
get
{
if (Session["AllCommunities"] == null)
{
var db = new CommunityGuideDB();
Session["AllCommunities"] = db.Communities.OrderBy(x => x.Name).ToList();
}
return (List<Community>) Session["AllCommunities"];
}
}
public List<Category> Categories
{
get
{
if (Session["Categories"] == null)
{
var db = new CommunityGuideDB();
Session["Categories"] = db.Categories.OrderBy(x => x.Name).ToList();
}
return (List<Category>) Session["Categories"];
}
}
public event EventHandler Categories_Selected = delegate { };
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) Session.Remove("Categories");
LoadCategories();
}
private void LoadCategories()
{
foreach (var parent in Categories.Where(item => item.ParentId == null && item.ShowAsPivot == true).OrderBy(x => x.DisplayOrder))
{
var pane = new AccordionPane {ID = parent.Name};
pane.HeaderContainer.Controls.Add(new LiteralControl(parent.Name));
var cblValues = new CheckBoxList();
cblValues.AutoPostBack = true;
cblValues.SelectedIndexChanged += cblValues_SelectedIndexChanged;
foreach (var child in Categories.Where(child => child.ParentId == parent.Id))
{
var communityCount = child.CommunityCategory.Where(x => x.Categories_Id == child.Id).Count();
cblValues.Items.Add(new ListItem(string.Format("{0} ({1})", child.Name, communityCount), child.Id.ToString()));
}
pane.ContentContainer.Controls.Add(cblValues);
acdFilters.Panes.Add(pane);
}
}
protected void cblValues_SelectedIndexChanged(object sender, EventArgs e)
{
var cblValues = ((CheckBoxList) sender);
var selectedCategories = (from ListItem item in cblValues.Items where item.Selected select Categories.Find(c => c.Id == new Guid(item.Value))).ToList();
Categories_Selected(this, new CommandEventArgs("SelectedCategories", selectedCategories));
}
}
I don't get how do you add the control to a container?
I've just checked and I've got the event fired both on checking & unchecking.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CheckBoxList cbList = new CheckBoxList();
cbList.AutoPostBack = true;
for (int i = 0; i < 10; i++)
cbList.Items.Add(i.ToString());
cbList.SelectedIndexChanged += new EventHandler(cbList_SelectedIndexChanged);
form1.Controls.Add(cbList);
}
void cbList_SelectedIndexChanged(object sender, EventArgs e)
{
//fires both on check & uncheck of an item
}
}
The SelectedIndexChanged event you are bounding is fired upon selecting different item on your list, not when you check an item. CheckBoxList does not have an event for changing the status of its items.
Try a to use list control like Repeater ...

Textbox value null when trying to access it

namespace Dynamic_Controls.Dropdowndynamic
{
public partial class DropdowndynamicUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (ControlCount != 0)
{
Recreatecontrols();
}
}
private void Recreatecontrols()
{
// createtextboxes(ControlCount);
createtextboxes(2);
}
protected void createtextboxes(int ControlCount)
{
DynPanel.Visible = true;
for (int i = 0; i <= ControlCount; i++)
{
TextBox tb = new TextBox();
tb.Width = 150;
tb.Height = 18;
tb.TextMode = TextBoxMode.SingleLine;
tb.ID = "TextBoxID" + this.DynPanel.Controls.Count;
tb.Text = "EnterTitle" + this.DynPanel.Controls.Count;
tb.Load+=new EventHandler(tb_Load);
tb.Visible = true;
tb.EnableViewState = true;
DynPanel.Controls.Add(tb);
DynPanel.Controls.Add(new LiteralControl("<br/>"));
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Int32 newControlCount = Int32.Parse(DropDownList1.SelectedValue);
//createtextboxes(newControlCount);
//ControlCount+=newControlCount;
createtextboxes(2);
}
protected void Button1_Click(object sender, EventArgs e)
{
readtextboxes();
}
public void readtextboxes()
{
string x = string.Empty;
for (int a = 0; a < DynPanel.Controls.Count; a++)
{
foreach (Control ctrl in DynPanel.Controls)
{
if (ctrl is TextBox)
{
x = ((TextBox)ctrl).Text;
}
x+=x+("\n");
}
Result.Text = x;
}
}
private Int32 ControlCount
{
get
{
if (ViewState["ControlCount"] == null)
{
ViewState["ControlCount"] = 0;
}
return (Int32)ViewState["ControlCount"];
}
set
{
// ViewState["ControlCount"] = value;
ViewState["ControlCount"] = 2;
}
}
private void tb_Load(object sender, EventArgs e)
{
LblInfo.Text = ((TextBox)sender).ID + "entered";
}
}
}
Are you adding these controls dynamically in Page_Load (by, I'm assuming, calling your AddRequiredControl() method)? If so, is it wrapped in a conditional which checks for IsPostBack? The likely culprit is that you're destructively re-populating the page with controls before you get to the button click handler, so all the controls would be present but empty (as in an initial load of the page).
Also, just a note, if you're storing each control in _txt in your loop, why not refer to that variable instead of re-casting on each line. The code in your loop seems to be doing a lot of work for little return.
You need to recreate any dynamically created controls on or before Page_Load or they won't contain postback data.
I'm not entirely clear what happens on DropdownList changed - are you trying to preserve anything that has been entered already based on the textboxes previously generated?
In any event (no pun intended) you need to recreate exactly the same textboxes in or before Page_Load that were there present on the postback, or there won't be data.
A typical way to do this is save something in ViewState that your code can use to figure out what to recreate - e.g. the previous value of the DropDownList. Override LoadViewState and call the creation code there in order to capture the needed value, create the textboxes, then in the DropDownList change event, remove any controls that may have been created in LoadViewState (after of course dealing with their data) and recreate them based on the new value.
edit - i can't figure out how your code works now, you have AddRequiredControl with parameters but you call it with none. Let's assume you have a function AddRequiredControls that creates all textboxes for a given DropDownList1 value, and has this signature:
void AddRequiredControls(int index)
Let's also assume you have a PlaceHolder called ControlsPlaceholder that will contain the textboxes. Here's some pseudocode:
override void LoadViewState(..) {
base.LoadViewState(..);
if (ViewState["oldDropDownIndex"]!=null) {
AddRequiredControls((int)ViewState["oldDropDownIndex"]);
}
}
override OnLoad(EventArgs e)
{
// process data from textboxes
}
void DropDownList1_SelectedIndexChanged(..) {
ControlsPlaceholder.Controls.Clear();
AddRequiredControls(DropDownList1.SelectedIndex);
ViewState["oldDropDownIndex"]=DropDownList1.SelectedIndex;
}

Resources