How to Share Data Between Forms

Passing data between forms

Form1 frm = new Form1();

frm is now a new instance of class Form1.

frm does not refer to the original instance of Form1 that was displayed to the user.

One solution is, when creating the instance of Form2, pass it a reference to your current instance of Form1.

How to share data between forms?

Add a public property to your Form2 class that returns the selected item.

Then, replace the Show() call with ShowDialog() (a blocking method) and check the property afterwards.

Also, rename your forms.

Passing data between C# forms

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.

Safest way to pass data between forms in c# winforms

So the reasoning that you have given for just having a lot of public static data is not correct. It is no more or less secure from malicious attempts of another processes to access the information. It's in memory no matter what you do, so a malicious process (with sufficient privileges) can get at it no matter what, but they're likely to have a bit of a hard time of it no matter what as well. If you have a malicious process/user with that level of permissions you've already lost the fight; they can already do whatever they want.

The problems with storing all of your data in public static fields is merely a matter of effective development, not of actual security. When the data can be modified from anywhere in your entire program at any time it makes it extraordinary hard to understand what's going on in the program at any one point in time, it makes bugs really hard to track down as there could be problems almost anywhere in the code, it makes bringing in new developers to a project really hard because they can't just open up a class or two and understand them, they need to understand the entire application to be able to reason correctly about what's going on in any one part, due to the high level of coupling in your application.

You should strive to reduce coupling of various modules in your application by keeping the data more localized. This allows a developer to look at a single module (whether that be a form, a user control, some worker class, etc.) and only need to understand that class in front of them without needing to understand every single point in the entire application that also touches the same variables.

You also need to be very concerned about threading issues when you're accessing public static variables from multiple threads, since you almost certainly are going to require multiple threads in a winform application.

Finally, if you're storing all of your data statically it means that you'll never be able to have multiple instances of your forms. Most forms that you'll write, from a logical perspective, shouldn't require that there never be more than one of them in an application. If their data is localized to just them there isn't any problem creating a second form. If all of the data is static, then the forms will end up fighting with each other over that data.

As for how to accomplish this, the primary goal here should be to keep data scoped as narrowly as you are able to (which is something that you should generally strive for throughout all types of programming) without allowing variables to be accessible in places where they don't need to be accessed.

The case you've described is a fairly straightforward problem to solve. If a form is creating another form that needs some data upon construction, if that data is essential to the use of that other form then just create parameters in the constructor for that data. The form (or whatever else) creating it can then pass in that required data. If the data isn't required, or it isn't required right at construction, then the other option is to have properties that allow the "owner" of that form to pass in the data that is needed. Doing this isn't really any more complex than creating a public static field; it's simply creating a public non-static property.

Now that this data isn't static you know that, rather than being accessed from anywhere, that information is going to be provided from whoever is "owning" that particular instance of the form. You're limiting the scope of where the data can be accessed to place that needs it, and the place that has it, rather than "everywhere".

How to pass data between forms?

Try This.

Select Content Type Form

private List<string> _selectedItems = new List<String>();
public List<string> SelectedItem
{
get {return _selectedItems;}
}

private void btnSelect_Click(object sender, EventArgs e)
{
for(int i=0; i<lst.Items.Count;i++)
{
if (lstContenType.GetItemCheckState(i) == CheckState.Checked)
_selectedItems.Add(lst.Items[i].ToString());
}
this.Close();
}

Create List Form

private void rdoEnableCntType_Checked(object sender, EventArgs e)
{
if (rdoEnableCntType.Checked = true)
{
FrmConentType frm = new FrmConentType();
frm.ShowDialog();
List<string> list = frm.SelectedItems;
//Place your code to use selected items
}
}

passing data between two forms using properties

I know this is a (really) old question, but hell..

The "best" solution for this is to have a "data" class that will handle holding whatever you need to pass across:

class Session
{
public Session()
{
//Init Vars here
}
public string foo {get; set;}
}

Then have a background "controller" class that can handle calling, showing/hiding forms (etc..)

class Controller
{
private Session m_Session;
public Controller(Session session, Form firstform)
{
m_Session = session;
ShowForm(firstform);
}

private ShowForm(Form firstform)
{
/*Yes, I'm implying that you also keep a reference to "Session"
* within each form, on construction.*/
Form currentform = firstform(m_Session);
DialogResult currentresult = currentform.ShowDialog();
//....

//Logic+Loops that handle calling forms and their behaviours..
}
}

And obviously, in your form, you can have a very simple click listener that's like..

//...
m_Session.foo = textbox.Text;
this.DialogResult = DialogResult.OK;
this.Close();
//...

Then, when you have your magical amazing forms, they can pass things between each other using the session object. If you want to have concurrent access, you might want to set up a mutex or semaphore depending on your needs (which you can also store a reference to within Session). There's also no reason why you cannot have similar controller logic within a parent dialog to control its children (and don't forget, DialogResult is great for simple forms)

C#- Data transfer between two forms

Finally, I solved the problem.

Application.OpenForms["form1"].Controls["textBox1"].Text = 
gridView1.GetFocusedRowCellValue("ID").ToString();

Thanks for help.



Related Topics



Leave a reply



Submit