0

I want to hide a column in a datagridview which is in Form1 from Form2. I wrote this code on a button Click in Form2 but that doesn't work.

private void button_Click(object sender, EventArgs e)
{
    Form1 form = new Form1();
    form.datagridview.Columns["ColumnName"].Visible = false;
}

but the Column is visible yet after clicking on the button.

  • `Form1 form = new Form1();` you are creating a new instance of `Form1` which is not the form that you are seeing behind `Form2`. When in `Form1` you open a new Instance of `Form2`, you need to pass `this` (which is the instance of `Form1`) to `Form2` constructor. `var f2 = new Form2(this);` and then show the f2. You should also change the constructor of `Form2` to accept an instance of `Form1` and store it in a member field and use it wherever required, something like this: `private Form1 f1; public Form2(Form1 f1) {this1.f1=f1;}` and then for example later in Form2, `this.f1.datagridview...`. – Reza Aghaei Jan 19 '21 at 19:26
  • 2
    Look at example 7 in [Interaction between forms — How to change a control of a form from another form?](https://stackoverflow.com/a/38769212/3110834) – Reza Aghaei Jan 19 '21 at 19:32
  • you can pass the datagrid object in the constructor of form2, so that you can directly hide the column or you have to declare the datagrid as public and pass your form1 instance to form2, or you can declare a static property and access is from everywhere. your choice. Ah, and you can route the checkbox checked event and subscribe within form1 directly – TinoZ Jan 19 '21 at 19:33

1 Answers1

0

You may need to change the Form1 control modifier property to "public" in order to be able to access the control from Form2.

mjhillman
  • 1
  • 1