Dynamically Creating Multiple controls which use a common handler - c#

This first section is in a loop. It creates the dynamic check boxes with no problems.
// All I am doing here is incrementing our session counter
int id = Convert.ToInt32(Session["id"]);
id++;
Session["id"] = id;
// Now I create my checkbox
chkDynamic = new CheckBox();
chkDynamic.Text = "hey";
string chk = "chk" + id.ToString();
chkDynamic.ID = chk;
chkDynamic.CheckedChanged += new EventHandler(this.chkDynamic_CheckedChanged);
Panel1.Controls.Add(chkDynamic);
My event handler is not wiring up for this. Strangly if I hard code the ID it does work, but only for one iteration of the loop because if we hard coded the IDs then we would run into 'multiple id errors'
protected void chkDynamic_CheckedChanged(object sender, EventArgs e)
{
if (chkDynamic.Checked)
Response.Write( "you checked the checkbox");
else if (!chkDynamic.Checked)
Response.Write("checkbox is not checked");
}

You need to check sender in your event handler to know which checkbox sent the event:
protected void chkDynamic_CheckedChanged(object sender, EventArgs e)
{
if (((CheckBox)sender).Checked)
Response.Write( "you checked the checkbox");
else
Response.Write("checkbox is not checked");
}

Related

c# add button event programmatically

Trying to add buttons programmatically to a webform.
Some work - others don't.
In the code below I add btnY and btnX in the Page_Load.
These both work - they show on the page and fire the event
and the code in the event handler works....
In the page load I also run bindData which gets a DataTable
and uses the data to create controls.
in the example I am only creating Button.
These buttons will appear on the page correctly but when clicked
they only do a postback ..
the code in the event handler doesn't work - does it get called?
The event handler is the same for all the buttons.
Any ideas why or how I can make it work?
protected void Page_Load(object sender, EventArgs e)
{
PlaceHolder1.Controls.Add(btn("btnY", "Y"));
Pages P = new Pages();
bindData(P.DT);
PlaceHolder1.Controls.Add(btn("btnX", "X"));
}
Button btn(string id, string text)
{
Button btn1 = new Button();
btn1.ID = id;
btn1.Text = text;
btn1.Click += new System.EventHandler(this.btn_click);
return btn1;
}
protected void bindData(DataTable dt)
{
foreach (DataRow row in dt.Rows)
{
render(Convert.ToInt32(row["PageKey"]));
}
}
protected void render(int pageKey)
{
PlaceHolder1.Controls.Add(btn("btn_" + pageKey.ToString(), "Edit"));
}
protected void btn_click(object sender, EventArgs e)
{
Button btn = (Button)sender;
string id = btn.ID;
Pages P = new Pages();
bindData(P.DT);
lt.Text = "ID=" + id;
}
Never mind .. figured it out .. example above should work, my actual code had a if (!Page.PostBack) that caused the problem

Access dynamically created checkbox values in c#

I have added a CheckBox dynamically in asp.net
CheckBox cb = new CheckBox();
cb.Text = "text";
cb.ID = "1";
I can access this CheckBox via c# in pageLoad itself, just after declaring above codes.
But when I try to access this values after a button click I'm getting null values.
CheckBox cb1 = (CheckBox)ph.FindControl("1");
Response.Write(cb1.Text);
ph.Controls.Add(cb);
(ph is a placeholder)
Can any one tell me whats wrong here?
You need to recreate the checkbox everytime the page posts back, in Page_Load event, as it's dynamically added to page.
Then you can access the checkbox later in button click event.
// Hi here is updated sample code...
Source
<body>
<form id="frmDynamicControl" runat="server">
<div>
<asp:Button ID="btnGetCheckBoxValue" Text="Get Checkbox Value" runat="server"
onclick="btnGetCheckBoxValue_Click" />
</div>
</form>
</body>
code behind
protected void Page_Load(object sender, EventArgs e)
{
CheckBox cb = new CheckBox();
cb.Text = "text";
cb.ID = "1";
frmDynamicControl.Controls.Add(cb);
}
protected void btnGetCheckBoxValue_Click(object sender, EventArgs e)
{
CheckBox cb1 = (CheckBox)Page.FindControl("1");
// Use checkbox here...
Response.Write(cb1.Text + ": " + cb1.Checked.ToString());
}
After you click the button it will post back the page which will refresh the state. If you want the values to be persistent then you'll need to have them backed inside the ViewState or similar.
private bool CheckBox1Checked
{
get { return (ViewState["CheckBox1Checked"] as bool) ?? false; }
set { ViewState["CheckBox1Checked"] = value; }
}
void Page_load(object sender, EventArgs e)
{
CheckBox cb = new CheckBox();
cb.Text = "text";
cb.ID = "1";
cb.Checked = CheckBox1Checked;
cb.OnCheckedChanged += CheckBox1OnChecked;
// Add cb to control etc..
}
void CheckBox1OnChecked(object sender, EventArgs e)
{
var cb = (CheckBox)sender;
CheckBox1Checked = cb.Checked;
}
I'm a bit later here, but i just do:
try{
if(Request.Form[checkboxId].ToString()=="on")
{
//do whatever
}
}catch{}
If a checkbox is not checked, it will not appear in the Form request hence the try catch block. Its quick, simple, reusable, robust and most important, it just works!

How to handle events of dynamically added checkbox on windows form

I am able to add checkbox dynamically on windows form and add data value to its text property. On click of any checkbox I have run a procedure which will make certain other checkbox disabled.
I am not able to find eventhandler for it.
Have you tried this
CheckBox check = new CheckBox();
check.Checked = true;
check.AccessibleName = checkName;
check.Location = new System.Drawing.Point(340, 40);
check.CheckedChanged +=new EventHandler(check_CheckedChanged);
this.Controls.Add(check);
private void custom_event_handler(object sender, EventArgs e)
{
....
}
and then you add checbox like this:
CheckBox cb = new CheckBox();
cb.CheckedChanged += new EventHandler(custom_event_hahndler);
if the name of the dynamically added checkbox is c, the answer is as below:
c.CheckedChanged += c_CheckedChanged;
and c_CheckedChanged is as below:
private void c_CheckedChanged(object sender, EventArgs e)
{
if (((CheckBox)sender).Checked)
{
((CheckBox)(this.Controls.Find("c1", false))[0]).Enabled = false;
}
}
which c1 is the name of the checkbox you want to disable.
Add event handler when you create a checkbox programmatically. And its handler you can do your code logic.
CheckBox dynamicCheckBox = new CheckBox();
dynamicCheckBox.CheckedChanged +=new EventHandler(dynamicCheckBox_CheckedChanged);
private void dynamicCheckBox_CheckedChanged(object sender, EventArgs e)
{
// Your code
}

change controls based on database value

Problem:
I have a value in a database table. This value can either contain a number, or null. If its null I would like to show one group of controls. If its not null I would like to show another group of controls.
Previous Attempts:
I have tried creating the controls in the code behind depending on the value of the database. This worked. However, on postback I get a null reference exception. The control doesn't exist on postback because the page is stateless. I'm building the controls in the page_load handler (depending on the value of the table column). Since I'm creating the controls in the page_load shouldn't they exist on postback?
I also tried recreating the controls in the event handler for the button. I get a "theres already a control with this id" exception (presumably because I already created it in the page_load method).
I read a few posts about how I have to store the controls in a session. This seems like more work than it should be.
Questions:
Am I going about this the wrong way? This seems like it should have been simple but is turning into a mess.
If this is the correct way to do this, Where do I add the session information? I've been reading other posts and I'm kind of lost
Code:
int bookId;
string empName;
protected void Page_Load(object sender, EventArgs e)
{
if(int.TryParse(Request.QueryString["id"], out bookId))
{
//This is where the value in the database comes into play. If its null Book.GetCopyOwner
// returns a string with length 0
empName = Book.GetCopyOwner(bookId, Request.QueryString["owner"]);
if (empName.Trim().Length > 0)
{
CreateReturnControls();
}
else
{
CreateCheckoutControls();
}
}
}
protected void ReturnButton_Click(object sender, EventArgs e)
{
}
protected void CheckOut_Click(object sender, EventArgs e)
{
int bookId;
if (int.TryParse(Request.QueryString["id"], out bookId))
{
TextBox userId = (TextBox)this.Page.FindControl("UserId");
//WHEN I TRY TO USE THE TEXTBOX userId HERE, I GET NULL REFERENCE EXCEPTION
BookCopyStatusNode.Controls.Clear();
CreateReturnControls();
}
}
protected void CopyUpdate_Click(object sender, EventArgs e)
{
}
private void CreateCheckoutControls()
{
TextBox userId = new TextBox();
//userId.Text = "Enter Employee Number";
//userId.Attributes.Add("onclick", "this.value=''; this.onclick=null");
userId.ID = "UserId";
Button checkOut = new Button();
checkOut.Text = "Check Out";
checkOut.Click += new EventHandler(CheckOut_Click);
TableCell firstCell = new TableCell();
firstCell.Controls.Add(userId);
TableCell secondCell = new TableCell();
secondCell.Controls.Add(checkOut);
BookCopyStatusNode.Controls.Add(firstCell);
BookCopyStatusNode.Controls.Add(secondCell);
}
private void CreateReturnControls()
{
Label userMessage = new Label();
userMessage.Text = empName + " has this book checked out.";
Button returnButton = new Button();
returnButton.Text = "Return it";
returnButton.Click += new EventHandler(ReturnButton_Click);
TableCell firstCell = new TableCell();
firstCell.Controls.Add(userMessage);
TableCell secondCell = new TableCell();
secondCell.Controls.Add(returnButton);
BookCopyStatusNode.Controls.Add(firstCell);
BookCopyStatusNode.Controls.Add(secondCell);
}
It looks like you're creating a static set of controls based on the database value. Why not simply have 2 Panels that contain the controls you want and simply set their visibility to true or false:
if (!Page.IsPostBack)
{
if (int.TryParse(Request.QueryString["id"], out bookId))
{
empName = Book.GetCopyOwner(bookId, Request.QueryString["owner"]);
var display = (empName.Trim().Length > 0);
panelReturnControls.Visible = display;
panelCheckoutControls.Visible = !display;
}
}

Checkbox added programmatically not found

I add checkboxes that way:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CheckBox FieldCh = new CheckBox();
FieldCh.ID = "Field_" + Field.Id;
Panel1.Controls.Add(FieldCh);
}
}
but when I try to get this checkboxes from form:
foreach (Control item in FindControl("FieldForm").Controls)
{
if (item is Panel)
{
foreach (Control checkbox in item.Controls)
i cannot find this checkboxes :/ This could be problem with runat=server? I not find this property in Checkbox ..
If you want to find this CheckBox after PostBack (what I've assumed), you need to recreate it. Try to create this CheckBox out of if(!PostBack) clause (so it's recreated after postback too):
protected void Page_Load(object sender, EventArgs e)
{
CheckBox FieldCh = new CheckBox();
FieldCh.ID = "Field_" + Field.Id;
Panel1.Controls.Add(FieldCh);
if (!IsPostBack)
{
// ....
}
}
You must have to use Page_Load even to add controls dynamically.
protected void page_load()
{
CheckBox FieldCh = new CheckBox();
FieldCh.ID = "Field_" + Field.Id;
Panel1.Controls.Add(FieldCh);
}
you may simply use a better method of finding your control
just use this
CheckBox chkBox = this.form1.FindControl("YourControlId") as CheckBox;

Categories

Resources