简体   繁体   中英

C# filling dataGrid from other form

I would like to add data from a fill out form I made, to another form which contains my DataGridView. The problem is that they dont see one another. I tried making a struct of those data fields(textboxes and comboboxes) and making a static list which I wanted to use in the other form with the table. But it still doesnt work. I have a form Statue and a form Table. I tried

foreach('struct i made in both forms' rs in 'Statue.that static list')
{
-fill table-
} 

but it displays error "cannot convert type Statue.registeStruct to Table.registreStruct". Can you help me with this? Thanks

Using mouse select your component in Visual Studio (I mean that dataGrid). Then go to property list, and change row "Modifiers" from private to public. Not you can access that dataGrid from another form.

Assuming you're using Windows Forms .

You want to use DataBinding .

I firmly suggest that you have a BindingSource per DataGridView , and then expose the its DataSource property in order to share the same source between the two.

public class Form1 : Form {
    public IList<MyObjectType> DataContext {
        get { return (IList<MyObjectType>)myBindingSource.DataSource; }
        set { myBindingSource.DataSource = value; }
    }
}

public class Form2 : Form {
    public IList<MyObjectType> DataContext {
        get { return (IList<MyObjectType>)myBindingSource.DataSource; }
        set { myBindingSource.DataSource = value; }
    }
}

Then, in another form, you'll be able to share the information between the two.

public class Form3 : Form {
    private void onWhateverEventItMIghtBe(object sender, EventArgs e) {
        instanceOfForm2.DataContext = instnceOfForm1.DataContext;
    }
}

You will indeed need to set data binding up in designer mode.

Set your BindingSource.DataSource property in the PropertyWindow to a new DataSource using the wizard in order for both your DataGridView to set up their columns to what you want. Then, set you DataGridView.DataSource property to your BindingSource .

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