Create a void method for each button - c#

Hi im hoping someone can assist im still new to programming and this is a noob question but i have created a Visual studio - C# (Windows Form Application) and now the question reads to Create a void method for each of my buttons i created in the form and telling me even what to name the method.
but on my research The void keyword is used in method signatures to declare a method that does not return a value.
LinkToAddresses () will be my void method for address the (button), so my question is do i just put in this void method and its going to do nothing?
im just going to link the full question maybe im just really not understanding this>?
''
The below form will represent the main form from which the user will navigate to the other forms. Meaning each button should be linked to the appropriate form. E.g. If button Manage Addresses is clicked the form managed addresses should be displayed. The Exit button should successfully terminate the program.
Create a void method for each button and name them as follow: LinkToAddresses (), LinkToCustomers (), LinkToDrivers (), LinkToStatus (), and LinkToFreight (). The methods should be called under the appropriate button. For the exit button create a void method named AppExit () this should terminate the program.
''
I would appreciate any help or guidance, thank you in advance.

Visual studio usually handles the button actions easily. Just place the buttons on your form, then rename the buttons to LinkToAddresses, LinkToCustomers, LinkToDrivers, LinkToStatus, LinkToFreight and AppExit. Then simply just double click on the each button and visual studio will create a void method for their click event.
using System;
using System.Windows.Forms;
namespace YourApp
{
public partial class FormMain : Form
{
private FormManagedAddresses formManagedAddresses = null;
public FormMain()
{
InitializeComponent();
}
private void LinkToAddresses_Click(object sender, EventArgs e)
{
if (formManagedAddresses != null)
{
formManagedAddresses.Close();
}
formManagedAddresses = new FormNews();
formManagedAddresses.Show();
}
private void AppExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}

The closest thing to a buttons function, is the Click Event Handler. While specific names vary based on Display technology (WinForms, WPF/UWP, ASP.Net), that is the general pattern for Graphical User Interfaces. It is called event driven programming. Even things that have a different programm flow like Games and Web Applications usually try to imitate it.
The signature of a event is given during its definition and must be strictly followed. Usually void NameOfTheEvent(object sender, SampleEventArgs e).
A return type of void is extremely common with events. If there is to be any output, that usually is handeled via a property in the Event Args or by directly doing stuff with the other GUI Elements.
If you want a button to do nothing, you just never give it a event handler. Every single button you ever used, was given a implicit or explicit event handler to do exactly what it did. If you want it to conditionally do nothing, either disable the Button so it can not be clicked, or put a proper if-statement into the event Handler.
A advanced topic would be the command pattern, where there is a bunch of commands in code behind. And each button, menu item and key combination is meerely a way to trigger said command - a representation for hte user to call the command.
You can share a single event across any number of Elements. AS you can see above, the pattern for events includes object sender as argument. This means you can check if it is a specific Button instance that called the event. Or even "unpack" the specific button, do look at stuff like Display String, Tag to get data from it. However, as a general rule retrieving data from the GUI is a bit frowned - ideally the GUI should only represent the data in the backend.

Related

Setting description of an item in Visual Studio -and- changing what "this" refers to

I'm working in Visual Studio 2010 and I'm dealing with C#; I've made a statusStrip that I intend to use as my tool-tip viewer, its .text attribute changing depending on the control the mouse has entered. I've got two textBoxes and I'm trying to make it such that entering the control fires a function called tooltipEnter, and leaving it fires a function called tooltipLeave. Here's my code for those two functions:
private void tooltipEnter(object sender, EventArgs e)
{
toolStripStatusLabel1.Text = this.AccessibleDescription;
}
private void tooltipLeave(object sender, EventArgs e)
{
toolStripStatusLabel1.Text = "Look here for tool-tips regarding the form!";
}
The problem with this is that, first, I'm not sure AccessibleDescription is the right attribute to saddle the description to, and I'm not sure of the most elegant way to do the toolStripStatusLabel1.Text assignment in the first place. Second, this in the program's frame of reference refers to the form on which these controls lay, not the controls themselves; How do I refer uniformly to "the control that just got entered" in a way that allows me to have just the one function for all entries, without having to make different ones for each control?
The problem with this is that, first, I'm not sure
AccessibleDescription is the right attribute to saddle the description
to, and I'm not sure of the most elegant way to do the
toolStripStatusLabel1.Text assignment in the first place.
AccessibleDescription is just some string instance referenced in your form, from this code. The text assignment is done in the only way possible. I'm not sure what your question is regarding this.
Second, this in the program's frame of reference refers to the form on
which these controls lay, not the controls themselves; How do I refer
uniformly to "the control that just got entered" in a way that allows
me to have just the one function for all entries, without having to
make different ones for each control?
sender is always the object from which the event was raised in the EventHandler delegate: msdn.microsoft.com/en-us/library/system.eventhandler.aspx

Windows Forms - using public event to subscribe Form to a user control event

I have an issue when it comes working with events and/or delegates. I saw very similar questions but still the real implementation is not clear to me. So please when you answer be more specific so I can try and eventually understand how exactly creating/handling of public/custom events work by doing it in a code I know.
What I have is a User Control which is simply a text box and a button I need to change a record in a database using the value from the text box. I'm using this control for many forms so I need to know which entity exactly I'm using and be able to call it's own save method. Doing all that will be easier if I just can use the click event of the button from my User Control and then call the Save() method of the current form.
This is my User Control :
namespace UserControls.CommonControls
{
public delegate void ClickMe(string message);
public partial class ChangeCode : UserControl
{
public event ClickMe CustomControlClickMe;
public ChangeCode()
{
InitializeComponent();
}
private void btnChange_Click(object sender, EventArgs e)
{
if (CustomControlClickMe != null)
CustomControlClickMe("Hello");
//ToDo fill
//MessageBox.Show("To Do: Write the busieness logic.");
}
public void SetTextBoxMask(MaskedTextBox txtBox)
{
txtChange.Mask = txtBox.Mask;
}
}
}
I post it with the last attempt I made to try and implement what I need.
This is one of the form that need to use the Click event from the User Control and more specific the Constructor because if I understand right there is the place where I have to subscribe for the event :
public MaterialEdit()
{
InitializeComponent();
UserControls.CommonControls.ChangeCode. += new ClickMe(button2_Click);
}
UserControls.CommonControls.ChangeCode - this is how I reach my User Control it's named ChangeCode.
From what you pasted it is not clear that you added ChangeCode control to your form. To use the control and it's events and properties, first you must create new instance to it and add it to the form. This is done:
In designer, by dragging control from Toolbox to the form
In code editor, by invoking control constructor and adding new object to control collection
Only then can you handle event of that object. Let's say that you dropped ChangeCode control to a form, and that Visual Studio named it ChangeCode1. You attach a handled to CustomControlClickMe event like this:
ChangeCode1.CustomControlClickMe += new ClickMe(button2_Click);
Code you pasted (UserControls.CommonControls.ChangeCode. += new ClickMe(button2_Click);) is incorrect for several reasons:
Syntactically, left hand side expression ends with . which makes it incorrect assignment target (UserControls.CommonControls.ChangeCode.)
Event name is not provided, only the control name (you need to end left hand side of assignment with what you want to assign to - .CustomControlClickMe)
You are trying to attach handler to a class and not an object

Changing button event after button click in C#

I've a form that navigates webpage and access data. It looks like something below.
private void LoginButton_Click(object sender, EventArgs e)
{
if(LoginButton.Text == Login)
{
LoginButton.Text = "Logging in...";
....
...
Login process goes here...
..
if(Login Successed)
{
LoginButton.Text ="Download";
}
else
{
LoginButton.Text = "Login";
}
}
else if(LoginButton.Text==Download)
{
Download data here...
}
}
Same button(And same event too), doing two process and seems like different events with a label.
1) If there any problem like inefficiency run?
2) Any alternate ways to do this like different flag schemes?
3) Any method to have with more than one event for same button to achieve same idea?
Thanks.
1) If there any problem like inefficiency run?
Button clicks run at human time. You can burn half a billion cpu instructions without inconveniencing the user.
2) Any alternate ways to do this like different flag schemes?
Using the Text property of the button is fragile, your code will break when somebody decides to change the button text or when you localize your app to another language. A simple private bool field in your class is much better.
3) Any method to have with more than one event for same button to achieve same idea?
No. You could of course use two buttons, placed on top of each other and one of them always hidden. Makes localization much simpler and you'll get that bool field for free.
like Daniel A. White said
have two buttons
may be on some event like oncreate/onload do check..jst a pseudo code
if process is login then
do
//then showLoginButton
btnlogin.visible
else
//download
btndonload.visible
inside the login button
if(Login Successed)
{
btndonload.visible
}
else
{
LoginButton.Text = "Login";
}
this may be better with two buttons then single..and cleaner also
Write custom event handlers for the mouseClick
Write separate methods for login and download.
Register your custom event handlers to the button click event
I assume there is some logic that decides that the button text should be "download" or "login". At that point, set the button text of course, but also register the appropriate event handler.
This will allow you to have a single button that does anything
protected void Login_MouseClickHandler (object obj ,MouseClickEventArgs e) {
// login logic
// this would be the logic you say is "inside the login button"
}
protected void Download_MouseClickHandler (object obj ,MouseClickEventArgs e) {
// download logic
}
// pseudo code
// note that there is only one button
if process is login then
theButton.text = "login"
theButton.MouseClick += new MouseClickEventHandler(Login_MouseClickHandler)
else
button.text = "download"
theButton.MouseClick += new MouseClickEventHandler (Download_MouseClickHandler)
end if
Software Design Thoughts
Easier to extend. We don't need another button for every new thing to do
Separation of Concerns - All login code, for example, is in a separate method that does only login stuff.
Change is isolated and minimized. Writing new, separate methods is less error prone than in-lining that code in your if else structure. And consequently the if else structure is kept simple and comprehensible.
It is generally a bad idea use the text as the state. Ideally, you should have 2 buttons that fire different events and call out the main logic to a presenter in the MVP pattern.
Use control containers such as Panel and GroupBox. You can have a whole bunch of Panels for controls in different states.

How to distinguish between User Control load on form and load when runtime

I created a user control using C# for windows form application. This user control has some properties. In runtime, if the user does not enter values for this properties I want to show a message box and exit the application.
The problem is when I write the checking code in the Load event of User Control. When I drag & drop it on the form the message box will appear.
private void UserControl1_Load(Object sender, EventArgs e)
{
if (_getFirstPageArgument==null || _getFirstPageArgument.Length==0)
{
throw new Exception("Some Message");
}
}
How do I distinguish between load on the form and load on run time?
I fear there is a larger problem here. But to solve your immediate problem (if I understand correctly...) There is a form attribute called DesignMode. When you are in the visual studio design mode, this will be true. At runtime, this will be false.
For beginners, #Nimas case can be a good study point to understand that Visual Studio actually runs and executes parts of our code even when we are in design time, which is why the constructor is invoked. Even "DesignMode" property is not 100% reliable. You can find an interesting note here related to that http://weblogs.asp.net/fmarguerie/archive/2005/03/23/395658.aspx
If you only want to know when the type itself has been loaded into the runtime (not a specific instance), you can put code into the static constructor for that class.
If I'm misinterpreting your question, please clarify using a timeline when you want specific events to happen.

c# / WPF : Make a Browse for File Dialog

I'm new to WPF and am trying to make my first WPF desktop application using VC# Express.
I'm trying to get make three open file dialogs complete with text fields that show the specified path if the user chooses a file. I found working code to make the dialog box appear at the click of a button, but how do I get a text field to update/bind to the file path?
Something similar to how the file input boxes in HTML work would be ideal.
...
EDIT:
Okay I read the post just below mine and found the solution...
Now, how about redirecting console output to a text field?
To answer your question about redirecting console output:
You'll be better off changing the code to fire an event with the string you wish to output. Then in the UI add a handler for that event and in the handler update the text field.
To declare an event add something like this code in your processing class:
public event EventHandler<StringEventArgs> Process_Message;
where StringEventArgs is a class based on EventArgs that wraps the message for sending.
To fire the event add something like this code in your processing class:
Process_Message(this, new StringEventArgs(message));
To attach a message handler in your UI class:
process.Process_Message += Process_Message;
To handle the event add something like this code to your UI class:
private void Process_Message(object sender, StringEventArgs e)
{
Action action = () => UpdateStatus(e.Message);
{
Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, action);
}
else
{
action();
}
}
You need to do the threading test as the UI can't be updated from a different thread.
Then the UpdateStatus method:
private void UpdateStatus(string message)
{
statusTextBox.Text = message;
}
Obviously you'll need to rename things to be appropriate to your application.
Look up events and EventArgs in the MSDN.
If i understand you correctly
Use the FileDialog.FileName to the the Full path .. and bind that to your text box.
76mel

Categories

Resources