Text not showing in a label when clicking on a button - c#

I am having trouble with a project I am working on that involves clicking on a button, and text is supposed to show up in a label box I created. I know this would be easier using a text box to show the text when I click on the button but my instructor wants us to use a label instead to show the text. I have debugged the project and everything says it is fine, but when I click on one of my buttons at the bottom, the text does not show up in the assigned label. Below is the code I am using. Maybe I am missing something. For example, when I click on customer relations button, it should show the department in one label, the contact name in the next, and the phone number in the next. I hope that is enough information
private void btnCustomerRelations_Click(object sender, EventArgs e)
{
lblDepartment.Text = "Customer Relations";
lblContact.Text = "Tricia Smith";
lblPhone.Text = "500-1111";
}
private void btnMarketing_Click(object sender, EventArgs e)
{
lblDepartment.Text = "Marketing";
lblContact.Text = "Michelle Tyler";
lblPhone.Text = "500-2222";
}
private void btnOrderProcessing_Click(object sender, EventArgs e)
{
lblDepartment.Text = "Order Processing";
lblContact.Text = "Kenna Ross";
lblPhone.Text = "500-3333";
}
private void btnShipping_Click(object sender, EventArgs e)
{
lblDepartment.Text = "Shipping";
lblContact.Text = "Eric Johnson";
lblPhone.Text = "500-4444";
}

Did the project compiled without any errors ?.
By default every Event Handler in C# is declared as void,which I am unable to find in your code.Did you modify the Event Handlers generated by Visual Studio,if this is the case then the issue you are facing is because of this.
Let me explain what would have gone wrong;
Whenever you create a Event Handler for any control using the Properties Window of Visual Studio,for the sake of this explanation let me take example of TextBox.Suppose you have a TextBox (named as textBox1,which is default) and you subscribe to its TextChanged Event (to do that locate TextChanged event in the events window of Visual Studio and double click it,when you do that Visual Studio generates this for you;
private void textBox1_TextChanged(object sender,EventArgs e)
{
}
This is what we programmers call an Event Handler,now locate Solution Explorer Window in Visual Studio click on Form1.Designer.cs you will get a lot of code there,locate the line which says
private System.Windows.Forms.TextBox textBox1;
where textBox1 is the control's name.Locate a plus sign above this point,click it and locate the following code;
//
// textBox1
//
this.textBox1.AcceptsReturn = true;
this.textBox1.Location = new System.Drawing.Point(478, 0);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(359, 23);
this.textBox1.TabIndex = 1;
this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
PS:The Location , AcceptsReturn , Size and TabIndex property in yours might not be same as mine.
Read the last line of this code,it says;
this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
where textBox1_TextChanged is the name of event which must be same as that defined in Form1.cs.If you modify this you'll get various compile time errors.
So now I guess you know what is the relationship between Form1.cs(main code file) and Form1.Designer.cs(code behind file).
In one line the conclusion is that make sure ;
Any event handler function in Form1.cs starts with private void ....,and the words after private void are exactly same as defined in the code behind file for that particular control.If you would like to read more about this stuff,have a look here.
Hope it would have helped you to solve the issue.Anything else left please inform me.

Have you tried inserting an Application.DoEvents() statement at the end of each method? Sometimes forms are finicky about updating labels and that method will force the form to redraw itself.

Related

How to prevent an event from being executed on form load

I have the following code when loading the form
private void LlenarCampos()
{
NombreProducto.Text = productos.Nombre;
ID.Text = productos.Producto_ID.ToString();
Codigobarrafrm.Text = productos.CodigoBarra;
Existenciafrm.Text = productos.Existencia.ToString();
precio1frm.Value = (decimal)productos.Precio1;
beneficio1frm.Value = (decimal)productos.Beneficio;
Costo.Value = (decimal)productos.Costo;
Existenciafrm.Enabled = false;
ComboCategoria.SelectedItem = CategoriaYPresentaciones.Categoria.fromid(productos.Categoria_ID).Nombre;
}
This code is in charge of filling all the fields of my form as such, but I have two textboxes that, when the EditValueChanged event is executed, make a calculation, how can I prevent this event from happening until the form is filled with the data from the database data and user make the changes?
This is the textbox code:
private void precio1frm_EditValueChanged(object sender, EventArgs e)
{
decimal beneficio = (precio1frm.Value - Costo.Value);
beneficio1frm.Value = (beneficio / Costo.Value) * 100;
}
You are not showing where you define the event handler, so I assume you are letting the designer do this via the Windows Forms IDE. So if you look at events for your textbox in designer, you see it there.
What that does, is create this code (or similar):
precio1frm.EditValueChanged += precio1frm_EditValueChanged;
Find that code (if not sure where it is, right-click the definition for precio1frm_EditValueChanged and choose 'Find all References' or click on the 'references' link just above it. Cut it from there and paste it at the end of your Form Load code. Repeat for each of the controls as required.
That means the event handler won't be fired until after form load is complete

How to switch tabs with button in a TabControl?

I've watched a few tutorials online on how to change tabs using buttons but for some reason all the code I've tried doesn't work. I am currently running Microsoft Visual Studio 2017 and am trying to write some code for a button to change tabs.
I couldn't find any differences between my code and code shown in tutorials, so it may just be a Visual Studio setting that I haven't set up correctly to allow the button correctly, but I couldn't figure out if or where it may be.
Here's my current code:
//Element event handlers
public Form1()
{
InitializeComponent();
}
private void buttonStart_Click(object sender, EventArgs e)
{
tabControl.SelectedTab = DestSelect;
}
private void buttonGotoIntro_Click(object sender, EventArgs e)
{
tabControl.SelectedTab = Intro;
}
//An old computer-generated segment code for the previous button.
//When I try to remove it the computer gets mad at me.
private void GotoIntro_Click(object sender, EventArgs e)
{
}
Please confirm you have subscribed to the Click event for the buttons.
public Form1()
{
InitializeComponent();
buttonStart.Click += buttonStart_Click;
buttonGotoIntro.Click += buttonGotoIntro_Click;
}
Instead of 'tabControl.SelectedTab = DestSelect;" try instead the method 'tabControl.SelectTab(DestSelect);'
I read through this article to find your (hopefully) answer:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/2cf22896-c5bd-4a9b-ab61-34404b55ef01/how-to-jump-to-a-specific-tab-in-the-tabcontrol?forum=vbgeneral
I assume u want to select a tab when a different Button is clicked.
tabControl.SelectedIndex = [Index of tab to switch to];
Code should look like;
tabControl.SelectedIndex = feeTabIndex;
If this is not clear enough, tell me exactly what you want to do.

Button click event not responding c#

The problem we are having is accessing the click event for a button which is created in the click event of another button i.e. clicking the first button generates a new panel and controls, and we now want the button on this newly created panel to perform an action.
The controls have been declared at the top of the class as follows:
Panel createElementPage = null;
TextBox elementDescription = null;
TextBox elementName = null;
Button continueButton = null;
AuditSystem audit;
Here is an excerpt of the method that generates the new panel, the part that defines the continueButton is written as follows:
public void CE_Click(object sender, EventArgs e)
{
createElementPage.Controls.Add(elementDescription);
continueButton = new Button();
continueButton.Text = "Continue";
continueButton.Location = new Point(700, 500);
continueButton.Size = new Size(100, 50);
createElementPage.Controls.Add(continueButton);
}
We want to access the continueButton's click event handler but the method we have written does not seem to be working. This is what we have so far:
private void continueButton_Click(object sender, EventArgs e)
{
Console.WriteLine(" something");
}
Clicking the button yields no results, and we have tried a few solutions such as implementing a seperate eventHandler method. Does anybody have a fix for this?
You have to actually subscribe to the event:
continueButton.Click += continueButton_Click;
Events need to be told what they should handle. Without that, they won't "listen" to anything.
Friendly note: be careful when adding handlers "on demand" like this (i.e. outside of the designer). It doesn't really apply here (you have a new button each time), but it's fairly easy to accidentally subscribe to a control's event multiple times, and your handler will fire multiple times as a result. It's just nice to be aware of :)

Create a submit button when I press Add, multiple events under one button

Any idea how I could make a click event create another button with different click event?
I have a WPF app to make using EF. So I'm stuck at the part where I need to press button "Add" which will freeze other buttons and then create another button "Submit" with code for adding data to the table. I have tried some advice from msdn, but it doesn't work. Here is the code (previously in XAML added a button named b1):
public partial class RoutedEventAddRemoveHandler {
void MakeButton(object sender, RoutedEventArgs e)
{
Button b2 = new Button();
b2.Content = "New Button";
// Associate event handler to the button. You can remove the event
// handler using "-=" syntax rather than "+=".
b2.Click += new RoutedEventHandler(Onb2Click);
root.Children.Insert(root.Children.Count, b2);
DockPanel.SetDock(b2, Dock.Top);
text1.Text = "Now click the second button...";
b1.IsEnabled = false;
}
void Onb2Click(object sender, RoutedEventArgs e)
{
text1.Text = "New Button (b2) Was Clicked!!";
}
I even tried the most obvious solution to simply create another button with click event directly in click event.
I would recommend an alternative approach and put the submitbutton in your xaml code right away but make it so that it is invisible and disabled.
Then in the event handler you simply have to make it visible and enable it.
Your event handler that handles the submit, the dynamic creation of the button, hooking it in the form and such can all be avoided and don't have to be done at runtime.
This will result in a lot better readable code and maintainable code than your original approach unless you have a very good reason for it.
I have done the following coding and it is working for me
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
Button oButton = new Button();
oButton.Name = "btnMessage";
oButton.Content = "Message Show";
oButton.Height = 50;
oButton.Width = 50;
oButton.Click += new RoutedEventHandler(oButton_Click);
//root is a stack panel
root.Children.Insert(root.Children.Count, oButton);
DockPanel.SetDock(oButton, Dock.Top);
}
void oButton_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello World !");
}

How to connect text change event in multiple text boxes to a single method (C#)?

When I double click on my text boxes in the designed, it creates a method auto-magically for me. Since I wish the same things to occur in any of the cases, I simply call an auxiliary method from each, like in the code below.
private void TextBox_1_TextChanged(object sender, EventArgs e)
{
TextChanged();
}
private void TextBox_2_TextChanged(object sender, EventArgs e)
{
TextChanged();
}
private void TextChanged(object sender, EventArgs e) { ... }
Now I'd like to know if there's a way (other than going into my design file (which, according to the information in it, shouldn't be attempted to) to connect the actions listeners to the same method and skip the detour via the automatically generated ones.
On the designer page go to the events tab, find the event you are looking for (TextChanged) and manually enter the name of the event handler you wish them all to use.
I usually proceed like this in my projects, if controls are not going to change at runtime (i.e. if all controls in the form are added at design time):
// this is the container's ctor
public MyForm()
{
TextBox1.TextChanged += new EventHandler(UniqueHandler);
TextBox2.TextChanged += new EventHandler(UniqueHandler);
...
TextBoxN.TextChange += new EventHandler(UniqueHandler);
}
void UniqueHandler(object sender, EventArgs e)
{
TextBox source = (sender as TextBox);
// handle the event!
}
If controls will change, it's actually quite similar, it just doesn't happen in the ctor but on-site:
// anywhere in the code
TextBox addedAtRuntime = new TextBox();
addedAtRuntime.TextChanged += new EventHandler(UniqueHandler);
MyForm.Controls.Add(addedAtRuntime);
// code goes on, the new textbox will share the handler
In the properties fold-out (most often to the right of your screen) you should have a thunder icon. That's where all the events are referable.
If you don't see the properties, select the regarded component (the text box in your case), right-mouse it and pick "properties" in the context menu.
You can do it by this way:
void btn1_onchange(object sender, EventArgs e)
{
MessageBox.Show("Number One");
}
void btn1_onchange2(object sender, EventArgs e){
MessageBox.Show("Number Two");
}
public MyForm() {
Button btn1 = new Button();
btn1.Text = "Click Me";
this.Controls.Add(btn1);
btn1.TextChange += new EventHandler(btn1_onchange);
btn1.TextChange += new EventHandler(btn1_onchange2);
}
You could do it in designer view. Instead of double-clicking on an element - go to your buttons' properties, select events tab and then put a proper handler name for adequate event. Voila!
Follow these steps:
Go to the InitializeComponent().
There are three events attached to each text box.
There you shoud be able to see the following.
this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
this.textBox2.TextChanged += new System.EventHandler(this.textBox2_TextChanged);
Replace this with
this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
this.textBox2.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
And then remove the method below
private void TextBox_2_TextChanged(object sender, EventArgs e)
{
TextChanged();
}

Categories

Resources