Problem in event generation of dynamically generated CheckBox - c#

I have a datagrid with dynamically generated checkbox column..I am not able to
generate the checkedChanged event for the checkbox..
Here is my code:
public class ItemTemplate : ITemplate
{
//Instantiates the checkbox
void ITemplate.InstantiateIn(Control container)
{
CheckBox box = new CheckBox();
box.CheckedChanged += new EventHandler(this.OnCheckChanged);
box.AutoPostBack = true;
box.EnableViewState = true;
box.Text = text;
box.ID = id;
container.Controls.Add(box);
}
public event EventHandler CheckedChanged;
private void OnCheckChanged(object sender, EventArgs e)
{
if (CheckedChanged != null)
{
CheckedChanged(sender, e);
}
}
}
and Here is the event
private void OnCheckChanged(object sender, EventArgs e)
{
}
Thanks In advance

Typically we've used the "CommandName" property on the control. This will pass through to the RowCommand event of the GridView. You can then inspect the value of CommandName and act accordingly.

since you add the control dynamically, you also need to add it to the viewState (see overrides for LoadViewState and SaveViewState).
when you do postback, the page has no information about the checkbox you've added and that's why you don't get any event.
please check this article: http://weblogs.asp.net/infinitiesloop/archive/2006/08/25/TRULY-Understanding-Dynamic-Controls-_2800_Part-1_2900_.aspx
it describes those issues very well.

Related

Detecting change source (user or program) in radio buttons

I'm trying to set a flag saying whether the last change on the Checked property was caused by the user or the program.
I'm using a custom RadioButton:
public class MyRadioButton : RadioButton
{
ValueChanger valueChanger = ValueChanger.Program;
public MyRadioButton()
{
this.Click += OnButtonClickedByUser;
this.CheckedChanged += OnCheckChange;
}
public void setChecked(bool val)
{
this.valueChanger = ValueChanger.Program;
this.Checked = val;
}
void OnButtonClickedByUser(Object sender, EventArgs e)
{
this.valueChanger = ValueChanger.User;
}
void OnCheckChange(Object sender, EventArgs e)
{
// do stuff depending on 'this.valueChanger'
}
enum ValueChanger
{
User,
Program
};
}
I call setChecked whenever the value was changed because of a message received from a serial connection, and I expect OnButtonClickedByUser to be called by the Click event whenever the value is changed through the UI.
My problem is that the CheckedChanged event fires before the Click event, which makes OnCheckChange unreliable.
Is there any way to fix that ?
User can change the value of the RadioButton by click on the control or by moving the focus to the control (arrow key, tab, mnemonic key combination).
Both OnEnter and ProcessMnemonic try to call PerformClick which calls OnClick which is responsible to checking the control. So you can override OnClick method:
protected override void OnClick(EventArgs e)
{
// Here CheckedChanged event has not been raised yet
base.OnClick(e);
}
To find out more about how RadioButton works internally, take a look at its source code.

C# auto update chart when textbox is changed

I have a windows form consisting of a series of textboxes and a button.
The user needs to input some data into the textboxes and then the code uses these inputs to do some calculation.
The user then clicks the button and a chart is generated showing the results of the calculations.
The chart is done using R which is connected to C# via R.Net.
The question is: how can I make the chart to update dynamically as soon as the user changes some input in one of the textboxes (so without first clicking the button that generates the graph)?
I thought that I would need some loop that constantly checks if any of the textboxes has been changed but I cannot make this work:
foreach (Control subctrl in this.Controls)
{
if (subctrl is TextBox)
{
((TextBox)subctrl).TextChanged += new EventHandler();
}
}
TextChanged should trigger the buttonClick event so that the reated code that generates the graph is executed.
What is a good approach for this problem? Thanks.
<<<< EDIT >>>>>
Here is my code for the form:
public partial class myInputForm : Form
{
public myInputForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// call methods to run calculations using new inputs from textboxes
plotGraph(); // plot the new results
}
}
I would like to keep the calculation methods and the plot function plotGraph() inside the button1_Click event.
Trying to adopt Refus L's suggestion, I am adding the following to the partial class myInputForm above:
private void TextBox_TextChanged(object sender, EventArgs e)
{
TextBox textbox = sender as TextBox;
if (IsValidText(textBox.Text))
{
textbox.TextChanged += new System.EventHandler(this.button1_Click);
}
else
{
DisplayBadTextWarning(textBox.Text);
}
}
private void myInputForm_Load(object sender, EventArgs e)
{
foreach (Control control in this.Controls)
{
var textBox = control as TextBox;
if (textBox != null)
{
textBox.TextChanged += TextBox_TextChanged;
}
}
}
But this still doesn't work. If I insert the following:
this.myFirstBox.textChanged += new System.EventHandler(this.button1_Click);
directly in the code that is automatically generated by the form designer it works and a change in the textbox myFirstBox triggers the button click and thus the plot.
But I would need to write a line for each textbox cause the foreach doesn't work there.
Can you please explain how to set this up to work in my form? Thanks.
You can just specify an existing method that you want to handle the event. Ideally you'd have a separate method that updates the chart, which can be called from anywhere. Then you can call it from your TextChanged or Button_Click event, but these two control events are not tied together (in TextChanged you may want to do some validation on the text first). Also, if you want to update the chart from some other place, you have an independent method you can call that will do it.
For example, if you have this method to update the chart:
private void UpdateChart()
{
// Do something here to update the chart
}
You can call it from your event handlers:
private void button1_Click(object sender, EventArgs e)
{
UpdateChart();
}
private void TextBox_TextChanged(object sender, EventArgs e)
{
// You might have some data validation on the TextBox.Text here,
// which you wouldn't need in the Button_Click event
TextBox textbox = sender as TextBox;
if (IsValidText(textBox.Text))
{
// Now update the chart
UpdateChart();
}
else
{
DisplayBadTextWarning(textBox.Text);
}
}
Then you can hook up all your TextBox.TextChanged events to the custom handler above:
private void Form1_Load(object sender, EventArgs e)
{
// Dynamically hook up all the TextBox TextChanged events to your custom method
foreach (Control control in this.Controls)
{
var textBox = control as TextBox;
if (textBox != null)
{
textBox.TextChanged += TextBox_TextChanged;
}
}
}

Radio button event executing two times

In my project, There are two radioButtons. To which I have given same CheckedChanged event by doing
something like this:
DoctorRadioButton.CheckedChanged += new EventHandler(RadioButton_CheckedChanged);
PatientRadioButton.CheckedChanged += new EventHandler(RadioButton_CheckedChanged);
I kept both the RadioButtons in a Panel to make them one true while other one is false.
Now the problem is that I am implementing a very big code in the RadioButton_CheckedChanged event.
Whenever the user is changing the state of any of the two RadioButtons, the event is raising two times.
After so many hours I got the answer, the event is raising two times because both the RadioButton states are being changed(Hence, the event will be raised two times). To solve this problem I am trying to unhook the event temporarily something like this:
RadioButton_CheckedChanged Event: (Not Working)
if (DoctorRadioButton.Checked)
{
PatientRadioButton.CheckedChanged -= RadioButton_CheckedChanged; //Un
//
//My functions
//
PatientRadioButton.CheckedChanged += new EventHandler(RadioButton_CheckedChanged);
}
else
{
DoctorRadioButton.CheckedChanged -= RadioButton_CheckedChanged;
//
//My functions
//
DoctorRadioButton.CheckedChanged += new EventHandler(RadioButton_CheckedChanged);
}
Eventhough the event is executing two times. I know I am doing something wrong in Hooking and Unhooking. Please Help.
You can check the sender RadioButton and place your code accordingly like this -
void RadioButton_CheckedChanged(object sender, EventArgs e)
{
RadioButton senderRadioButton = sender as RadioButton;
if (senderRadioButton.Equals(DoctorRadioButton))
// OR senderRadioButton.Name == "DoctorRadioButton"
{
// Place your code here for DoctorRadioButton.
}
else
{
// Place your code here for PatientRadioButton.
}
}
Update
If you can't use two different handlers for both radioButtons and want to execute code only in case checkbox is checked you can do this -
void RadioButton_CheckedChanged(object sender, EventArgs e)
{
RadioButton senderRadioButton = sender as RadioButton;
if (senderRadioButton.IsChecked)
{
// Place your code here for check event.
}
}
For an extremely simple (albeit crude) solution would be to not hook both the radio buttons, and hook only one of them to the handler: since checking one radio unchecks the other one, it would work as intended.
A more complicated way would be to use a backing property, like this:
class myForm
{
private bool radioStatus = false; // depends on the default status of the radios
private bool RadioStatus
{
get{return radioStatus;} set {radioStatus = value; Checked_Changed();}
}
public myForm()
{
// Lambdas as handlers to keep code short.
DoctorRadioButton.CheckedChanged += (s,args)=>
{ if((s as RadioButton).Checked) RadioStatus = true; };
PatientRadioButton.CheckedChanged += (s,args)=>
{ if((s as RadioButton).Checked) RadioStatus = false; };
}
void Checked_Changed()
{
if (RadioStatus) // = true --> DoctorRadioButton was checked
{
//code
}
else // = false --> PatientRadioButton was checked
{
//other code
}
}
}
This approach has the advantage of allowing you to abstract from the UI a bit.
Put both radio buttons in the same panel or groupbox and automatically they will be grouped so that only one can be selected at a time.
Its a late solution but i found there is no correct answer for your question so i am posting it may be it works For You
Create Click Event for both radio button and simple put your code beacuse on every click your radio button got checked and your code executes :):):)
private void DoctorRadioButtons_Click(object sender, EventArgs e)
{
//Your code on Doctor Radio Button
}
private void PatientRadioButton_Click(object sender, EventArgs e)
{
// Your code on Patient Radio Button
}

Add Dynamic CheckBox Handle CheckedChanged Event ASP.NET

I would like to know why the event is not firing & how to find which checkbox control fired the event.
chkList1 = new CheckBox();
chkList1.Text = row["subj_nme"].ToString();
chkList1.ID = row["subjid"].ToString();
chkList1.Checked = true;
chkList1.Font.Name = "Verdana";
chkList1.Font.Size = 12;
chkList1.AutoPostBack = true;
chkList1.CheckedChanged += new EventHandler(CheckBox_CheckedChanged);
Panel1.Controls.Add(chkList1);
protected void CheckBox_CheckedChanged(object sender, EventArgs e)
{
Label1.Text = "Called";
}
If the events aren't firing, it's likely for one of two reasons:
The controls are recreated too late in the page lifecycle. Try creating the controls during OnInit.
Validation is preventing the postback. To work around this you can set CausesValidation to false on all of the CheckBox controls.
You can find out which control triggered the event using the sender argument.
protected void CheckBox_CheckChanged(object sender, EventArgs e)
{
//write the client id of the control that triggered the event
Response.Write(((CheckBox)sender).ClientID);
}

How determine which control was clicked in WPF UserControl?

I have a WPF user contol, in which I have a StackPanel. To this panel I'm adding programatically a label this way (Container is the name of StackPanel):
public void Insert(string Value)
{
Label l = new Label();
l.Content = Value;
Container.Children.Add(l);
}
Now I want to provide some public event SelectedIndexChange, when user clicks on label. Now I have a problem how determine which label was clicked. Can someone help?
If in Insert you add the line:
l.Click += ClickHandler;
then the first argument of ClickHandler will be the control that raised the Click event.
e.g. If your handler is:
private void ClickHandler(object sender, RoutedEventArgs e){...};
then sender will be the label that was clicked.
You could alternatively look at e.OriginalSource.
I Guess You Can Use This Code
l.MouseClick+= MouseClickHandler;
And Switch Between Lables
Example:
private void label1_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.LeftButton== MouseButtonState.Pressed)
{
Label l = (Label)e.Source;
switch (l.Name)
{
case "lable1":
int a = 10;
break;
}
}
}

Categories