Transfer datafrom one form to an other - c#

I have a C# application with two forms(form1,form2).In form1 on btnTransfer_click I open second form.
private void btnTransfer_Click(object sender, EventArgs e)
{
Form2 frmConn = new Form2 ;
frmConn .Show();
//i need here values from second form
}
In second form I have 2 textboxes (txtUser,txtPassword) and a button (btnOk) .On button btnOk I verify user and password and if are correct i have to come back to first form and get this values on click button.
In Form2 :
private void btnOk_Click(object sender, EventArgs e)
{
//verify if txtUser and txtPassword are correct
//if are corrects i have to send back to first form
this.Close();
}
How can I do This?
Thanks!

In the class for form2, create two public class properties, one for the value of each textbox:
private String _username = null;
public String UserName { get { return _username; } }
private String _password = null;
public String Password { get { return _password; } }
In form2 you can verify and assign to properties:
private void btnOk_Click(Object sender, EventArgs e)
{
//verify if txtUser and txtPassword are correct
if (correct)
{
_username = txtUser.Text;
_password = txtPassword.Text;
}
this.Close();
}
Then you can retrieve them in your form1 code as such:
private void btnTransfer_Click(Object sender, EventArgs e)
{
//This using statement will ensure that you still have an object reference when you return from form2...
using (Form2 frmConn = new Form2())
{
frmConn.Show();
String user = frmConn.UserName;
String pass = frmConn.Password;
if (!String.IsNullOrEmpty(user) && !String.IsNullOrEmpty(pass))
//do something with them, they are valid!
}
}

Usually, it's using a Data Transfer Object:
http://msdn.microsoft.com/en-us/library/ff649585.aspx
Or a Domain Object.
http://msdn.microsoft.com/en-us/magazine/dd419654.aspx

Related

Accessing a list from a second form and adding user input to the list

I have a list called "studentInfo" and I am trying to allow the user to go to a form I created called "addRecord" and type in a student code and a student mark and once they hit submit the data is then added to the list in form1 and then also the data gets added to the listbox in form1.
I don't know how to go about this since I am new to C# so any guidance will be appreciated.
My list is created like this
public static List<string> studentInfo = new List<string>();
Then once my form1 loads I read in from a CSV file to populate the listbox
private void Form1_Load(object sender, EventArgs e)
{
string lines, studentNumber, studentMark;
StreamReader inputFile;
inputFile = File.OpenText("COM122.csv");
while (!inputFile.EndOfStream)
{
lines = inputFile.ReadLine();
studentInfo = lines.Split(',').ToList();
studentNumber = studentInfo[0];
studentMark = studentInfo[1];
lstMarks.Items.Add(studentNumber + " : " + studentMark);
}
inputFile.Close();
}
I want the user to go to the addRecord form, enter in a student code and student mark, then hit submit and then the program asks the user to confirm that the data they have entered is correct and then the user is directed back to form1 and the data will be in the listbox.
Alrighty, in Form addRecord, we create two properties to hold the data to be retrieved from the main Form. This should only be done if addRecord returns DialogResult.OK. I've added in two buttons, one for cancel and one for OK. These simply set DialogResult to their respective results. The property values for the two values to be returned are also set in the OK button handler:
public partial class addRecord : Form
{
public addRecord()
{
InitializeComponent();
}
private string _Student;
public string Student
{
get
{
return this._Student;
}
}
private string _Score;
public string Score
{
get
{
return this._Score;
}
}
private void btnOK_Click(object sender, EventArgs e)
{
this._Student = this.tbStudent.Text;
this._Score = this.tbScore.Text;
this.DialogResult = DialogResult.OK;
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
}
}
Now, back in Form1, here is an example of showing addRecord with ShowDialog(), then retrieving the stored values when OK is returned:
public partial class Form1 : Form
{
public static List<string> studentInfo = new List<string>();
// ... other code ...
private void btnAddRecord_Click(object sender, EventArgs e)
{
addRecord frmAddRecord = new addRecord();
if (frmAddRecord.ShowDialog() == DialogResult.OK)
{
studentInfo.Add(frmAddRecord.Student);
studentInfo.Add(frmAddRecord.Score);
lstMarks.Items.Add(frmAddRecord.Student + " : " + frmAddRecord.Score);
}
}
}
--- EDIT ---
Here's a different version of addRecord that doesn't allow you to hit OK until a valid name and a valid score have been entered. Note that the property has been changed to int, and the TextChanged() events have been wired up to ValidateFields(). The OK button is also initially disabled:
public partial class addRecord : Form
{
public addRecord()
{
InitializeComponent();
this.tbStudent.TextChanged += ValidateFields;
this.tbScore.TextChanged += ValidateFields;
btnOK.Enabled = false;
}
private string _Student;
public string Student
{
get
{
return this._Student;
}
}
private int _Score;
public int Score
{
get
{
return this._Score;
}
}
private void ValidateFields(object sender, EventArgs e)
{
bool valid = false; // assume invalid until proven otherwise
// Make sure we have a non-blank name, and a valid mark between 0 and 100:
if (this.tbStudent.Text.Trim().Length > 0)
{
int mark;
if (int.TryParse(this.tbScore.Text, out mark))
{
if (mark >= 0 && mark <= 100)
{
this._Student = this.tbStudent.Text.Trim();
this._Score = mark;
valid = true; // it's all good!
}
}
}
this.btnOK.Enabled = valid;
}
private void btnOK_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
}
}

Passing values through forms c#

I am building a form application at Visual Studio 2015 in C#. First of all i've made a user login form using 2 textboxes and 1 button. All i want to do is to pass the value from the textbox that contains username to a label which is located to another form which form is called MainMenu. This is my code for the button i made to the login form:
private void button_login(object sender, EventArgs e)
{
MainMenu username = new MainMenu();
username.Value1 = textBox1.Text;
this.Hide();
MainMenu ss = new MainMenu();
ss.Show();
}
and the code for the MainMenu form that i want to pass the value is the following:
private string value1 = string.Empty;
public string Value1
{
set { value1 = value; }
get { return value1; }
}
private void MainMenu_Load(object sender, EventArgs e)
{
label7.Text = Value1;
}
As you can see i have create a property in MainMenu form that is accessible from login form so i could transfer the value from textbox1 directly in your MainMenu form. The problem is that the text in label7 remains empty during runtime and i can't understand why. Am i missing something from my code or i am doing something completely wrong ?
Any suggestions would be appreciated
You actually create two Forms: username and ss. You set Value1 of username, but you show ss which you didn't set its Value1. So you should show username:
private void button_login(object sender, EventArgs e)
{
MainMenu username = new MainMenu();
username.Value1 = textBox1.Text;
this.Hide();
username.Show(); // and not ss.Show();
}
Also, a tip, use better names for your variables. The code below do exactly the same thing but is much more comprehensible:
private void loginButton_Click(object sender, EventArgs e)
{
var mainMenuForm = new MainMenu();
mainMenuForm.UserName = userNameTextBox.Text;
this.Hide();
mainMenuForm.Show();
}
class MainMenu : Form
{
// This is an "Auto-Implemented Property".
// Auto-Implemented Properties are used as a shortcut of what you have done.
// Google them for more information.
public string UserName { get; set; }
private void MainMenu_Load(object sender, EventArgs e)
{
userNameLabel.Text = UserName;
}
}
MainMenu username and MainMenu ss are two distinct instances (of the same MainMenu class, but that's a detail).
You are setting the memeber variable Value1 of username instance but you are displaying ss instance.
Consider this code
private void button_login(object sender, EventArgs e)
{
MainMenu username = new MainMenu();
username.Value1 = textBox1.Text;
this.Hide();
usename.Show();
}
You are using two different MainMenu objects, the right code should be something like
MainMenu username = new MainMenu();
username.Value1 = textBox1.Text;
this.Hide();
username .Show();
Just as a completely different approach to the problem:
Another option is to create a static class in your project that will house any variables that you would like to reuse.
So lets say your static class is call Globals, after successfull login you would set the variable you require ie Globals.Username = textBox1.Text.
Then wherever you need that value again you can access it using Globals.Username.
When you need to pass variable values from one form to another, write the constructor of the second form accordingly and pass the value while creating the object of the second form.
private void button_login(object sender, EventArgs e)
{
MainMenu ss= new MainMenu(textBox1.Text);
this.Hide();
ss.Show();
}
class MainMenu : Form
{
// This is an "Auto-Implemented Property".
// Auto-Implemented Properties are used as a shortcut of what you have done.
// Google them for more information.
public string UserName { get; set; }
private void MainMenu(string userName)
{
this.UserName = userName;
}
}
Creating public properties and accessing them in another class for every instance of the class is bad practice for OOP.

How to pass data from another form and back

I've been trying to get this working. I'm sure I've written in correctely
Form 1
private string _temp;
public string Temp
{
get { return _temp; }
set { _temp = value; }
}
private void button1_Click(object sender, EventArgs e)
{
_temp = "test";
}
Form 2
private void button1_Click(object sender, EventArgs e)
{
Form1 main = new Form1();
MessageBox.Show(main.Temp);
}
You have to get the reference to the Form1 instance via the sender parameter (assuming that Form2's button1_Click handler is attached to a button on Form1):
//Form2
private void button1_Click(object sender, EventArgs e)
{
Button button = (Button) sender;
Form1 main = (Form1) button.FindForm();
MessageBox.Show(main.Temp);
}

Passing Values Between Windows Forms c# [duplicate]

This question already has answers here:
Communicate between two windows forms in C#
(12 answers)
Closed 3 years ago.
I am struggling to work out how to pass values between forms. I have four forms and I want to pass the information retrieved by the Login to the fourth and final form.
This is what I have so far.
In this function:
private void btnLogin_Click(object sender, EventArgs e)
I have deserialized the data I want like this:
NewDataSet resultingMessage = (NewDataSet)serializer.Deserialize(rdr);
Then, when I call the next form I have done this:
Form myFrm = new frmVoiceOver(resultingMessage);
myFrm.Show();
Then, my VoiceOver form looks like this:
public frmVoiceOver(NewDataSet loginData)
{
InitializeComponent();
}
private void btnVoiceOverNo_Click(object sender, EventArgs e)
{
this.Close();
Form myFrm = new frmClipInformation();
myFrm.Show();
}
When I debug, I can see the data is in loginData in the second form, but I cannot seem to access it in the btnVoiceOverNo_Click event. How do I access it so I can pass it to the next form?
You need to put loginData into a local variable inside the frmVoiceOver class to be able to access it from other methods. Currently it is scoped to the constructor:
class frmVoiceOver : Form
{
private NewDataSet _loginData;
public frmVoiceOver(NewDataSet loginData)
{
_loginData = loginData;
InitializeComponent();
}
private void btnVoiceOverNo_Click(object sender, EventArgs e)
{
// Use _loginData here.
this.Close();
Form myFrm = new frmClipInformation();
myFrm.Show();
}
}
Also, if the two forms are in the same process you likely don't need to serialize the data and can simply pass it as a standard reference to the form's constructor.
Google something like "C# variable scope" to understand more in this area as you will encounter the concept all the time. I appreciate you are self-taught so I'm just trying to bolster that :-)
In various situations we may need to pass values from one form to another form when some event occurs. Here is a simple example of how you can implement this feature.
Consider you have two forms Form1 and Form2 in which Form2 is the child of Form1. Both of the forms have two textboxes in which whenever the text gets changed in the textbox of Form2, textbox of Form1 gets updated.
Following is the code of Form1
private void btnShowForm2_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.UpdateTextBox += new EventHandler<TextChangeEventArgs>(txtBox_TextChanged);
form2.ShowDialog();
}
private void txtBox_TextChanged(object sender, TextChangeEventArgs e)
{
textBox1.Text = e.prpStrDataToPass;
}
Following is the code of Form2
public event EventHandler<TextChangeEventArgs> UpdateTextBox;
private string strText;
public string prpStrText
{
get { return strText; }
set
{
if (strText != value)
{
strText = value;
OnTextBoxTextChanged(new TextChangeEventArgs(strText));
}
}
}
private void textBox_Form2_TextChanged(object sender, EventArgs e)
{
prpStrText = txtBox_Form2.Text;
}
protected virtual void OnTextBoxTextChanged(TextChangeEventArgs e)
{
EventHandler<TextChangeEventArgs> eventHandler = UpdateTextBox;
if (eventHandler != null)
{
eventHandler(this, e);
}
}
In order to pass the values we should store your data in a class which is derived from EventArgs
public class TextChangeEventArgs : EventArgs
{
private string strDataToPass;
public TextChangeEventArgs(string _text)
{
this.strDataToPass = _text;
}
public string prpStrDataToPass
{
get { return strDataToPass; }
}
}
Now whenever text changes in Form2, the same text gets updated in textbox of Form1.

Error when accessing a control's data of one form in another form in C#

I have two forms in my application. In my Form1 I have a list view having some items. When I double click on a row, I should get a pop-up window allowing me edit the row values. For this I used doubleclick event. Now for the pop-up window I created new form- Form2. I have made the listview as internal in Form1, so as to access the selected rows values in my form2. In form2 load I am retrieving the values of selected row to display in textboxes but this gives me error. This is my code:
//this is in form1
private void bufferedListView1_DoubleClick(object sender, EventArgs e)
{
form2 obj = new form2();
obj.ShowDialog();
}
//in form2
Form1 o = new Form1();
private void form2_Load(object sender, EventArgs e)
{
txt_editname.Text = o.bufferedListView1.SelectedItems[0].SubItems[0].Text;
txt_editno.Text = o.bufferedListView1.SelectedItems[0].SubItems[1].Text;
}
The error that I get is: InvalidArgument=Value of '0' is not valid for 'index'.
Parameter name: index
Where am I wrong?
Pass needed data in constructor of form2
public form2(string text1, string text2)
{
//work with values
}
And change calling code to this:
private void bufferedListView1_DoubleClick(object sender, EventArgs e)
{
form2 obj = new form2(bufferedListView1.SelectedItems[0].SubItems[0].Text,
bufferedListView1.SelectedItems[0].SubItems[1].Text);
obj.ShowDialog();
}
Form1 o = Application.OpenForms["Form1"] as Form1;
private void form2_Load(object sender, EventArgs e)
{
txt_editname.Text = o.bufferedListView1.SelectedItems[0].SubItems[0].Text;
txt_editno.Text = o.bufferedListView1.SelectedItems[0].SubItems[1].Text;
}
you should retrieve the instance of Form1 which is already created, not a new instance.
Your code should be like this:
//this is in form1
private void bufferedListView1_DoubleClick(object sender, EventArgs e)
{
form2 obj = new form2
{
Name = o.bufferedListView1.SelectedItems[0].SubItems[0].Text,
No = o.bufferedListView1.SelectedItems[0].SubItems[1].Text,
};
obj.ShowDialog();
}
//in form2
public String Name;
public String No;
Form1 o = new Form1();
private void form2_Load(object sender, EventArgs e)
{
txt_editname.Text = Name;
txt_editno.Text = No;
}

Categories