Passing data between C# forms - c#

I am struggling to pass data between two forms (all I want to do is have a textbox in Form1, and show that textbox value in textbox1, which is located in Form2). How would I go about this, using WPF? Have looked at quite a few solutions, but cannot seem to get any of them at all to work.
For the form in which I'm wanting to display the values (in tbd.Text), here is the code:
namespace test
{
/// <summary>
/// Interaction logic for OptionDisplayWindow.xaml
/// </summary>
public partial class OptionDisplayWindow : Window
{
public OptionDisplayWindow()
{
InitializeComponent();
tbd.Text = "k"; //want to change this value based on "s" in the other form
}
The form in which the text is transferred from (want to display the string):
public void Button1_Click(object sender, RoutedEventArgs e)
{
string s = "testText"
}
I have tried every single other answer on SO (spent the past 6 hours trying) and have had absolutely no luck.
EDIT 2: Using the method listed as the best answer here Send values from one form to another form I've come up with this code for Form1:
private void ttbtn_Click(object sender, RoutedEventArgs e)
{
using (Form2 form2 = new Form2())
{
tbd.Text = form2.TheValue;
}
}
And the code for Form2:
public string TheValue
{
get { return arrayTest.Text; }
}
However, I'm getting the error 'Form 2': type used in a using statement must be implicitly convertible to 'System.IDisposable'.

The code that you put in the sample project (that you provided as a link in the comments) should be in your question. Given that it becomes much easier to understand what you're trying to do and to give you a workable solution.
I would suggest creating a "DataTransferObject" and pass that between each form.
public class Dto
{
public string Text;
}
The code in MainWindow would then look like this:
private void button1_Click(object sender, RoutedEventArgs e)
{
var dto = new Dto();
window2 win2 = new window2();
win2.Dto = dto;
win2.ShowDialog();
textBox1.Text = dto.Text;
}
And the code in window2 would look like this:
public Dto Dto;
private void textBox2_TextChanged(object sender, TextChangedEventArgs e)
{
if (this.Dto != null)
{
this.Dto.Text = textBox2.Text;
}
}
That is one way - out of about a million - of transferring data between forms. An advantage of using a data transfer object is that it begins you on the road of separating your data from your UI, and that is generally a very good thing to do.

Another simple way to pass data between forms is using your application's settings.
Step 1: Create a setting, open the "Project" menu and pick "test Properties..."
this will take you to the settings page, create a setting name it however you want, I named mine "PassString" and make sure it's a string type and the Scope is set to user.
Step 2. Lets set the string setting to your textbox.text property, add these changes to the code:
private void button1_Click(object sender, RoutedEventArgs e)
{
Properties.Settings.Default.PassString = textBox1.Text;
window2 win2 = new window2();
win2.ShowDialog();
}
Step 3. Update the text on your second window Initialization Process.
public OptionDisplayWindow()
{
InitializeComponent();
tbd.Text = Properties.Settings.Default.PassString;
}
P.S. you may have to add a reference to reach your application settings.
using test.Properties;

Related

How to import a value from another Form in C# [duplicate]

This question already has answers here:
Passing Values from one Form to another Form in a Button click
(4 answers)
Closed 2 years ago.
Okay, I saw a couple of answers to similar questions but nothing was quite right, so I thought I would write down my own problem. I have a couple of Forms that are supposed to be connected.
private void btnAdd_Click(object sender, EventArgs e)
{
AuthorForm authorForm = new AuthorForm();
authorForm.Show();
}
This is the code from the Form2 that opens once I want to create a new list of Authors. With that, the third Form "AuthorForm" pops up and that's where I want to enter a name to add to a listBox that is in Form2. I don't know how to pass the string from the TextBox to the other form.
I'm sorry if this doesn't make much sense. I'm pretty bad at trying to explain what I need but if you have questions, I'll try to explain better.
Hi and welcome to StackOverflow. There are several ways to achieve this but I believe the easiest would be to use a property in your AuthorForm as follows:
// Inside AuthorForm create the following...
public string AuthorName { get; private set; }
Having done that, you can set this property either in text changed, or when the user clicks to commit the entered text, you then read this property from the Form2.
// This goes inside the text changed off your name text box.
this.AuthorName = AuthorTextBox.Text; // Assuming the name of the textox is AuthorTextBox
Inside Form2 you call read the property as follows.
private void btnAdd_Click(object sender, EventArgs e)
{
AuthorForm authorForm = new AuthorForm();
authorForm.ShowDialog();
// Read the entered text from the property
var userInput = authorForm.AuthorName;
}
You can proceed to make use of the text the user entered after this.
If i'm not mistaken you want to change Form2 instance after authorForm.Show(); statment
You can initial public variable for example name in Form2 and then send all the form2 instance to AuthorForm with constructor (use this keyword) , now you can change variable from form2 in authorForm
see :
AuthorForm authorForm = new AuthorForm();
authorForm.Show(this);
AuthorForm :
Form2 form2;
public AuthorForm(Form2 form2)
{
this.form2 = form2;
}
public void DoSomething()
{
form2.name = "test";
}
If I got it right, you want to get values from from AuthorForm.
You can do that by adding a property to the AuthorForm, like that:
public string AuthorName { get; set; }
And use authorForm.ShowDialog() so all the opened forms will freeze until you use the Close() method in the form you opened as a dialog. And then you can continue the form.
For example:
AuthorForm.cs:
public void BtnClose_Click(object sender, EventArgs e)
{
AuthorName = "rom_totach";
Close();
}
MainForm.cs:
public void BtnOpenAuthorForm(object sender, EventArgs e)
{
AuthorForm form = new AuthorForm();
form.ShowDialog();
MessageBox.Show(form.AuthorName);
}
I hope I helped!

How pass information between forms involving listView item being changed?

I have file manager program that displays folder in a treeView on the left hand side of a form (frmMain) and files in listView on the left side. I want to be able to select a file (item) from the listView then display the file name in a text on another form with the label = 'Enter a file name.' then rename the file with that new name.
Code from the second form.
public frmRename(string oFile)
{
InitializeComponent();
textBox1.Text = oFile;
}
private void bntOK_Click(object sender, EventArgs e)
{
string nFileName;
nFileName = textBox1.Text;
frmMain fm = new frmMain();
fm.re_nameFile(nFileName);
}
This code runs without any errors; however, when uncommented that is presently commented I get error 'Value of zero is not a valid for index'. I know that this error has talked about a lot; however, I am concern with a different aspect of this error. If I use a line of in private function I don't get this error; whereas, if I use it public function I do. First of all I want to understand why this happens? Second can you tell me how to fix the problem?
So in frmMain you create a new frmRename and in frmRename you create a new frmMain. Bad idea. The new frmMain knows nothing about the original frmMain (including its populated listView).
Solution: in frmMain.bntRename_Click call
rename.ShowDialog();
newFileName = rename.nFileName;
do whatever you want to do with the new name and in frmRename define
public string nFileName {get; private set;}
and further change
private void bntOK_Click(object sender, EventArgs e)
{
nFileName = textBox1.Text;
Close();
}

Visual C#: How to add controls to a form created with code?

I'm new to Visual C# and I'm currently stuck on how to create a new form (with code, not design) and add things (namely labels and textboxes) to this new form. Here's what I have right now:
namespace AccountInfo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
profileForm profile = new profileForm(); // Make new form
profile.Name = "newProfile";
profile.Text = "Add a new profile";
profile.LabelText = "test";
profile.Show(); // Display form
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
public class profileForm : Form
{
// Controls
Label label1 = new Label();
public profileForm()
{
}
public string LabelText
{
set { label1.Text = value; }
}
private void profileForm_Load(object sender, EventArgs e)
{
}
}
}
When I run this code, I get the default form and I click button1. It brings up a new form, but with nothing on it. I expect a label to show up but it won't. I've tried this multiple different ways (this being my most recent method) and I can't get anything to show up. I've looked around StackOverflow and one other topic came up, but its solution didn't work for me. I'd appreciate any insight into this :) Thanks a ton!
Edit: I've also tried this using the constructor instead. It didn't help.
You're creating a Label object in memory but you're not assigning it to a particular parent control, or setting it's position etc... Google "Dynamically create controls C#" and you'll find a tonne of examples.
You basically need to call the following two lines from somewhere in profileForm.
label1.Location = new Point(25,25);
this.Controls.Add(label1);
As suggested by Dylan, you need to add the Label object to the profileForm in the load event as follows:
this.Controls.Add(label1);
Soon, i was watching a video that answers to this question.
It is complete guide how to add dinamicly controlls with the flow layout.
Here is the video: http://windowsclient.net/learn/video.aspx?v=13245

Making two boxes equal each other

I am trying to make a text box (UPC_txtBox4) self populate to equal the same value of UPC_txtBox2. The two text boxes are on separate forms but I feel there should be a way to link the two.
If form1 is responsible for navigating to form2, then you can pass the value on the query string from form1 using a URL similar to the following:
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
Response.Redirect(Request.ApplicationPath + "/Form2.aspx?upc=" + UPC_txtBox2.Text, false);
}
}
then in form2 code:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
// Assuming this field is an asp.net textbox and not an HTML input
UPC_txtBox4.Text = Request.QueryString["upc"];
}
}
Alternatively, you could store the value in session state, assuming that you are using sessions.
CORRECTION: Seeing as you are using WebForms, not WinForms as I had assumed, the below is irrelevant. I'll leave it just incase it helps someone else.
You should just create a method on the form that needs to be updated, then pass a reference when of that form to the newly created form.
This won't work if either form is a dialog (as far as I know).
So:
Form that has the textbox that will be directly edited.
private Form formToUpdate;
public void OpenForm(Form _formToUpdate)
{
formToUpdate = _formToUpdate;
txtBlah.TextChanged += new EventHandler(OnTextChanged);
this.Show();
}
private void OnTextChanged(object sender, EventArgs e)
{
formToUpdate.UpdateText(txtBlah.Text);
}
Form that is to be dynamically updated:
delegate void StringParameterDelegate (string value);
public void UpdateText(string textToUpdate)
{
if (InvokeRequired)
{
BeginInvoke(new StringParameterDelegate(UpdateText), new object[]{textToUpdate});
return;
}
// Must be on the UI thread if we've got this far
txtblah2.Text = textToUpdate;
}
Note: this is untested (although it should work), and largely pseudo code, you'll need to tailor it to your solution obviously.

Add listview items from other form (using objects)

I want to get some data to fill a listview control, but this data it's determined in other form. This is what I code in form1 (Nuevo_Credito):
private void combo_cliente_SelectionChangeCommitted(object sender, EventArgs e)
{
Credito_Grupo ventana = new Credito_Grupo(combo_cliente.SelectedItem);
ventana.ShowDialog();
}
public void AgregaIntegrantes(string id, string nombre, string monto)
{
ListViewItem elem = new ListViewItem(id);
elem.SubItems.Add(nombre);
elem.SubItems.Add(monto);
listView_integrantes.Items.Add(elem);
}
I'm invoking form2 (Credito_grupo) as show dialog window, then I want to retrieve some values and pass them to Form1 using the public method "AgregaIntegrantes". So in form2 I did the following:
public Credito_Grupo(dynamic item)
{
this.id = item.IDCliente;
this.nombre = item.NomComp;
InitializeComponent();
}
private void Credito_Grupo_Load(object sender, EventArgs e)
{
text_nombre.Text = this.nombre;
}
private void button_AgregaCliente_Click(object sender, EventArgs e)
{
Nuevo_Credito obj = new Nuevo_Credito();
obj.AgregaIntegrantes(id.ToString(), nombre, text_monto.Text);
this.Close();
}
When the event button_AgregaCliente_click is triggered I need to add the data to listview in form1 using the method described above, but none data is added. I found a solution using delegates here 3077677, is there an approach using objects?
You have an error in button_AgregaCliente_Click method (the last one in the listing). You create a new Nuevo_Credito form there, and pass the data to listview. It looks OK. But this newly created Nuevo_Credito form does exist only in the local variable, so then you throw it away without displaying it when button_AgregaCliente_Click finishes.
I think you need to delete this line: Nuevo_Credito obj = new Nuevo_Credito();
You need to get your real Nuevo_Credito form, not create a new one here.
You can send this from your Nuevo_Credito to the constructor of the Credito_Grupo form. Then you can use it to call back to the original Nuevo_Credito. This approach is based only on objects, and not delegates. As you wanted. :-)

Categories