简体   繁体   中英

Full access from Form2 to Form1

How to create a full access from: Form 2 to Form1
So i can use all Textboxes, Datagridviews and the given information from my From1 in my second Form2

My Plan : User choose a Item in my DataGridView and then automatically my Second Form open, where all informations are given in Textboxes and so on... the user can modify them and save them into my SQL Database, Form2 closed and Form1 opens again

I look at Stackoverflow and google but i dont find a soulution, working for me ...

Assume you have person class:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

And list of persons bound to grid

List<Person> people = GetPeople();
peopleGridView.DataSource = people;

When you double-click on some row, get data bound person and pass it to second form:

private void peopleGridView_DoubleClick(object sender, EventArgs e)
{
    if (peopleGridView.CurrentRow == null)
        return;

    Person person = (Person)peopleGridView.CurrentRow.DataBoundItem;
    using (var editForm = new PersonDetailsForm(person))
    {
        if (editForm.ShowDialog() != DialogResult.OK)
            return;

        // get updated person data and save them to database
        UpdatePerson(editForm.Person);
    }
}

In edit form display person data in controls (you can use data-binding also):

public partial class PersonDetailsForm : Form
{
    public PersonEditForm(Person person)
    {
        InitializeComponent();
        idLabel.Text = person.Id.ToString();
        nameTextBox.Text = person.Name;
        // etc
    }

    public Person Person
    {
        return new Person {
            Id = Int32.Parse(idLabel.Text),
            Name = nameTextBox.Text
        };
    }     
}

Benefits - you can change PersonEditForm independently - add/remove controls, change their types, adding data binding etc without changing your main form.

you can create a constructor in your Form2 that takes the parameters that will fill your controls for example:

public Form2(string property1, List<object1> objects)
{
    textbox1.text = property1;
    gridview1.DataSource = objects;
    //and so on
}

and then call them from form1

Form2 form = new Form2(string1,list1);
form.Open();

or you can pass a single object to the constuctor and extend its properties in Form2

将所有必要的数据传输到第三类,并将实例作为参数传递给form2。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM