Alright, so I'm trying to practice my windows forms skills and I've been trying to figure out a simple thing such as making a button that says "Show message", when you click it, it makes an invisible label Visible that says "Hey man" and the text of the button should change to "Hide message".
When you click it the label should go invisible again. I tried to do it with if statements for a while but didn't really figure it out, so I just used 2 buttons which made it a million times more simple. I'm just wondering, how would I go about doing it with only 1 button?
My code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void btnShow_Click(object sender, EventArgs e)
{
lblShow.Visible = true;
btnShow.Visible = false;
btnHide.Visible = true;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnHide_Click(object sender, EventArgs e)
{
lblShow.Visible = false;
btnShow.Visible = true;
btnHide.Visible = false;
}
}
}
You could add a bool to your class, and change the bool when you click the button
bool showLabel = true;
private void btnToggle_Click(object sender, EventArgs e)
{
if (showLabel)
{
lblShow.Visible = true;
}
else
{
lblShow.Visible = false;
}
showLabel = !showLabel;
}
This can be done quite simply with only two lines of code:
private void btnToggle_Click(object sender, EventArgs e)
{
lblShow.Visible = !lblShow.Visible;
btnToggle.Text = lblShow.Visible ? "Hide Message" : "Show Message";
}
It can technically be done in one line, but I think it's less readable:
btnToggle.Text = (lblShow.Visible = !lblShow.Visible) ? "Hide Message" : "Show Message";
I suggest keeping a state variable and updating the form based on the value of the state variable. This is a flexible pattern where you can accommodate more than one state, which means you can have combinations of buttons that produce different results.
Try this:
public partial class Form1 : Form
{
public enum FormState
{
MessageHidden,
MessageVisible,
Default = MessageHidden
}
FormState state = FormState.Default;
public Form1()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
UpdateUI();
}
protected void UpdateUI()
{
switch (state)
{
case FormState.MessageHidden:
label1.Visible = false;
button1.Text = "Show Message";
break;
case FormState.MessageVisible:
label1.Visible = true;
button1.Text = "Hide Message";
break;
default:
throw new NotImplementedException();
}
}
private void button1_Click(object sender, EventArgs e)
{
switch (state)
{
case FormState.MessageHidden:
state = FormState.MessageVisible;
break;
case FormState.MessageVisible:
state = FormState.MessageHidden;
break;
default:
throw new NotImplementedException();
}
UpdateUI();
}
}
Example screenshots
FormState.MessageHidden
FormState.MessageVisible
You can refactor using one method to set the label visibility like that:
private void btnToggle_Click(object sender, EventArgs e)
{
lblShow.Visible = !lblShow.Visible;
btnToggle.Text = lblShow.Visible ? "Hide Message" : "Show Message";
}
With the VS Form Desiner you can set the label Visible property to true and the button Text to nothing.
And in the FormLoad event you call the method to set the things :
btnToggle_Click(this, null);
Related
I am new to C# and I want to utilize the forms with one another.
I have 2 forms. (1)MMCMLibrary_home and (2)MMCMLibrary_reserve.
In this project, I'm in the stage of changing the label background colors in Form 1 but can't seem to utilize Form 2 to process it.
These are my necessary codes so far:
FORM 1
namespace MMCM_Library
{
public partial class MMCMLibrary_home : Form
{
public static MMCMLibrary_home instance;
//DCR1 Labels
public Label lbl1_1;
public Label lbl1_2;
public Label lbl1_3;
public Label lbl1_4;
public MMCMLibrary_home()
{
InitializeComponent();
instance = this;
lbl1_1 = lblDCR1_9;
lbl1_2 = lblDCR2_11;
lbl1_3 = lblDCR1_1;
lbl1_4 = lblDCR1_3;
public void btnDCR1_Click(object sender, EventArgs e)
{
var reserveDCR1 = new MMCMLibrary_reserve();
reserveDCR1.Show();
}
public void btnDCR2_Click(object sender, EventArgs e)
{
var reserveDCR2 = new MMCMLibrary_reserve();
reserveDCR2.Show();
}
public void btnDCR3_Click(object sender, EventArgs e)
{
var reserveDCR3 = new MMCMLibrary_reserve();
reserveDCR3.Show();
}
public void btnDCR4_Click(object sender, EventArgs e)
{
var reserveDCR4 = new MMCMLibrary_reserve();
reserveDCR4.Show();
}
}
}
FORM 2
when I click any reserve now button in form 1 it will open form 2. However, if I pick a radio button, the background change will always be applied to Discussion Room 1 even I reserved for discussion room 2
namespace MMCM_Library
{
public partial class MMCMLibrary_reserve : Form
{
public static MMCMLibrary_reserve instance;
public MMCMLibrary_reserve()
{
InitializeComponent();
instance = this;
}
private void MMCMLibrary_reserve_Load(object sender, EventArgs e)
{
}
private void splitContainer1_Panel2_Paint(object sender, PaintEventArgs e)
{
}
private void splitContainer1_Panel1_Paint(object sender, PaintEventArgs e)
{
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
}
private void radioButton1_CheckedChanged_1(object sender, EventArgs e)
{
}
private void btnDCR1_Click(object sender, EventArgs e)
{
}
public void btnDCRoomsReserve_Click(object sender, EventArgs e)
{
if (rbtn9.Checked)
{
MMCMLibrary_home.instance.lbl1_1.BackColor = System.Drawing.Color.Red;
}
}
}
}
Can you help me to device an efficient way to solve this. Can you also suggest a database method suitable for my beginner project.
You've said that:
the background change will always be applied to Discussion Room 1
Well, yes. It seems you don't pass specific object into Form2. There's strightforward:
MMCMLibrary_home.instance.lbl1_1.BackColor = System.Drawing.Color.Red;
So you'll be always changing backcolor of lbl1_1 of your Form1. What needs to be done is to indicate which room has been selected. You can assign room after you click the button by passing the int parameter:
public void btnDCR1_Click(object sender, EventArgs e)
{
var reserveDCR1 = new MMCMLibrary_reserve(1);
reserveDCR1.Show();
}
or:
public void btnDCR2_Click(object sender, EventArgs e)
{
var reserveDCR2 = new MMCMLibrary_reserve(2);
reserveDCR2.Show();
}
Then, in Form2, at the very top, add something like:
int room; to be able to assign the room number in Form2:
public MMCMLibrary_reserve(int roomNumber)
{
InitializeComponent();
room = roomNumber;
instance = this;
}
And then you could just select room you clicked, by:
public void btnDCRoomsReserve_Click(object sender, EventArgs e)
{
if (rbtn9.Checked)
{
if(room == 1)
{
MMCMLibrary_home.instance.lbl1_1.BackColor = System.Drawing.Color.Red;
}
else if(room == 2)
{
MMCMLibrary_home.instance.lbl1_2.BackColor = System.Drawing.Color.Red;
}
else if(room == 3)
{
MMCMLibrary_home.instance.lbl1_3.BackColor = System.Drawing.Color.Red;
}
else if(room == 4)
{
MMCMLibrary_home.instance.lbl1_4.BackColor = System.Drawing.Color.Red;
}
}
else if(radioButton2.Checked)
{
//etc.
}
else if(radioButton3.Checked)
{
//etc.
}
else if(radioButton4.Checked)
{
//etc.
}
}
I think that was the problem. Try it and let us know.
I'm using two buttons for "on" and "off". When I press "On" button, it passes a string value "1", and pressing the "Off" button passes the string value "2".
How can I do this within one button? By default button should be off, when I press it should on and when i press again it should off.
public partial class _Default : System.Web.UI.Page
{
SerialPort ardo;
protected void Page_Load(object sender, EventArgs e)
{
ardo = new SerialPort();
ardo.PortName = "COM5";
ardo.BaudRate = 9600;
}
protected void Button1_Click(object sender, EventArgs e)
{
string stop = "1";
ardo.Open();
ardo.Write(stop);
ardo.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
string On = "2";
ardo.Open();
ardo.Write(On);
ardo.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//consider initially its stopped
if(Session[“currentState”] == null)
Session[“currentState”] = “1”;
if(Session[“currentState”].ToString() == “1”)
{
Session[“currentState”]= “2”;
}
else
{
Session[“currentState”]= “1”;
}
ardo.Open();
ardo.Write(Session[“currentState”].ToString());
ardo.Close();
}
it set to hidden text box.
then you can check if statement it is pressed or not
protected void Button1_Click(object sender, EventArgs e)
{
// hf means hidden textbox
if(hf.text==1){
// your on code
hf.text=0;
}
if(hf.text==0){
//your off code
hf.text=1;
}
}
Declare a string variable
private string isOn = "2";
and then on the button click event you can handle it like
protected void Button1_Click(object sender, EventArgs e)
{
if(isOn.Equals("2"))
isOn = "1";
else
isOn = "2";
}
I am trying to make the text of the button change colour when a checkbox is checked, but for some reason, I just don't know how. Would I need to write an If statement, if so how do I do that?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ColourCheckBox.ForeColor = Color.Red;
}
private void ColourCheckBox_CheckedChanged(object sender, EventArgs e)
{
ColourCheckBox.ForeColor = Color.Black;
}
}
Your question is so obscure, but based on the things that I understand, you should check the Checked property.
private void ColourCheckBox_CheckedChanged(object sender, EventArgs e)
{
if (ColourCheckBox.Checked)
{
ColourCheckBox.ForeColor = Color.Black;
}
else
{
ColourCheckBox.ForeColor = Color.Red;
}
}
In the CheckedChanged event, you can use the Checked property:
ColourCheckBox.ForeColor = ColourCheckBox.Checked ? Color.Black : Color.Red;
In case of a Triple state checkbox, with 3 color you can switch on CheckState value :
Unchecked = 0
Checked = 1
Indeterminate = 2
using System.Drawing;
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
button1.ForeColor = Color.Red;
}
I have two forms, Form 2 is inheriting from Form 1.
What I need to do is that when I close both Form 1 and Form 2 another form which asks if user is sure to quit appears. Then if user clicks Yes, another form which asks if the user wants to save the game appears if and only if the form which the user closes is Form 2 and not Form 1 since for Form 1 there is no saving necessary.
This is what I managed to do:
// These are the Form 1 closing and closed event handlers:
private void GameForm_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
SureClose sc = new SureClose();
sc.StartPosition = FormStartPosition.CenterScreen;
sc.Show();
}
private void GameForm_FormClosed(object sender, FormClosedEventArgs e)
{
MainMenu menu = new MainMenu();
menu.Show();
}
Then in Sure Close: // Please note that Tournament is Form 2 inheriting from GameForm (Form 1)
private void yesButton_Click(object sender, EventArgs e)
{
this.Hide();
if (GameForm.ActiveForm is Tournament)
{
SaveGame sg = new SaveGame();
sg.StartPosition = FormStartPosition.CenterScreen;
sg.Show();
}
else
{
GameForm.ActiveForm.Close();
}
}
private void noButton_Click(object sender, EventArgs e)
{
this.Hide();
}
// This is the SaveGame Form:
private void saveButton_Click(object sender, EventArgs e)
{
// Still to do saving!
}
private void dontSaveButton_Click(object sender, EventArgs e)
{
this.Hide();
GameForm.ActiveForm.Close();
}
The problem is that when in the yesButton event handler in SureClose Form I have GameForm.ActiveForm.Close(), this is going back to the GameForm Closing event handler therefore the SureClose dialog is appearing again.
I tried doing: if (e.CloseReason() == CloseReason.UserClosing)
but obviously it doesn't work either because the reason of closing will always be the user :/
How can I solve this?
Thanks a lot for any help !
Form1 :
private void GameForm_FormClosing(object sender, FormClosingEventArgs e)
{
if(SureClose())
{
SaveChanges();
}
else
{
e.Cancel = true;
}
}
private bool SureClose()
{
using(SureClose sc = new SureClose())
{
sc.StartPosition = FormStartPosition.CenterScreen;
DialogResult result = sc.ShowDialog();
if(result == DialogResult.OK)
{
return true;
}
else
{
return false;
}
}
}
protected virtual void SaveChanges()
{
}
Form2:
protected override void SaveChanges()
{
using(SaveGame sg = new SaveGame())
{
sg.StartPosition = FormStartPosition.CenterScreen;
DialogResult result = sg.ShowDialog();
if(result == DialogResult.OK)
{
//saving code here
}
}
}
SureClose form and SaveGame form:
private void yesButton_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
}
private void noButton_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
}
I have two buttons in my program and i want that when i press first button the second button is clicked automatically ( in the event handler of first button , i want to press the second button through coding).
private void button1_Click(object sender, EventArgs e)
{
passWord = pwd.Text;
user = uName.Text;
loginbackend obj = new loginbackend();
bool isValid = obj.IsValidateCredentials(user, passWord, domain);
if (isValid)
{
loginbackend login = new loginbackend();
passWord = pwd.Text;
login.SaveUserPass(passWord);
HtmlDocument webDoc = this.webBrowser1.Document;
HtmlElement username = webDoc.GetElementById("__login_name");
HtmlElement password = webDoc.GetElementById("__login_password");
username.SetAttribute("value", user);
password.SetAttribute("value", passWord);
HtmlElementCollection inputTags = webDoc.GetElementsByTagName("input");
foreach (HtmlElement hElement in inputTags)
{
string typeTag = hElement.GetAttribute("type");
string typeAttri = hElement.GetAttribute("value");
if (typeTag.Equals("submit") && typeAttri.Equals("Login"))
{
hElement.InvokeMember("click");
break;
}
}
button3_Click(sender, e);
label1.Visible = false ;
label3.Visible = false;
uName.Visible = false;
pwd.Visible = false;
button1.Visible = false;
button2.Visible = true;
}
else
{
MessageBox.Show("Invalid Username or Password");
}
}
private void button3_Click(object sender, EventArgs e)
{
HtmlDocument webDoc1 = this.webBrowser1.Document;
HtmlElementCollection aTags = webDoc1.GetElementsByTagName("a");
foreach (HtmlElement link in aTags)
{
if (link.InnerText.Equals("Show Assigned"))
{
link.InvokeMember("click");
break;
}
}
}
I think what you're describing is that you want to call a method when button B is clicked, but then also call that method when button A is clicked.
protected void ButtonA_Click(...)
{
DoWork();
}
protected void ButtonB_Click(...)
{
// do some extra work here
DoWork();
}
private void DoWork()
{
// do the common work here
}
Depending on your implementation in the event handlers, you can also just call the event handler of the second button from that of the first, but the above way is the 'right' way to do it.
You could just call the method.
private void btnA_Click(object sender, EventArgs e)
{
doA();
}
private void doA()
{
//A stuff
}
private void btnB_Click(object sender, EventArgs e)
{
doA();
doB();
}
private void doB()
{
//B stuff
}
Or call the _Click method directly;
private void btnB_Click(object sender, EventArgs e)
{
btnA_Click(sender, e);
doB();
}
I guess, you don't really care whether the button is clicked or not, you just care that the code of the second button is executed. So... just call it:
void button1_Click(...)
{
button2_Click(...);
}