Automatically show string on form open - c#

I have two forms, the main opens a second form prior to main loading.
On this secondary form I have a textbox to display the logged in username for Windows.
I want this username to show in the textbox when then form opens but currently it only displays when clicking into the textbox and pressing down the spacebar.
I have tried changing the onclick stuff but closet I got was having it load when the cursor went over it.
How can I have the textbox show the username onload or would a label be a better idea?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Chat
{
public partial class loginForm : Form
{
public loginForm()
{
InitializeComponent();
}
private void loginForm_Load(object sender, EventArgs e)
{
string userName = Environment.UserName;
usernametextBox.Text = (userName);
}
private void userloginbutton_Click(object sender, EventArgs e)
{
Application.Run(new chatForm());
Application.Exit();
}
private void usernametextBox_TextChanged(object sender, EventArgs e)
{
}
}
}
Thanks
Daniel

There are plenty of places where you can initialize the value of a textbox.
One common place would be the Form's constructor.
Something like
private void Form2_Load(object sender, EventArgs e)
{
string userName = Environment.UserName;
usernametextBox.Text = (userName);
}
That would be the constructor of the second form, the one that contains the text box.
You can also pass the value to the second form via a constructor parameter or public function if you want the first form to be in charge of prepopulating the username value of the second form after creating it.

private void Form_Load(object sender, EventArgs e)
{
string userName = Environment.UserName;
usernametextBox.Text = userName;
}

if you want to load username on form loading then you should go with FormLoad event of form
or
if you want to load username on focus of textbox then you should go with GotFocus event

Related

How to use variable from another method in a WinForms C# Application

I'm attempting to create a simple WinForms application written in C# that:
Takes user input from a text box.
Uses the data from that text box, and stores it in a user_command variable, which is then used in a method that runs the string in that variable in windows cmd.
E.g: I enter "calc.exe" in the text box. The program then passes that into cmd, therefore opening the calculator.
I am unaware of how I use that data from that text-box and put it into System.Diagnostics.Process.Start("CMD.exe", user_command);
I will leave all the code below:
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace gui_1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
string user_command = textBox1.Text;
}
private void textBox1_TextChanged(object sender, EventArgs e, string user_command)
{
System.Diagnostics.Process.Start("CMD.exe", user_command);
}
}
}
The errors I get are:
Error CS0123 No overload for 'textBox1_TextChanged' matches delegate 'EventHandler' gui_1
The problem here is you put a third parameters on your textBox1_TextChange eventhandler which causing you the error.
I suggest you put the System.Diagnostics.Process.Start("CMD.exe", user_command); on to the button1_Click event, and remove the 3rd parameter on your textBox1_TextChange.
When you click the button1 it will run the CMD.exe with the user_command as argument.
namespace gui_1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
string user_command = textBox1.Text;
System.Diagnostics.Process.Start("CMD.exe", user_command);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
EDIT:
executing different process with arguments.
try to type on your textbox1 before clicking the button1 c:\test.txt.
this will try to open test.txt file on your drive c: on the notepad and ask you if you want to create the file if it is not existing.
public void button1_Click(object sender, EventArgs e)
{
string user_command = textBox1.Text;
System.Diagnostics.Process.Start("notepad.exe", user_command);
}
EDIT2:
executing CMD.exe to execute the parameter.
/c argument will execute the arguments entered on textbox1 upon starting the CMD.exe
public void button1_Click(object sender, EventArgs e)
{
string user_command = textBox1.Text;
System.Diagnostics.Process.Start("CMD.exe", "/c " + user_command);
}
The eventargs (e) should contain the value in the checkbox. put a breakpoint and inspect it. I am sure you will find the text in there.
Remove your third parameter to start matching the overload again !
I hope this code is for educational purposes since it will open a huge gap in the security of the server it is running on.

Resetting Modal Form When Closing C# Windows Forms App

I am writing a C# Windows Forms App Online Store GUI that interfaces with a database. One of the things I have to do is handle customers that are already in the database. From the main menu form they click the 'Returning Customer' button, and enter their email and password. The data entered is then checked against the customers stored in the database, and if it's verified, their user information is filled into text boxes (Name, Credit Card info, CVS, etc...) and the order form becomes visible. I have no issues there. The issue I'm having is that if a returning customer successfully logs in, then cancels out back to the main menu, the next person to click the 'Returning Customer' button pulls up the form with the first user's information already filled in and visible, since both the this.Close() and the this.DialogResult = DialogResult.Cancel methods both only hide the form rather than actually close and free it. But then if I use this.Dispose() on the Returning Customer Form to free it, it can't be reopened.
My question is: is there an easy way to handle this? I'm self taught in C# so forgive my inexperience. Thank you for any help you can give.
Per request see Form1 (Main Menu Form) code below:
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Database_Interface_Project
{
public partial class Form1 : Form
{
// Removed SqlConnectionString for security purposes.
public SqlConnection cnn = new SqlConnection(connectionString);
// Main Menu Form
public Form1()
{
InitializeComponent();
}
// New Customer Form
Form2 newCustomer = new Form2();
private void newCusButt_Click(object sender, EventArgs e)
{
newCustomer.ShowDialog();
}
// Returning Customer Form
ReturningCustomer returningCustomer = new ReturningCustomer();
private void RetCusButt_Click(object sender, EventArgs e)
{
returningCustomer.ShowDialog();
}
private void exitButt_Click(object sender, EventArgs e)
{
this.Close();
}
// Manager Menu Form
Manager managerMenu = new Manager();
private void managerButt_Click(object sender, EventArgs e)
{
managerMenu.ShowDialog();
}
}
}```
You just need to re-instantiate returningCustomer form in order to reset its fields.
private void RetCusButt_Click(object sender, EventArgs e)
{
using (var returningCustomer = new ReturningCustomer())
{
returningCustomer.ShowDialog();
}
}
Using statement calls Dispose() automatically after the using-block is left.
Note: In your case you need to dispose ShowDialog appropriately to avoid GDI leak, since it has side effect of keeping the GDI objects alive.

Check if all elements on a form is fully loaded C#

I am developing a C# application using Visual Studio 2015
it has 2 forms, on form1 I have a button that when clicked
shows form2, now what I would like to do is print form2
after it has fully loaded, I am using the printform control
on form2 to do this, if I use this on the the form_load event
it prints a blank page and then shows the form, I have
also tried using it on form_Shown, however this prints a box
where the elements are but not the element itself as if they have
not finished loading, there is probably a better way to do this
but I am new to C# so still learning
Below is an example of the code that I have on form2
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MyApp
{
public partial class Form2: Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
this.Shown += new System.EventHandler(this.Form2_Shown);
}
private void Form2_Shown(object sender, EventArgs e)
{
printForm.Print();
}
}
}
The Shown event fires a wee bit too early. The form's frame and background is painted but the rest follows later. Painting is a low priority task that occurs only when nothing else needs to be done, firing the Shown event happens first.
The workaround is simple, just ask the form to finish updating itself by calling its Update() method. Fix:
private void Form2_Shown(object sender, EventArgs e)
{
this.Update();
printForm.Print();
}

button in c# not firing

I am writing a simple code it has 3 buttons 2 that will need to open up other forms and one to close the program. When i start the program the exit button will not work even though i have it coded the same as any other time i have wrote a program.
When i press any of the buttons nothing happens. Im not 100% sure how to use the buttons to open another form but i know the exit button should work as is.
Here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace _3343_ParksJ_Lab02
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void workerButton_Click(object sender, EventArgs e)
{
WorkerForm workersForum = new WorkerForm();
}
private void suppervisorButton_Click(object sender, EventArgs e)
{
SupervisorForm workersForum = new SupervisorForm();
}
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
You have to subscribe your buttons' click events to the event methods before they'll fire correctly.
You can check the Designer.cs file to see if this has already been done, though I'm guessing it hasn't. You'll be looking for something like this:
this.workerButton.Click += new System.EventHandler(this.workerButton_Click);
One way to do so is directly in the constructor:
public MainForm()
{
InitializeComponent();
workerButton.Click += workerButton_Click;
suppervisorButton.Click += suppervisorButton_Click;
exitButton.Click += exitButton_Click;
}
Normally, I'd do this through the designer. Select each Button in turn, then open the properties panel and double-click on the event you wish to subscribe to, which will create the corresponding event method in the code-behind for you.
Look at .Designer.cs file and make sure your button is adding the correct delegate method. In your case it should exitButton_Click.
Sometimes when you change names of a button VS designer does not make the name change correctly in the .Designer file. Very rare but it happens.

Problem logging in programatically to a website using WebBrowser Control

I'm trying to login programatically to https://www.salesgenie.com/Account/LogOn using WebBrwoser control.
The problem is when I click on "Log On", the browser doesn't navigate to the next page in the LogonCompleted event.
HtmlElement userName = wBrowser.Document.GetElementById("username");
userName.SetAttribute("value", SomeUserName);
HtmlElement password = wBrowser.Document.GetElementById("password");
password.SetAttribute("value", SomePassword);
wBrowser.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(LogonPageLoaded);
wBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(LogonCompleted);
HtmlElement logonForm = wBrowser.Document.GetElementById("logon-submit");
logonForm.InvokeMember("click");
I think this is because the element "logon-submit" calls a JavaScript function or so.
Please, any help would be appreciated.
Check out your 4th line, you're setting userName again when you should be setting password
EDIT
Besides the problem above I'm guessing that you're trying to invoke the click too soon. The button is created using JavaScript so you have to wait a bit before clicking it. Unfortunately there's no event that you can listen for to determine when the JavaScript is done although you could test various properties probably. The safest thing is to probably just wait a couple seconds after load before invoking click.
The code below works for me (although I don't have a valid username and password). I've got one button called button1 and one webbrowser called webBrowser1. Once the page is visually loaded in the browser clicking the button on the form correctly invokes the click event in the browser.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.webBrowser1.Navigate("https://www.salesgenie.com/Account/LogOn");
}
private void button1_Click(object sender, EventArgs e)
{
string SomeUserName = "Test";
string SomePassword = "Test";
HtmlElement userName = webBrowser1.Document.GetElementById("username");
Console.WriteLine(userName.GetAttribute("value"));
userName.SetAttribute("value", SomeUserName);
userName.RemoveFocus();
HtmlElement password = webBrowser1.Document.GetElementById("password");
Console.WriteLine(userName.GetAttribute("value"));
password.SetAttribute("value", SomePassword);
HtmlElement logonForm = webBrowser1.Document.GetElementById("logon-submit");
logonForm.InvokeMember("click");
}
}
}
Did you try using logonForm.click(); ? Without invoking any member ?

Categories