CheckBox CheckedChanged event added from code behind - c#

I have a couple of checkboxes that I add from my code behind, but I can't get the CheckedChanged event to fire.
This code is being called on page load:
CheckBox cb = new CheckBox();
cb.AutoPostBack = true;
cb.CheckedChanged += cb_CheckedChanged;
cb.ToolTip = dr["Id"].ToString();
cb.ID = Guid.NewGuid().ToString();
Label lbl = new Label();
lbl.Text = dr["Id"].ToString();
lbl.AssociatedControlID = cb.ID;
dvCheckboxes.Controls.Add(cb);
dvCheckboxes.Controls.Add(lbl);
dvCheckboxes.Controls.Add(new LiteralControl("<br />"));
And the event:
void cb_CheckedChanged(object sender, EventArgs e)
{
System.Diagnostics.Debug.Write(((CheckBox)sender).ToolTip);
}
I've put a breakpoint in the CheckedChanged event, but it's never reached.
What I've tried:
putting the code in if(!IsPostBack), but no difference.
cb.CheckedChanged += new EventHandler(cb_CheckedChanged);
cb.CheckedChanged += new EventHandler(this.cb_CheckedChanged);
cb.ViewStateMode = System.Web.UI.ViewStateMode.Enabled;
tried putting the code in Page_Init instead of Page_Load

#johan, Try this. Create the checkboxes in PageInit instead of Pageload. Also provide an appropriate id for the Checkbox.
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_init(object sender, EventArgs e)
{
CheckBox cb = new CheckBox();
cb.AutoPostBack = true;
cb.CheckedChanged +=cb_CheckedChanged;
cb.CausesValidation = false;
cb.ToolTip = "Hello";
cb.ID = "chk_test";
Label lbl = new Label();
lbl.Text = "test";
lbl.AssociatedControlID = cb.ID;
dvCheckboxes.Controls.Add(cb);
dvCheckboxes.Controls.Add(lbl);
dvCheckboxes.Controls.Add(new LiteralControl("<br />"));
}
protected void cb_CheckedChanged(object sender, EventArgs e)
{
System.Diagnostics.Debug.Write(((CheckBox)sender).ToolTip);
}

Add event in your site code - not code behind:
<asp:CheckBox ID="cb" Runat="server" CheckedChanged="cb_CheckedChanged" />
Hope this helps.

Related

Pass variable with onclick method in asp.net

I create a button dynamically and I want when my button click and onclick event fired, a variable pass with this event.
Button btn = new Button();
btn.Click += new EventHandler(Button_Click);
//btn.Click += new EventHandler(Button_Click(32)); <-- I want something like this
divUserUploadedList.Controls.Add(btn);
And this is Onclick event:
protected void Button_Click(object sender, EventArgs e)
{
//I want to access that value here
}
You can do this by using CommandArgument property
protected void Page_Load(object sender, EventArgs e)
{
Button btn = new Button();
btn.Click += btn_Click;
btn.CommandArgument = "12"; //<-- you can pass argument like this
divUserUploadedList.Controls.Add(btn);
}
void btn_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
string value = btn.CommandArgument;
}
What you are looking for is probably the CommandArgument property.
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.commandargument%28v=vs.110%29.aspx

dynamic linkbutton not calling command when clicked

New to dynamic controls, but until now I have been creating them successfully in a
template field in my gridview, recently switched from a hyperlink to a link button
and had to make some changes but still not working
In my page I have the following code (abridged to salient parts)
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
...
...
TemplateField tf = new TemplateField();
tf.HeaderText = "Action";
tf.ItemTemplate = new AssignPage.MyTemplate(..., mylb);
GridView1.Columns.Add(tf);
protected void Page_PreInit(object sender, EventArgs e)
{
LinkButton lb = new LinkButton();
lb.Text = "AssignAll";
lb.Command += new CommandEventHandler(AssignAll_Click);
lb.CommandName = "XXX";
this.mylb = lb;
protected void AssignAll_Click(object sender, CommandEventArgs e)
{
string[] arg = new string[2]; // BREAK POINT HERE
arg = e.CommandArgument.ToString().Split(';');
...
...
Response.Redirect("BaseAndRepeats.aspx?id=" + r.Event.ID);
In the template class I have I have
LinkButton lb;
public MyTemplate(..., LinkButton _lb)
{
...
lb = _lb;
...
public void InstantiateIn(System.Web.UI.Control container)
{
...
...
// various conditional statements
lb.CommandArgument = mylist[rowCount].ReqtID.ToString() + ";" + mylist[rowCount].RotaUser;
container.Controls.Add(lb);
...
The break point in the handler is never reached
I thought I was creating the linkbutton in the right place
the linkbutton appears in the grid quite happily
when I click on the linkbutton there is a call
to Page_PreInit and to Page_Load and as I expected
it is a postback.
But AssignAll_Click is never called.
In the browser footer it shows "javascript: __dooPsotabck(..." when you hover
over the buttonlink
I believe the problem is this line:
lb.Command += new CommandEventHandler(AssignAll_Click);
Change it to:
lb.Command += AssignAll_Click;
Edit:
Also you want to move it from Page_PreInit to Page_Init but you may find more success with it in Page_Load (outside the IsPostBack). Here's an example that works for me:
On the ASPX page:
<asp:Panel ID="TestPanel" runat="server" />
Codebehind:
protected void Page_Init(object sender, EventArgs e)
{
//Init used because TestPanel doesn't exist yet
CreateTestButton();
}
private void CreateTestButton()
{
var lb = new LinkButton();
lb.Text = "hello";
lb.Command += lb_Command;
TestPanel.Controls.Add(lb);
}
void lb_Command(object sender, CommandEventArgs e)
{
throw new NotImplementedException();
}
Going over your code it looks like your adding another column into your GridView and creating a button inside that column for each row - but you've got the column being added on Page_Load and the button being created and bound to it before in Page_PreInit

how to create button click event in gridview RowDataBound c# asp.net

i am trying to create button and click event in rowdatabound in gridview c# asp.net like below code
protected void btnerror_Click(object sender, EventArgs e)
{
GridView gv = new GridView();
gv.RowDataBound += gv_RowDataBound;
gv.RowCommand += gv_RowCommand;
gv.RowCreated += gv_RowCreated;
gv.EnableViewState = true;
gv.DataSource = _dt;
gv.DataBind();
}
void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton btnUpdate = new ImageButton();
btnUpdate.ID = "btnupdate";
btnUpdate.ImageUrl = "~/SmartAdmin/Images/update.png";
btnUpdate.ToolTip = "Click Update";
btnUpdate.CommandName = "update";
btnUpdate.Click += btnUpdate_Click;
TableCell tc = new TableCell();
tc.Controls.Add(btnUpdate);
e.Row.Cells.Add(tc);
}
}
void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "update")
{
}
}
while click that button click event is not firing ...
where i made error...
thank u.......
Do you really want to create the GridView manually? I strongly doubt that. Instead add it declaratively to the aspx-page and make it visible in btnerror_Click.
Don't create the control dynamically and register the event handler in RowDataBound but in RowCreated which is triggered on every postback (as opposed to RowDataBound):
void gv_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton btnUpdate = new ImageButton();
btnUpdate.Click += btnUpdate_Click;
TableCell tc = new TableCell();
tc.Controls.Add(btnUpdate);
e.Row.Cells.Add(tc);
}
}
void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton btnUpdate = (ImageButton)e.Row.FindControls("btnupdate")
btnUpdate.ID = "btnupdate";
btnUpdate.ImageUrl = "~/SmartAdmin/Images/update.png";
btnUpdate.ToolTip = "Click Update";
btnUpdate.CommandName = "update";
}
}
So create it in RowCreated but initialize it in RowDataBound where you can also access the datasource (if required).
Also note that you should DataBind the GridView only if(!IsPostBack) not on every postback (if that's the case). So add this check where you assign the datasource.
You need to add function for click event
btnUpdate.Click += btnUpdate_Click;
protected void btnUpdate_Click(object sender, EventArgs e)
{
}

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!

EventHandler is not working for dynamic control

I have referred Error with the event handlers of dynamic linkbutton . It says to add event handlers in Page_Init or Page_Load. I tired following code. But the event handler is not fired when I click on the dynamic added link buttons. What need to be corrected here?
Note: The dynamic LinkButton controls are added in the click event of a button after some business validations (the business code is not given for brevity)
Markup
<form id="form1" runat="server">
<div>
<asp:LinkButton ID="lnkTest" runat="server" OnClick="LinkButton_Click">Static LinkButton</asp:LinkButton>
<br />
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="btnAdd_Click" />
<br />
<asp:PlaceHolder ID="plhDynamicLinks" runat="server"></asp:PlaceHolder>
</div>
</form>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
foreach (Control ctrl in plhDynamicLinks.Controls)
{
LinkButton dynamicButton = (LinkButton)ctrl;
dynamicButton.Click += new EventHandler(LinkButton_Click);
}
if (Page.IsPostBack)
{
}
}
protected void Page_Init(object sender, EventArgs e)
{
int x = 0;
foreach (Control ctrl in plhDynamicLinks.Controls)
{
LinkButton dynamicButton = (LinkButton)ctrl;
dynamicButton.Click += new EventHandler(LinkButton_Click);
}
}
protected void LinkButton_Click(object sender, EventArgs e)
{
LinkButton clickedControl = (LinkButton)sender;
Response.Write(clickedControl.ID +" Link Button Clicked");
}
protected void btnAdd_Click(object sender, EventArgs e)
{
plhDynamicLinks.Controls.Clear();
LinkButton button1 = new LinkButton();
button1.ID = "D1";
button1.Text = "1";
plhDynamicLinks.Controls.Add(button1);
LinkButton button2 = new LinkButton();
button2.ID = "D2";
button2.Text = "2";
plhDynamicLinks.Controls.Add(button2);
}
It is mandatory to register all the required dynamic controls’ event handlers in the Page_Load/ Page_Init itself. One working example can be seen at Dynamic Control’s Event Handler’s Working
MarkUp
<form id="form1" runat="server">
<div>
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="btnAdd_Click" />
<br />
<asp:PlaceHolder ID="plhDynamicLinks" runat="server"></asp:PlaceHolder>
</div>
</form>
CODE BEHIND
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
LinkButton lnk1 = new LinkButton();
lnk1.ID = "D1";
lnk1.Text = "A";
//Event handler must be registered in the Page_Load/Page_Init
lnk1.Click += new EventHandler(LinkButton_Click);
plhDynamicLinks.Controls.Add(lnk1);
LinkButton lnk2 = new LinkButton();
lnk2.ID = "D2";
lnk2.Text = "B";
lnk2.Click += new EventHandler(LinkButton_Click);
plhDynamicLinks.Controls.Add(lnk2);
LinkButton lnk3 = new LinkButton();
lnk3.ID = "D3";
lnk3.Text = "C";
lnk3.Click += new EventHandler(LinkButton_Click);
plhDynamicLinks.Controls.Add(lnk3);
LinkButton lnk4 = new LinkButton();
lnk4.ID = "D4";
lnk4.Text = "D";
lnk4.Click += new EventHandler(LinkButton_Click);
plhDynamicLinks.Controls.Add(lnk4);
}
}
protected void LinkButton_Click(object sender, EventArgs e)
{
PopulateLinksBasedOnCriteria();
LinkButton clickedControl = (LinkButton)sender;
Response.Write(DateTime.Now.ToString()+"___"+ clickedControl.ID + " Link Button Clicked" );
}
protected void btnAdd_Click(object sender, EventArgs e)
{
PopulateLinksBasedOnCriteria();
}
private void PopulateLinksBasedOnCriteria()
{
plhDynamicLinks.Controls.Clear();
if (DateTime.Now.Second < 30)
{
LinkButton linkButton1 = new LinkButton();
linkButton1.ID = "D1";
linkButton1.Text = "1";
plhDynamicLinks.Controls.Add(linkButton1);
LinkButton linkButton2 = new LinkButton();
linkButton2.ID = "D2";
linkButton2.Text = "2";
plhDynamicLinks.Controls.Add(linkButton2);
}
else
{
LinkButton linkButton3 = new LinkButton();
linkButton3.ID = "D3";
linkButton3.Text = "3";
plhDynamicLinks.Controls.Add(linkButton3);
LinkButton linkButton4 = new LinkButton();
linkButton4.ID = "D4";
linkButton4.Text = "4";
plhDynamicLinks.Controls.Add(linkButton4);
}
}
Dynamic controls must be re-created on every postback, this Article is a good link about how to persist dynamic controls and their state.
Add javascript onClick attribute to the dymanic control and set hidden field values which is required for the control event. Onclick of the dymanic grid, the will postback and will get the hidden field value. In page load call a method to do the job if the hidden field has value and make it null after doing the job.

Categories

Resources