So I'm trying to make a button to so that when it is clicked, the button will turn transparrent, and a game in the background will begin. I'm new and don't know what i'm doing, but here is my code:
public Form1()
{
//Just ignore all this
InitializeComponent();
Label[] labelArray = { label1, label2, label3, label4, label5,
label6, label7, label8, label9 };
for (int i = 0; i < labelArray.Length; i++)
{
labelArray[i].BackColor = System.Drawing.Color.Transparent;
}
//Button details...
Button buttonStart = new Button();
buttonStart.Location = new Point(90, 150);
buttonStart.Text = ("Click start to begin");
buttonStart.Size = new Size(150, 50);
//Adding the evnet handler
buttonStart.Click += new EventHandler(buttonStart_Click);
//Adding the button to the form
this.Controls.Add(buttonStart);
buttonStart.BringToFront();
//Clicking it, in the hopes that what in (buttonStart_Click event
//handler would do something)
buttonStart.PerformClick();
}
//Eventhandler that says it cannot recoqnize
//my "buttonStart", and I cannot seem to find any other way to do this
private void buttonStart_Click(object sender, EventArgs e)
{
buttonStart.BackColor = System.Drawing.Color.Transparent;
}
try this:
private void buttonStart_Click(object sender, EventArgs e)
{
this.buttonStart.visible = false;
}
Related
I am creating an online test application, in which I am generating approximately 100 buttons at run time on form load. Here is the piece of code:w
private void addQuestion_Reviewbutton()
{
for (int i = 1; i <= clsGlobalVars.gnTotalQuestion; i++)
{
Button button = new Button();
button.Location = new Point(160, 30 * i + 10);
button.Click += new EventHandler(ButtonClickOneEvent);
button.Tag = i;
button.Name = "Question" + i;
button.Text = i.ToString();
button.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.button));
button.BackgroundImageLayout = ImageLayout.Stretch;//.Zoom;
button.FlatAppearance.BorderSize = 0;
button.Size = new System.Drawing.Size(47, 41);
button.BackColor = Color.Transparent;
button.FlatStyle = FlatStyle.Flat;
button.Font = new System.Drawing.Font("Segoe UI Semibold", 12);
button.ForeColor = Color.White;
button.Cursor = Cursors.Hand;
flowLayoutPanel1.Controls.Add(button);
}
}
and on this button click, I am changing the background-color.
void ButtonClickOneEvent(object sender, EventArgs e)
{
Button button = sender as Button;
//button.BackColor = Color.Yellow;
button.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.button_Orange));
lblQuestionNo.Text = ((int)button.Tag).ToString()+".";
btnNext.Focus();
}
I have a button on the form Named "Next". Now my problem is that if I am currently in question "1." and I press the button next I want to change the background image of the button whose text is "2".
Yo check this !
tldr; the guidance are
Is the click event go to ButtonClickOneEvent ?
How to call other button
...
profit?
protected void Page_Load(object sender, EventArgs e)
{
addQuestion_Reviewbutton();
}
void ButtonClickOneEvent(object sender, EventArgs e)
{
Button button = sender as Button;
var currentbtn_id = button.ID;
int nextid = Convert.ToInt32( currentbtn_id.Substring("Question".Length)) + 1;
var nextBtn = flowLayoutPanel1.FindControl("Question"+ nextid.ToString() );
(nextBtn as Button).BackColor = Color.Red;
}
I have a grid with 9 buttons. In the timer tick event a random button is higlighted. If one clicks the higlighted button, a dynamic click event is created and within the click event the button is marked with a different color. The counterHits variable in the dynamic button click event is supposed to keep track of the highlighted buttons that were hit. Sometimes though it increases the variable more than by one. I cannot figure out why this is happening. Any help anyone?
public partial class Form1 : Form
{
const int buttons = 9;
int counterHits;
int counterTicks;
int currentIndex;
int lastIndex;
bool hit = false;
Random r;
Timer timerGameLoop;
Timer timerUpdateUI;
public Form1()
{
InitializeComponent();
timerGameLoop = new Timer();
timerGameLoop.Interval = 1000;
timerGameLoop.Tick += t_Tick;
timerUpdateUI = new Timer();
timerUpdateUI.Interval = 10;
timerUpdateUI.Tick += timerUpdateUI_Tick;
r = new Random();
}
// set up the grid and start
private void btnStart_Click(object sender, EventArgs e)
{
for (int i = 0; i < buttons; i++)
{
var b = new Button();
b.Size = new Size(100, 100);
b.Margin = new Padding(0);
b.BackColor = Color.White;
flowLayoutPanel.Controls.Add(b);
}
timerGameLoop.Start();
timerUpdateUI.Start();
}
// tick event ui update loop
void timerUpdateUI_Tick(object sender, EventArgs e)
{
lblHitCounter.Text = "hits : " + counterHits.ToString();
lblTickCounter.Text = "ticks : " + counterTicks.ToString();
}
// tick event game loop
void t_Tick(object sender, EventArgs e)
{
// reset to white background if not clicked
if (!hit)
flowLayoutPanel.Controls[lastIndex].BackColor = Color.White;
// highlight button to be clicked
currentIndex = r.Next(buttons);
lastIndex = currentIndex;
flowLayoutPanel.Controls[currentIndex].BackColor = Color.Violet;
// highligted button clicked
flowLayoutPanel.Controls[currentIndex].Click += b_Click;
hit = false;
counterTicks++;
}
// highlighted button clicked event
void b_Click(object sender, EventArgs e)
{
var b = (Button)sender;
b.BackColor = Color.Olive;
hit = true;
counterHits++;
b.Click -= b_Click;
}
}
The following lines attaches b_Click to your button. That eventhandler is only removed if you press the button
flowLayoutPanel.Controls[currentIndex].Click += b_Click;
See the implementation of b_Click
// highlighted button clicked event
void b_Click(object sender, EventArgs e)
{
//Stugg
b.Click -= b_Click;←Removed Here only if it is pressed
}
This line indicates that some buttons have more than one EventHandler attached. Therefore when you click the button eventhandler runs more than once.
I want to create a form programmatically, then add controls to that for and handle click events on those controls,
such as click on button should show impact on text box
namespace formwizard
{
public partial class Form1 : Form
{
Form form = new Form();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
form.Text = formtitle.Text;
int count = Convert.ToInt32(FormName.Text);
int i=1;
while (i<= count)
{
TextBox tb = new TextBox();
tb.Text = "Text box"+ i.ToString();
Button bt = new Button();
bt.Text = "Button" + i.ToString();
tb.Location = new Point(15, i*20);
bt.Location = new Point(120, i*20);
bt.Name = "Button" + i.ToString();
form.Controls.Add(tb);
form.Controls.Add(bt);
bt.Click +=new EventHandler(bt_Click);
i++;
}
// form.Controls.Add(...);
form.ShowDialog();
}
void bt_Click(object sender, EventArgs e)
{
Button btn = (Button) sender;
string a=btn.Text.Substring(6,btn.Text.Length-6);
MessageBox.Show("You clicked Button "+a);
}
}
}
Your code is correct, the only problem I see is you haven't initialized a new instance of Form:
Form form2 = new Form();
//now add your controls to this form
//show form using "form2.ShowDialog()"
I'm trying to change for a preset amount of time the backcolor of a pictureBox when the user clicks a button. I tried to use timers but I saw this Stopwatch on another question. The problem is that the code inside the loop isn't running properly and it keeps crashing.How can I make this work? Code below
private void b_click(object sender, EventArgs e)
{
Button button = sender as Button;
Dictionary <Button, PictureBox> buttonDict= new Dictionary<Button, PictureBox>();
//4 buttons
buttonDict.Add(bRED, pbRED);
buttonDict.Add(bBlue, pbBLUE);
buttonDict.Add(bGREEN, pbGREEN);
buttonDict.Add(bYELLOW, pbYELLOW);
Stopwatch s = new Stopwatch();
s.Start();
while (s.Elapsed < TimeSpan.FromSeconds(0.5))
{
buttonDict[button].BackColor = Color.Black;
label1.Text = "black";//This part does run
}
buttonDict[button].BackColor = Color.White; //the pictureBox does turn white
s.Stop();
}
Use Timer instead of Stopwatch :
private void b_Click(object sender, EventArgs e)
{
Button button = sender as Button;
Dictionary<Button, PictureBox> buttonDict = new Dictionary<Button, PictureBox>();
//4 buttons
buttonDict.Add(bRED, pbRED);
buttonDict.Add(bBlue, pbBLUE);
buttonDict.Add(bGREEN, pbGREEN);
buttonDict.Add(bYELLOW, pbYELLOW);
Timer timer = new Timer();
timer.Interval = 500;
timer.Tick += (o, args) =>
{
buttonDict[button].BackColor = Color.White;
timer.Stop();
timer.Dispose();
};
buttonDict[button].BackColor = Color.Black;
label1.Text = "black";
timer.Start();
}
Another possibilities, using Task.Run:
private void b_Click(object sender, EventArgs e)
{
Button button = sender as Button;
Dictionary<Button, PictureBox> buttonDict = new Dictionary<Button, PictureBox>();
//4 buttons
buttonDict.Add(bRED, pbRED);
buttonDict.Add(bBlue, pbBLUE);
buttonDict.Add(bGREEN, pbGREEN);
buttonDict.Add(bYELLOW, pbYELLOW);
buttonDict[button].BackColor = Color.Black;
label1.Text = "black";
Task.Run(() =>
{
Thread.Sleep(500);
Invoke(new MethodInvoker(() =>
{
buttonDict[button].BackColor = Color.White;
}));
});
}
Use something like this:
private void b_click(object sender, EventArgs e)
{
pictureBox1.BackColor = Color.Black; //First color
new System.Threading.Tasks.Task(() => PictureBoxTimeoutt(1000)).Start(); //miliseconds until change
}
public void PictureBoxTimeout(int delay)
{
System.Threading.Thread.Sleep(delay);
Invoke((MethodInvoker)delegate
{
pictureBox1.BackColor = Color.White; //Second color
};
}
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GenerateButtons generate = new GenerateButtons();
generate.Generate5Controls(PlaceHolder1);
}
}
class GenerateButtons
{
PlaceHolder placeHolder;
public void Generate5Controls(PlaceHolder placeH)
{
placeHolder = placeH;
for (int i = 0; i < 5; i++)
{
Button newBtn = new Button();
newBtn.Click += btn_Click;
newBtn.Text = "PageLoadButton Created. Number: "+i;
placeHolder.Controls.Add(newBtn);
}
}
public void btn_Click(object sender, EventArgs e)
{
Button newBTN = new Button();
newBTN.Text = "A New Button was added by the button event btn_click";
newBTN.Click += btn2_Click;
placeHolder.Controls.Add(newBTN);
}
public void btn2_Click(object sender, EventArgs e)
{
Button newBTN = new Button();
newBTN.Text = "A New Button was added by the button event btn2_click";
placeHolder.Controls.Add(newBTN);
}
}
I want the events btn_click & btn2_click to fire every post back.. When i click the button that was programmatically created it disappears after each postback and its event doesnt fire (btn2_click). I know i could generate the button at the postback.. But I dont want to do that!! I want to know how I could update the state of the placeholder... so that the only button will appear and the 5 buttons generated in Generate5Controls(PlaceHolder placeH) to disappear.
I could use a bool Viewstate to prevent this generate.Generate5Controls(PlaceHolder1); from being execute..
But the question is how do I make the programmatically generated button to appear!?
You should generate controls on every PostBack or you can generate controls once, save in session and add generated controls from session on page_load event.
protected void Page_Load(object sender, EventArgs e)
{
if(Session["GeneratedButtons"] == null)
{
GenerateButtons generate = new GenerateButtons();
generate.Generate5Controls(PlaceHolder1);
}
else
{
List<Control> generatedControls = Session["GeneratedButtons"] as List<Control>;
foreach(Control oneControl in generatedControls)
{
PlaceHolder1.Controls.Add(oneControl);
}
}
}
class GenerateButtons
{
PlaceHolder placeHolder;
public void Generate5Controls(PlaceHolder placeH)
{
placeHolder = placeH;
List<Control> generatedControls = new List<Control>();
for (int i = 0; i < 5; i++)
{
Button newBtn = new Button();
newBtn.Click += btn_Click;
newBtn.Text = "PageLoadButton Created. Number: "+i;
placeHolder.Controls.Add(newBtn);
AddControlToSession(newBtn);
}
}
public void btn_Click(object sender, EventArgs e)
{
Button newBTN = new Button();
newBTN.Text = "A New Button was added by the button event btn_click";
newBTN.Click += btn2_Click;
placeHolder.Controls.Add(newBTN);
AddControlToSession(newBtn);
}
public void btn2_Click(object sender, EventArgs e)
{
Button newBTN = new Button();
newBTN.Text = "A New Button was added by the button event btn2_click";
placeHolder.Controls.Add(newBTN);
AddControlToSession(newBtn);
}
private void AddControlToSession(Control ctrl)
{
List<Control> generatedControls = Session["GeneratedButtons"] as List<Control>;
if(generatedControls == null)
{
generatedControls = new List<Control>();
}
generatedControls.Add(ctrl);
Session["GeneratedButtons"] = generatedControls;
}
}