I managed to create textboxes that are created at runtime on every button click. I want the text from textboxes to disappear when I click on them. I know how to create events, but not for dynamically created textboxes.
How would I wire this up to my new textboxes?
private void buttonClear_Text(object sender, EventArgs e)
{
myText.Text = "";
}
This is how you assign the event handler for every newly created textbox :
myTextbox.Click += new System.EventHandler(buttonClear_Text);
The sender parameter here should be the textbox which sent the even you will need to cast it to the correct control type and set the text as normal
if (sender is TextBox) {
((TextBox)sender).Text = "";
}
To register the event to the textbox
myText.Click += new System.EventHandler(buttonClear_Text);
Your question isn't very clear, but I suspect you just need to use the sender parameter:
private void buttonClear_Text(object sender, EventArgs e)
{
TextBox textBox = (TextBox) sender;
textBox.Text = "";
}
(The name of the method isn't particularly clear here, but as the question isn't either, I wasn't able to suggest a better one...)
when you create the textBoxObj:
RoutedEventHandler reh = new RoutedEventHandler(buttonClear_Text);
textBoxObj.Click += reh;
and I think (not 100% sure) you have to change the listener to
private void buttonClear_Text(object sender, RoutedEventArgs e)
{
...
}
I guess the OP wants to clear all the text from the created textBoxes
private void buttonClear_Text(object sender, EventArgs e)
{
ClearSpace(this);
}
public static void ClearSpace(Control control)
{
foreach (var c in control.Controls.OfType<TextBox>())
{
(c).Clear();
if (c.HasChildren)
ClearSpace(c);
}
}
This should do the job :
private void button2_Click(object sender, EventArgs e)
{
Button btn = new Button();
this.Controls.Add(btn);
// adtionally set the button location & position
//register the click handler
btn.Click += OnClickOfDynamicButton;
}
private void OnClickOfDynamicButton(object sender, EventArgs eventArgs)
{
//since you dont not need to know which of the created button is click, you just need the text to be ""
((Button) sender).Text = string.Empty;
}
Related
I am creating one button on a page dynamically. Now I want to use the button click event on that button.
How can I do this in C# ASP.NET?
Button button = new Button();
button.Click += (s,e) => { your code; };
//button.Click += new EventHandler(button_Click);
container.Controls.Add(button);
//protected void button_Click (object sender, EventArgs e) { }
The easier one for newbies:
Button button = new Button();
button.Click += new EventHandler(button_Click);
protected void button_Click (object sender, EventArgs e)
{
Button button = sender as Button;
// identify which button was clicked and perform necessary actions
}
Simply add the eventhandler to the button when creating it.
button.Click += new EventHandler(this.button_Click);
void button_Click(object sender, System.EventArgs e)
{
//your stuff...
}
It is much easier to do:
Button button = new Button();
button.Click += delegate
{
// Your code
};
You can create button in a simple way, such as:
Button button = new Button();
button.Click += new EventHandler(button_Click);
protected void button_Click (object sender, EventArgs e)
{
Button button = sender as Button;
// identify which button was clicked and perform necessary actions
}
But event probably will not fire, because the element/elements must be recreated at every postback or you will lose the event handler.
I tried this solution that verify that ViewState is already Generated and recreate elements at every postback,
for example, imagine you create your button on an event click:
protected void Button_Click(object sender, EventArgs e)
{
if (Convert.ToString(ViewState["Generated"]) != "true")
{
CreateDynamicElements();
}
}
on postback, for example on page load, you should do this:
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToString(ViewState["Generated"]) == "true") {
CreateDynamicElements();
}
}
In CreateDynamicElements() you can put all the elements you need, such as your button.
This worked very well for me.
public void CreateDynamicElements(){
Button button = new Button();
button.Click += new EventHandler(button_Click);
}
Let's say you have 25 objects and want one process to handle any one objects click event. You could write 25 delegates or use a loop to handle the click event.
public form1()
{
foreach (Panel pl in Container.Components)
{
pl.Click += Panel_Click;
}
}
private void Panel_Click(object sender, EventArgs e)
{
// Process the panel clicks here
int index = Panels.FindIndex(a => a == sender);
...
}
So I have a matrix of panels (maybe will change for Picture Boxes in the future), and what i want is that every time i press one of the panels after pressing the button on the toolbox it will change it's background to a certain picture.
Right now what i have is:
private void EtapaInicial_Click(object sender, EventArgs e)
{
EtapaInicialWasClicked = true;
}
private void panel_Click(object sender, EventArgs e)
{
if (EtapaInicialWasClicked)
{
panel1.BackgroundImage = Symbols.EtapaInicialbm;
EtapaInicialWasClicked = false;
}
}
What I would like to change was the panel1 to make it work for every panel (otherwise it will only change panel1 independently of the panel i've clicked), is that possible?
Try the following
private void EtapaInicial_Click(object sender, EventArgs e)
=> EtapaInicialWasClicked = true;
private void panel_Click(object sender, EventArgs e)
{
if (EtapaInicialWasClicked)
{
(sender as Panel).BackgroundImage = Symbols.EtapaInicialbm;
EtapaInicialWasClicked = false;
}
}
Yes it is. You have to loop through each panel
and assign the same event handler but you have to make some changes in the event handler itself
foreach(var p in allPanels)
{
p.Click += panel_Click;
}
Then change your event handler like this
private void panel_Click(object sender, EventArgs e)
{
var p = (Panel)sender;
if (EtapaInicialWasClicked)
{
p .BackgroundImage = Symbols.EtapaInicialbm;
EtapaInicialWasClicked = false;
}
}
Remember the sender argument contains reference to the actual control that initiated the event but you have to cast it first in order to use it.
However if you want to store more data for the event you've just handled you can use the panel.Tag property. This can be used to store EtapaInicialWasClicked for example
I am new to C# and I am planing to design my own keypad but I don't know how/where to start. as shown in photo, I have 4 textBoxes the keypad buttons.
The first problem came into my mind was: how can I detect the cursor location (which textBox is the cursor in?).
So for example if I had only one textbox then it is easy I could write inside button1 : textBox1.text = "1" and inside button2 : textBox1.text = "2" and inside button_A : textBox1.text = "A".... and so on but I have 4 textBoxes and it is confusing.
Can you please provide me with an idea or what to write inside each button to print its value in the textbox which the cursor is in.
Thank you professionals.
Firstly, have a textbox that represents the one that is selected (outside of subroutines but inside the class):
TextBox SelectedTextBox = null;
And then make the "Click" event of each TextBox look like this:
private void textBoxNUM_Click(object sender, EventArgs e)
{
SelectedTextBox = sender as TextBox;
}
And then make the "Click" event of each Button look like this:
private void buttonNUM_Click(object sender, EventArgs e)
{
if (SelectedTextBox != null)
{
SelectedTextBox.Text = buttonNUM.Text;//Or set it to the actual value, whatever.
}
}
Or if that one doesn't work, this should.
private void buttonNUM_Click(object sender, EventArgs e)
{
if (SelectedTextBox != null)
{
(SelectedTextBox as TextBox).Text = buttonNUM.Text;//Or set it to the actual value, whatever.
}
}
To check if a textbox is focused you can do
if(textbox1.Focused)
{
//Print the value of the button to textbox 1
}
else if (textbox2.Focused)
{
//Print the value to textbox 2
}
UPDATE:
Since the textbox will lose focus when you click the button, you should have a temporary textbox (ie lastTextboxThatWasFocused) which is saved to everytime a textbox gains focus. Write an OnFocused Method and do something like
public void Textbox1OnFocused(/*Sender Event Args*/)
{
lastTextboxThatWasFocused=textbox1;
}
Then on button click you can do
if(lastTextboxThatWasFocused.Equals(textbox1))
{
//ETC.
}
You can give something along these lines a try. Create a generic click handler for the buttons and then assign the value to a textbox the text from the button, which happens to be the value. You can check which box was the last one focused in the TextBoxes' Click event. Create a global variable to store which one and use it in the below method.
private TextBox SelectedTextBox { get; set; }
private void NumericButton_Click(object sender, EventArgs e)
{
var clickedBox = sender as Button;
if (clickedBox != null)
{
this.SelectedTextBox.Text += clickedBox.Text;
}
}
private void TextBox_Click(object sender, EventArgs e)
{
var thisBox = sender as TextBox;
if (thisBox == null)
{
return;
}
this.SelectedTextBox = thisBox;
}
Try this code:
TextBox LastTxtBox;
private void textBox_Enter(object sender, EventArgs e)
{
LastTxtBox = sender as TextBox;
}
private void button_Click(object sender, EventArgs e)
{
LastTxtBox.Text = this.ActiveControl.Text;
}
Add textBox_Enter function to all textboxes enter event.
Add button_Click to all buttons click event.
Button Enter Event
Control _activeControl;
private void NumberPadButton_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
if (_activeControl is TextBox || _activeControl is RichTextBox)
{
_activeControl.Text += btn.Text;
if (!_activeControl.Focused) _activeControl.Focus();
}
}
TextBox or RihTextBox Enter Event
private void TextBoxEnter_Click(object sender, EventArgs e)
{
_activeControl = (Control)sender;
}
Looking to refactor some application code. I have a GUI that has several of the same events that are reflected for different labels, textboxes, etc...
For example:
private void textBox1_Enter(object sender, EventArgs e)
{
textBox1.BackColor = Color.LightCyan;
}
and
private void textBox2_Enter(object sender, EventArgs e)
{
textBox2.BackColor = Color.LightCyan;
}
I just assign these methods to the event on the object properties in Visual Studio. Is there an efficient way to combine multiple event methods to clean up the code? Thanks!
Define a single event like:
private void textBox_Enter(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
if (textBox != null)
textBox.BackColor = Color.LightCyan;
}
and then assign that event to all your TextBox Enter event like:
textBox1.Enter += textBox_Enter; //Same event handler
textBox2.Enter += textBox_Enter; //Same event handler
If both event handlers do the same exact logic, as you probably have listed here, just create 1 event handler and assign it to both components.
private void TextBox_Enter(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
if (textBox != null) {
textBox.BackColor = Color.LightCyan;
}
}
To elaborate slightly you can take this approach even when you want to perform different actions depending on the control that fired the event.
private void textBox_Enter(object sender, EventArgs e)
{
//Check if the sender is textBox1
if(ReferenceEquals(sender, textBox1))
{
//Perform action on textBox1
}
//Check if the sender is textBox2
if(ReferenceEquals(sender, textBox2))
{
//Perform action on textBox2
}
}
I'm making a mahjong game and I'm totally new at C#, I wonder how i can take a button's name when it's clicked. All the buttons are created dynamically in the form.
public Button createButton(node x)
{
Button nButton;
nButton = new Button();
nButton.Name = x.info.ToString();
nButton.Text = x.info.ToString();
nButton.Width = 55;
nButton.Height = 75;
nButton.Visible = true;
if (x.isValid())
nButton.Enabled = true;
else
nButton.Enabled = false;
nButton.Click += new System.EventHandler(n1_click);
return nButton;
}
in the form i take buttons with this code
myButton = createButton(tp);
myButton.Location = new System.Drawing.Point(25 , 25);
this.Controls.Add(myButton);
The first argument to the event handler is the sender, you can cast that to a Button and then access the Name property.
Here is a small example of the event handler.
private void Button_Click(object sender, EventArgs e)
{
Button button = sender as Button;
if (button != null)
{
// Do something with button.Name
}
}
Edit: As Hans mentioned in the comments, using as could hide a potential bug. Using the as operator as in the example above will ensure that if you inadvertently wire this handler to an event of another control the code will handle it graciously and not throw an InvalidCastException, but there-in lies a problem as well, because this now silently fails you might not pickup a bug in your code. If the exception was thrown you would have realized there is a problem and been able to track it down. So the updated code would be something like this.
private void Button_Click(object sender, EventArgs e)
{
// If sender is not a Button this will raise an exception
Button button = (Button)sender;
// Do something with button.Name
}
With the following code you can get the button that was clicked
protected void Button1_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
}
on the function which handles the click "n1_click"
private void n1_click(object sender, EventArgs e)
{
Button temp = (Button)sender;
string neededText = temp.Text;
}