This question already has answers here:
C# - Add button click events using code
(3 answers)
Closed 6 years ago.
I program a game in c# and I created buttons array for the game board. The buttons defined in the code (I did not draw them on the panel). How can I creat an action that happens when the user clicks on the button?
You say you have an array of buttons:
Button[] buttons = new Button[10]; // Let's say 10
for (int i=0; i<buttons.Length; i++)
{
buttons[i] = new Button();
buttons[i].Click += button_Click;
}
private void button_Click(object sender, EventArgs e)
{
// This method is invoked when any of the buttons is clicked
}
You could add something like this:
Button _myButton= new Button();
button.Click += (s,e) => { your code; };
button.Click += new EventHandler(myButton_Click);
container.Controls.Add(button);
Related
I'm working on a c# winforms application.I have created buttons from the back end, like the following:
Button b = new Button();
How can I attach a click to each button that is created from the back end, that each button when clicked, a picture should become visible.
You can register events like this:
Button b = new Button();
b.Click += customButton_Click;
public void customButton_Click(object sender, EventArgs e)
{
// code here
}
Here the += operator will helps you to register the event handlers.
This question already has answers here:
C# Create Dynamic Buttons and onClick Dynamic EventHandlers
(2 answers)
Closed 5 years ago.
I have code which generates buttons dynamically
Button txt = new Button();
this.Controls.Add(txt);
txt.Top = cleft * 40;
txt.Name = "txt_" + cb;
txt.Size = new Size(200, 16);
txt.Left = 150;
But I cannot think how to generate its click event.
I assume you don't mean "how to generate", but rather how to handle. Since you have a reference to your dynamic button, just add an event handler:
txt.Click += new EventHandler(eventHandlerFunction);
Or use a lambda:
txt.Click += (object sender, EventArgs e) => ...;
I wanna make an example application in C# to show to my classmates(I'm 10th grade) how would a Wireless Device Controller Interface work. I know how to write most of the program, but I don't know how to do one thing.
I wanna create a button programmatically and once it is created, associate to it a panel that will show and hide when that button is clicked. Can someone help me?
I forgot to tell you something. The panel needs to be created programmatically too.
Create panel:
var panel = new Panel();
this.Controls.Add(panel);
Create button:
var button = new Button();
this.Controls.Add(button);
Add event handler to button:
button.Click += (o,e) =>
{
panel.Visible = !panel.Visible;
};
Is the Panel also created dynamically? – Idle_Mind
#Idle_Mind yes, it is. I forgot to mention it – DannyDSB Official
The easiest way is to simply store a reference to the Panel in the Tag() property of the Button. Here's a silly example:
private void button1_Click(object sender, EventArgs e)
{
Panel pnl = new Panel();
pnl.BorderStyle = BorderStyle.FixedSingle;
pnl.BackColor = Color.Red;
Button btn = new Button();
btn.Text = "Toggle Panel";
btn.Tag = pnl;
btn.Click += delegate {
Panel p = (Panel)btn.Tag;
p.Visible = !p.Visible;
};
flowLayoutPanel1.Controls.Add(btn);
flowLayoutPanel1.Controls.Add(pnl);
}
First you need the name of the panel. You need to set its visibility property to change the visibility (duh.)
To do that on a button click, you need to attach an event handler to it. Let's first assume that you called your newly created button "myButton" for simplicities sake.
First you create the handler function
void myButton_Click(object sender, RoutedEventArgs e){
panel.visibility = whatever;
}
and later assign the function to the click handler with
myButton.Click += myButton_Click;
I have created buttons by code as:
List<Button> buttons = new List<Button>();
ArrayList myTopics = sqlFunction.loadTopicList();
for (int i = 0; i < myTopics.Count; i++)
{
Button newButton = new Button();
buttons.Add(newButton);
panel1.Controls.Add(newButton);
}
Now I have to add click event listener to these buttons. What I need is like:
if(ClickedButton.Text =="something")
{
//do something
}
When looked in UI, this form contains only the empty panel - panel1. Can you please give any idea how would I give add this click event ??
I don't remember well enough the events on the buttons since I'm on my phone. But, you should do something like this:
(Assuming you are using Winforms)
in your loop:
newButton.Click += new EventHandler(do_something);
outside the loop:
void do_something(object sender, EventArgs e)
{
var btn = sender as Button;
if(btn.Text == "something")
{
//now, do something cool
}
}
I'm working on a project that is a quiz. I am using 4 asp buttons that are styled with CSS, and I am using those 4 buttons as answers, with the right or wrong answer in the button's text field. I have read around and found another post regarding something very similar to this but the answers were to use a dictionary list. I am kind of sure that I don't need to use a list, that I should be able to randomly assign the text attribute. Here is the code that I am using to add the answers to the buttons text attribute but I need to randomize where the answers go, because it wouldn't be right to have the correct answer in the same button all the time.
lblQuestion.Text = ds.Tables[0].Rows[myNum]["Question"].ToString();
btn1.Text = ds.Tables[0].Rows[myNum]["CorrectAnswer"].ToString();
btn2.Text = ds.Tables[0].Rows[myNum]["WrongAnswer1"].ToString();
btn3.Text = ds.Tables[0].Rows[myNum]["WrongAnswer2"].ToString();
btn4.Text = ds.Tables[0].Rows[myNum]["WrongAnswer3"].ToString();
each button has an onlick method to change to the next question and changes the buttons text to the next answers. This code is in every buttonclick event...
protected void btn1_Click(object sender, EventArgs e)
{
lblQuestion.Text = ds.Tables[0].Rows[myNum]["Question"].ToString();
btn1.Text = ds.Tables[0].Rows[myNum]["CorrectAnswer"].ToString();
btn2.Text = ds.Tables[0].Rows[myNum]["WrongAnswer1"].ToString();
btn3.Text = ds.Tables[0].Rows[myNum]["WrongAnswer2"].ToString();
btn4.Text = ds.Tables[0].Rows[myNum]["WrongAnswer3"].ToString();
myNum = myNum + 1;
}
I'm unsure but maybe I need to be able to use one method that can randomize all the buttons text instead of coding into each buttonclick event?
Thanks
I wrote a simple subroutine to demonstrate how to randomly order strings and then attach them to buttons. This example simply demonstrates how to randomize the location of the correct answer among 4 possible places on the screen.
static void Main()
{
// create array of 4 string (or answers in your case)
//string[] array = new string[4] { "apple", "banana", "cranberry", "dragon fruit" };
string[] array = new string[4] {
ds.Tables[0].Rows[myNum]["CorrectAnswer"].ToString(),
ds.Tables[0].Rows[myNum]["WrongAnswer1"].ToString(),
ds.Tables[0].Rows[myNum]["WrongAnswer2"].ToString(),
ds.Tables[0].Rows[myNum]["WrongAnswer3"].ToString(),
};
// randomize the ordering of the items
System.Random rnd = new System.Random();
array = array.OrderBy(x => rnd.Next()).ToArray();
// each time you run this, the correct answer will be in a different place:
btn1.Text = array[0];
btn2.Text = array[1];
btn3.Text = array[2];
btn4.Text = array[3];
}
Bonus answer, you can also wire-up multiple buttons to a single Event Handler like so. Once inside the handler, you can access the Button that raised the event and perform actions:
protected void Page_Load(object sender, EventArgs e)
{
// attach event handlers
Button1.Click += ButtonClick;
Button2.Click += ButtonClick;
Button3.Click += ButtonClick;
Button4.Click += ButtonClick;
}
private void ButtonClick(object sender, EventArgs e)
{
// your code here...
// this is the button that raised the event
Button button = (Button)sender;
// check its ID? you could also check its text, perform any actions you wish, etc.
if (button.ID == "Button1")
{
System.Diagnostics.Debug.Print("Button 1 Clicked!");
}
}