How to Hide and Show a button with if statements c# - c#

I am trying to make a button visible = false if a quantity in a text box is less than or equal to 0. The problem I am having is that you have to click the button in order to activate the function.
Here is my code so far
int quantity = int.Parse(textBox33.Text);
if (quantity <= 0)
button13.Visible = false;
if (quantity > 0)
button13.Visible = true;
do I have to disable the visibility of the text box beforehand?

Simply go to the form editor and double click on the textbox. In the code presented to you after double clicking add your code or double click on the form itself if you want the code to be executed whenever the form is loaded.

At first you should encapsulate the code to update the button in a specific method:
private void UpdateButton13()
{
button13.Visible = quantity > 0; // no need for if/else
}
Then you can call this from every event after which the button should be updated. From your comments it seems you want to update that button
at Form load and
when the text in textBox33 has been changed.
So for example:
public class YourForm : Form
{
public YourForm()
{
InitializeComponents();
// register event handlers:
Load += YourForm_Load;
textBox33.TextChanged += textBox33_TextChanged;
}
private void YourForm_Load(object sender, EventArgs e)
{
UpdateButton13();
}
private void textBox33_TextChanged(object sender, EventArgs e)
{
UpdateButton13();
}
private void UpdateButton13()
{
button13.Visible = quantity > 0; // no need for if/else
}
}
Of course you can also create and register the event handlers in the designer window, without having to write the code in the constructor yourself.
The code above may now seem a little redundant (same code in two methods and a one-line method). But I assume that you want to do further things on loading the form and on changing text, and maybe you want to call UpdateButton13 from other parts of your code, too. So encapsulating here is good style (imho) to avoid problems for further development.

go to textbox events and insert the code to textChanged event.
but for better than that you can do digit validation event
private void textBox33_KeyPress(object sender, KeyPressEventArgs e)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "[1-9]"))
{
e.Handled = true;
}
}
in that case order can be only positive number

Related

Enable WindowsForms button property wont work

i have a windows forms app which i want a certain button to change to enable if the textbox is not empty i tried to compare it to string.Empty but it wont work so i decided to compare to TextLength wont work either ..
Code down below:
private void Form1_Activated(object sender, EventArgs e)
{
if (firstDisplayTxtBox.TextLength > 0)
{
plusButton.Enabled = true;
}
}
mayble i place the if statement in the wrong method Let me know where i am wrong Big Thanks for helpers
Probably, you want to use TextChanged event, which fires every time when text in your firstDisplayTxtBox is changed.
public Form1()
{
InitializeComponent();
firstDisplayTxtBox.TextChanged += OnTextChange;
}
private void OnTextChange(object sender, EventArgs e)
{
plusButton.Enabled = firstDisplayTxtBox.Text.Length > 0
}
or

Automatic insertion of rows to DataGrid View without using a timer in Winforms

A row is to be automatically added in a datagridView of Winforms according to value changes in a text box.
A text box (textBox1) is used in the form to input the value. With the change in the value a row is to be inserted in the datagridview (dataGridView1)
I have used the following code for implementing the same,
private void timer1_Tick(object sender, EventArgs e)
{
int value;
value = Convert.ToInt32(textBox1.Text);
if(value == 2)
{
string[] row1 = {"Value is 2"};
dataGridView1.Rows.Add(row1);
}
}
The result I was expecting to get was a single row inserted in the dataGridView1.
I am getting the same row inserted a number of times since the code is running continuously inside the timer, timer1.
Can anyone help me with getting the expected result?
Can it be done without using a timer?
The usual approach would be to subscribe to the TextBox.TextChanged event:
//maybe in the form constructor
textBox1.TextChanged += HandleTextChanged;
Then you would need to implement a method HandleTextChanged somewhat like this (in the same class):
private void HandleTextChanged(object sender, EventArgs e)
{
if(int.TryParse(textBox1.Text, out var number))
{
if(number == 2)
{
string[] newRow = { "Value is 2" };
dataGridView1.Rows.Add(newRow);
}
}
}
For further information on events in WinForms, I propose you have a look at the documentation on learn.microsoft.com. Generally speaking WinForms is event-driven, so it's definitely useful to get used to the concept.
If you want to insert a new row according to the change in TextBox, you can use TextChanged event.
You delegate will be called each time the text is changed.
private void textbox_TextChanged(object sender, EventArgs e)
{
// place your code here for adding a row.
}
The textbox has a multitude of events, which you can inspect in the designer, by clicking it and selecting in the Properties window the yellow flash on the top.
if you want to add your textbox always as row when you finsihed editing the textbox,
use the apropiate event (Leave maybe) and add your row in there.
You could have your timer event tick once and then disable it:
private void timer1_Tick(object sender, EventArgs e)
{
int value;
value = Convert.ToInt32(textBox1.Text);
if(value == 2)
{
string[] row1 = {"Value is 2"};
dataGridView1.Rows.Add(row1);
}
timer1.Enabled = false; //<--disable timer1 once your job is done
}

How to output to a TexBox directly using RadioButtons and CheckBoxes without clicking Buttons

I want to know how to output to a TextBox as soon as a user has clicked on a series of RadioButtons and clicked the CheckBox(es) which are found inside various GroupBoxes on the Form.
Any help will be really appreciated, in case this question has already been answered in the past let me know I have search for it but could not find anything like this.
Sample Form layout:
I am no good at chasing the pictures and especially code as picture doesn't help anyone. Anyway next time please don't do that.
First, for all of your radio and checkboxes (radChocolate, radVanilla, ... radSmall, ..., chkChocoChips, ...) double click and fill Checked event such as:
private void radChocolate_CheckedChanged(object sender, EventArgs e)
{
CalculatePrice();
}
private void radVanilla_CheckedChanged(object sender, EventArgs e)
{
CalculatePrice();
}
// Do the same for other radio and checkboxes
Then add the CalculatePrice code as such (prices are arbitrary):
private void CalculatePrice()
{
decimal price = 0M;
if (radChocolate.Checked) price += 75M;
if (radVanilla.Checked) price += 65M;
if (radStrawberry.Checked) price += 55M;
if (radSmall.Checked) price += 20M;
if (radLarge.Checked) price += 30M;
if (chkChocoChips.Checked) price += 5M;
if (chkCookieCandy.Checked) price += 4M;
if (chkNuts.Checked) price += 3M;
if (chkFreshFruits.Checked) price += 2M;
txtPrice.Text = price.ToString("C");
}
This would do what you wanted to.
You either need to create an event handler for each radio button, or create a single event handler for all the radio buttons. It would depend on what you are trying to accomplish. For the radio button you would want to subscribe to the CheckedChanged event. Then inside this event you can change the text box.
private void radioButtonChangeText_CheckedChanged(object sender, EventArgs e)
{
//Code here to change text box or call sub
textBox.Text = "Hello world";
}
Based upon your link, you can create one event handler and bind it to all the events. (Link explaining binding)
So, every time any value is changed in your form, only one function gets called.
Then, check the values of every component present in your form and calculate value of your textbox.
Right click on a radio button and the go to properties, there click on "events" (that lightning sign). There is an event there called "CheckedChanged". Double click on the cell next to it to generate the event method.
it will generate a code like this,
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
MessageBox.Show("hi there");
}
you should be able to put any thing you want in there. Assuming you want to show hide the TextBox, you can do it in there.
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
setCheckBoxValue();
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
setCheckBoxValue();
}
private void setCheckBoxValue()
{
int finalPrice = 0;
if (radioButton1.Checked == true)
{
finalPrice = finalPrice + 75;
}
else if (radioButton2.Checked == true)
{
finalPrice = finalPrice + 87;
}
textBox1.Text = finalPrice.ToString("C");
}

Buttons in a Visual Studios form application

Sorry if this is a dumb question, I'm taking an intro to programming class and need a bit of help with this project I'm working on.
I'm trying to write an application that has about 30 buttons. One common thing I want is for all the buttons to turn yellow when clicked. If they're clicked a second time, they change back to the default color. right now I use the code:
private void btn_1_Click(object sender, EventArgs e)
{
btn_1.BackColor = Color.Yellow;
}
But that only turns the buttons yellow, I can't turn them "off" by clicking it a second time.
Also, when I'm creating these button events in VS2010, I end up with 30 different event handlers for each button..Is there a way to get them all to do the same thing without having to write all the repetitive code?
I'm guessing that I would have to write my own buttons class? How would I go about doing that? Do i need to create a class library which inherits Buttons?
Sorry for the noob questions. THanks
If every button has a specific action that needs to be performed, then yes, you need to have a click handler for each; however, you can encapsulate the common behavior in a single method.
For example:
private void btn_1_Click(object sender, EventArgs e)
{
ToggleColor((Button)sender);
//rest of the code specific to this button
}
private void ToggleColor (Button button)
{
if(button.Color==Color.Yellow;
button.Color=Color.Black;
else
button.Color=Color.Yellow;
}
Note that above code is not tested.
Now, if all the buttons do the same thing, you can just set the on click handlers for all of them to be btn_1_Click; for example.
private void btn_1_Click(object sender, EventArgs e)
{
if (btn_1.BackColor != Color.Yellow)
{
btn_1.BackColor = Color.Yellow
}
else
{
btn_1.BackColor = Color.Control;
}
}
this is switching default and yellow
If all buttons do the exact same thing you can assign the same event handler to all buttons (instead of btn_1_Click, btn_2_Click etc... you'd have btton_click) - you can select this handler in the properties of each button.
You don't have to write your own class. You can simply assign all your buttons to the same event handler, like this:
button1.Click += new EventHandler(myEventHandler);
button2.Click += new EventHandler(myEventHandler);
button3.Click += new EventHandler(myEventHandler);
button4.Click += new EventHandler(myEventHandler);
Just keep in mind that your event handler has this signature:
private void myEventHandler(object sender, EventArgs e)
By doing that, all your buttons, when clicked, will trigger the same method.
Now to control the color, what you can do is create a simple property on your form which would hold the last color applied. It could be an enum, then you could simply check its value and apply the other one to the buttons, like this:
// Declare your enum:
private enum Colors { Yellow, Default }
private Colors ActualColor = Colors.Default;
// Write your custom event handler:
private void myEventHandler(object sender, EventArgs e)
{
if (ActualColor == Colors.Default)
{
// Apply yellow to buttons
ActualColor = Colors.Yellow;
}
else
{
// Apply default
ActualColor = Colors.Default;
}
}
In order to keep track whether it is the 'second time' you press the button, you should declare a variable OUTSIDE the method, which indicates whether you already pressed the button or not.
For example:
public bool IsButtonYellow;
private void btn_1_Click(object sender, EventArgs e) {
if(!IsButtonYellow) {
btn.BackColor = Color.Yellow;
IsButtonYellow = true;
}
else {
btn.BackColor = Control.DefaultBackColor;
IsButtonYellow = false;
}
}
Yes:
Create your own button class
Inherit from Button
Implement the handler in your button class and you're done
You can do something simple like this:
public class MyButton : Button
{
private bool _buttonState;
protected override void OnClick(EventArgs e)
{
base.OnClick(e);
if (_buttonState)
{
BackColor = Color.Yellow;
}
else
{
BackColor = Color.White;
}
}
}
Then in your code you can just create as many of these "MyButton" objects as you need, with no code repetition.
To make all buttons use the same event handler in VS2010:
Click once on a button to select it.
In the “properties” window: click on the “lightning” (=events).
Paste the first button’s event name (btn_1_Click) next to “Click”.
Do the same for every button.
As for changing the color:
See answer by killie01.
Good luck.

Hiding datagridviews bug

I have a windows form with a panel on the left, which consists purely of radiobuttons, and a tabcontrol in the middle, with multiple tab pages within it. Each of these individual tabpages have a series of datagridviews within it, which are shown and hidden depending on which radio button you check.
I accomplish this effect by having each of the radiobuttons on the left assigned a CheckChanged event, which loops through all of the controls within the tabpagecontrol.SelectedTab, and calls .Show() on the corresponding datagridview and calls .Hide() on the rest so that only one datagridview is visible at one time.
My problem occurs when i try to programmatically check one of these RadioButtons. Lets say in Method X, I write RadioButtonA.checked = true. This triggers the usual CheckedChange event handling, which loops through all the datagridviews on the currently selected tabpage and calls .Hide() on everything except the one datagridview form that the radiobutton is supposed to bring up and calls .Show() instead. However, on one of these .Hide() calls on the datagridview, it ends up triggering the RadioButtonA.CheckedChange event AGAIN for a second time. When i look at the sender argument passed to the function, it shows that the sender is the RadioButton i just programmatically clicked on.
I am adding these datagridviews programmatically and can confirm that there are no eventhandlers assigned whatsoever to them. Can anyone help me determine what is causing this additional event to get triggered? Thanks.
For obnoxious change events that trickle through and upset other event handlers on my forms, I've found the only solution is to add a small boolean value:
bool radioIng;
void MyMethod() {
radioIng = true;
try {
radioButton1.Checked = true;
// etc.
} finally {
radioIng = false;
}
}
void radioButton_EventHandler(object sender, EventArgs e) {
if (radioIng) return;
// rest of code here
}
EDIT:
Alternately, you could just remove all of your event handlers and reconnect them later:
void MyMethod() {
try {
radioButton1.CheckChanged -= radioButton_EventHandler;
radioButton2.CheckChanged -= radioButton_EventHandler;
radioButton3.CheckChanged -= radioButton_EventHandler;
// execute your code
radioButton1.Checked = true;
} finally {
radioButton1.CheckedChanged += new EventHandler(radioButton_EventHandler);
radioButton2.CheckedChanged += new EventHandler(radioButton_EventHandler);
radioButton3.CheckedChanged += new EventHandler(radioButton_EventHandler);
}
}
void radioButton_EventHandler(object sender, EventArgs e) {
if (sender == radioButton1) {
// code here to handle
} else if (sender == radioButton2) {
// code here to handle
} else if (sender == radioButton3) {
// code here to handle
}
}

Categories

Resources