I am having trouble getting my 'start' button to show when I select either of the radio boxes.
Ideally, when one of the boxes is selected, the 'start' button will enable and allow to be clicked.
Here is my code for the form, as I am relatively new to C# I'm not sure if I'm posting all of the code you need, I'll post more if required.
public partial class mainForm : Form
{
public mainForm() {
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e) {
}
private void mainForm_Load(object sender, EventArgs e) {
title.Font = new Font("Arial", 10, FontStyle.Bold);
}
private void startButton_Click(object sender, EventArgs e) {
if (radioDice.Checked) {
startButton.Enabled = true; //Activates 'start' button
whichDiceGameForm GameForm = new whichDiceGameForm();
GameForm.Show();
}
if (radioCard.Checked) {
startButton.Enabled = true; //Activates 'start' button
whichCardGame GameForm = new whichCardGame();
GameForm.Show();
}
}
}
[Posting for a friend.]
You have placed your enable code in the Button's Click event Handler while you should do it on your checkboxes changed.
Take this code :
if (radioDice.Checked)
{
startButton.Enabled = true;
}
to radioDice checkbox's changed event handler and this one :
if (radioCard.Checked)
{
startButton.Enabled = true; //Activates 'start' button
}
to radioCard checkbox's changed event handler .
Man, seriously?
ANSWER:
You're trying to enable DISABLED button when clicking on that button. You cannot click DISABLED button. What's more - you're duplicating your code.
Button should be always enabled. You only have two choices. Every choice enabled button. So it should be always enabled. No matter the choice. If there is something hidden and button may be disabled, then enable the button in Radio Click event.
Additional information about your code:
Now. About code duplication. Look what you're doing in startButton_Click. You have duplicated code.
You can do something like:
BaseGameForm f = null;
if(radioDice.Checked)
f = new DiceGameForm();
else
if(radioCard.Checked)
f = new CardGameForm();
f.Show();
(BaseGameForm is base form for every game)
But this is not good solution. Better solution is (somewhere in construtor):
radioDice.Tag = new DiceGameForm();
radioCard.Tag = new CardGameForm();
Then in Start button click you look for checked radio:
foreach(Control c in selectGameTypeGroupBox.Controls) //you could do this using LINQ
{
if((c is RadioButton) && ((RadioButton)c).Checked)
{
((Form)c.Tag).Show();
}
}
But this is still not good solution, because you're creating all game forms at startup and this is stupid.
So the better solution would be to keep game form class name in your radio Tag property and then create object of this class using reflection and Activator.
But this is still not the best solution. But I assume that this is one of your first applications so I won't be telling you now about separating gui from logic. If you want to know more - read on the Internet. Or just ask.
Related
I checked and found this article that is referred to MANY times in this type of question, and it is NOT the answer I want...
I have a form, Form_Main frmMainPage, it creates Form_Status frmStatus.
When it does so, I disable the controls on frmMainPage so the user can't mess with things while things are processing.
When things are done processing they can close the frmStatus window to go back to frmMainPage to continue working. I cannot re-enable the controls from frmStatus. I tried to use the frmMainPage_Enter, but it goes crazy when it first loads, so that isn't really an option.
I have the following in Form_Main.cs
public void EnableForm() {
this.gridData.Enabled = true;
this.txtLocation.Enabled = true;
this.txtSupplier.Enabled = true;
this.txtItem.Enabled = true;
this.FillTable("", "", "");
}
When I use this (per article above):
private void btnClose_Click(object sender, EventArgs e) {
Form_Main f2 = new Form_Main();
f2.Show();
f2.EnableForm();
this.Close();
}
It creates a second Form_Main, which is not what I want. I want to know how to change the controls in the existing form.
Edit: No, it is not this that was also suggested. Most of the answers deal with changing controls on Form 2 from Form 1 when Form 2 is created by Form 1. In my case I need to do the opposite and change controls on Form 1 FROM Form 2, which was created by Form 1. Kind of a circular thing.
I can think of a couple of ways to do this. First (and most common) is to show the second form modally (which means that the first form's code pauses while the second form's code is running):
private void button1_Click(object sender, EventArgs e)
{
var statusForm = new frmStatus();
// ShowDialog will prevent frmMainPage from being accessible.
// This form's code will pause at the next line until the second form is closed
statusForm.ShowDialog();
}
There are occasions where you want to have both forms accessible at the same time. If this is the case, another method would be to add an event handler for the second form's FormClosed event, where you can re-enable the controls on the first form. This will allow both forms to be accessed at the same time:
private void button1_Click(object sender, EventArgs e)
{
var statusForm = new frmStatus();
// Add an event handler for the second form's FormClosed event, and
// put code in that event handler to re-enable controls on this form
statusForm.FormClosed += statusForm_FormClosed;
// Disable our controls on this form and show the second form
DisableForm();
statusForm.Show();
}
private void statusForm_FormClosed(object sender, FormClosedEventArgs e)
{
// When the second form closes, re-enable controls on this form
EnableForm();
}
private void DisableForm()
{
this.gridData.Enabled = false;
this.txtLocation.Enabled = false;
this.txtSupplier.Enabled = false;
this.txtItem.Enabled = false;
}
public void EnableForm()
{
this.gridData.Enabled = true;
this.txtLocation.Enabled = true;
this.txtSupplier.Enabled = true;
this.txtItem.Enabled = true;
this.FillTable("", "", "");
}
you dont need to do this disable enable.
you just need to show your new from with ShowDialog(); like this:
frmStatus.ShowDialog();
instead of just:
frmStatus.Show();
I have a treenode which displays a checklist from a SQL database. I have a method to get the selected workflows.
I want to enable the run button if a checkbox is checked and disable the button if nothing is checked and on load.
I'm not sure where to put this if statement. I have tried putting it under the run button on the click action but it is not working correctly.
Any help is appreciated.
List<WorkflowViewModel> workflowViewList = new List<WorkflowViewModel();
var workflowList = GetSelectedWrokflows();
if (workflowList.Count == 0)
{
button.enabled = false;
}
else
{
button.enabled = true;
}
One way to do this is to create a method that will do the work of determining the selected workflow items and enabling or disabling the button. By putting the code in a single method, it allows you to call it from multiple places, and if you need to change the behavior, you only have one place to make the modifications.
Then you can just call this method from the Form_Load event, and from the checked list box's ItemCheck event:
public partial class Form1 : Form
{
List<WorkflowViewModel> workflowViewList = new List<WorkflowViewModel>();
private void SetRunButtonState()
{
workflowViewList = GetSelectedWorkflows();
button.Enabled = workflowViewList.Count > 0;
}
private void Form1_Load(object sender, EventArgs e)
{
SetRunButtonState();
}
private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
{
SetRunButtonState();
}
// Rest of class code omitted...
}
I just started programming, and I want to use WinForms to make multiple buttons that you can click on to change from white to lime-green and back to white. I have done this for one button:
private void button1_Click(object sender, EventArgs e)
{
if (button1.BackColor != Color.Lime)
{
button1.BackColor = Color.Lime;
}
else
{
button1.BackColor = Color.White;
}
}
Now I could copy and paste that for all of the buttons, but I know that is inefficient; and if I use winforms to reference button1 on button2, it will just change the color of button1 (obviously).
So, do I need to use a helper method, new class, or something else? What would that look like?
There are a couple of approaches. One might be to create a common function which the different buttons call:
private void button1_Click(object sender, EventArgs e)
{
ChangeColor(button1);
}
private void ChangeColor(Button button)
{
if (button.BackColor != Color.Lime)
button.BackColor = Color.Lime;
else
button.BackColor = Color.White;
}
Then each button handler can use that same function call.
Or, if all of these buttons will always ever do exactly the same thing, then you can use one click handler function for all of them. In this case what you'd need to do is determine which button invoked the handler (whereas you're currently referencing button1 directly) so that you know which one to change. The sender object passed into the handler function is actually a reference to the form element which invoked the handler. All you need to do is cast it:
private void button_Click(object sender, EventArgs e)
{
var button = (Button)sender;
if (button.BackColor != Color.Lime)
button.BackColor = Color.Lime;
else
button.BackColor = Color.White;
}
So first the handler grabs a reference to the button which invoked it, then runs the logic on that button. Note also how I made the name of the handler function slightly more generic. Now you'd go to the form designer and set button_Click as the click handler for all of the buttons which should invoke this.
You do this the exact same way you'd do it for any C# class. You derive your own class and customize the base class behavior. Every event has a corresponding OnXxxx() method that you can override.
Add a new class to your project and paste this code:
using System;
using System.Windows.Forms;
class MyButton : Button {
protected override void OnClick(EventArgs e) {
// Your code here
//...
base.OnClick(e);
}
}
Change the code in OnClick() to do what you want to do. Compile. You'll now have your own button control on the top of the toolbox. And can drop as many copies of it as you want on a form. They'll all behave the same without having to add any code in the form.
Probably the easiest way would be to have each button invoke the same click handler. Then inside of your handler use the Sender instead of hard coding Button1.
private void buttons_Click(object sender, EventArgs e)
{
var theButton = (Button) sender;
if (theButton.BackColor != Color.Lime)
{
theButton.BackColor = Color.Lime;
}
else
{
theButton.BackColor = Color.White;
}
}
You can get the button that raised the Click event by casting sender to Button.
You can then add the same handler to every button.
I'm a VB guy.... in VB.Net you can add multiple handlers for events and connect multiple events to the same handler.
This sub hooks all clicks to color the buttons.
Private Sub ColorButtons(sender As System.Object, e As System.EventArgs) _
Handles Button1.Click, Button2.Click, ..
I do this all the time accidentally because I drag/copy a control to make a new one and the new button gets added to the original's events.
Other Subs can handle the same events to do other work - both will execute.
No idea how to do this in C#.
The proper way to do this really is to associate each button's click event to the function you have coded for that purpose (you want the function to run when the button is clicked, right?), so add the following (or similar) to an appropriate section of your code:
MyButton1.Click += new RoutedEventHandler(buttons_Click);
MyButton2.Click += new RoutedEventHandler(buttons_Click);
etc...
You can associate as many controls to the event handler as you like.
What I usually do before is this:
private void button2_Click(object sender, EventArgs e)
{
button1.PerformClick();
}
This code will just simply run the codes under button1_Click.
But try not to practice as such and just simply put it in a function/method just like what David suggested.
I have a login form. The form has 2 textboxes, and 3 buttons. one button says "Students."
What I want to do is to show a tooltip on this button when the form opens. I dont want to have to go to the button and hover on it in order for it to display. I want the form to load, show the tooltip, and then the tooltip should disappear after 5 seconds. this is what I have tried so far:
private void Form1_Load(object sender, EventArgs e)
{
toolTip.IsBalloon = true;
toolTip.ToolTipIcon = ToolTipIcon.Info;
toolTip.ShowAlways = true;
toolTip.UseFading = true;
toolTip.UseAnimation = true;
toolTip.ToolTipTitle = "Student Mode";
toolTip.Show("You don't have to log in if you are a student. Just click here to go to the questions.", btnStudent);
}
The form's Load event is mis-used far too often. It is here, the event fires before the window becomes visible. Your tooltip is therefore not visible either.
Move your code to a Shown event handler instead. Do favor overriding OnShown() btw, it doesn't make sense for a class to listen to its own events.
protected override void OnShown(EventArgs e) {
base.OnShown(e);
// Your code here
//...
}
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
}