Click here to Skip to main content
15,886,004 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a DateGridView1 instantiated in Form1 (by Visual C#).
I want it to be global . . . I want to access its cells from every class (I made a new one) in app.

I thought it would be accessible from all classes if I changed the generated code from private to public . . .

public System.Windows.Forms.DataGridView DataGridView1;

& also added public to the generated Form1 class as follows . . .

public partial class Form1 : Form

To just show my problem . . I created a class using same namespace . . .

public class V
{
string Client = DataGridView1[0, 0].Value.ToString();
}

2 errors . .

Error 2 The name 'DataGridView1' does not exist in the current context

Error 1 The name 'Client' does not exist in the current context

How can I access DataGridView1 from ALL classes? How do I make it Global?
Posted

In order to make is as Global access, you need to change the access modifier of the DataGridView1 as Public or Internal

To access the DataGridView1 in other classes you need to create an instance for the DataGridView1 Form (Form1)

C#
public class V
{
  public void Somemethod()
{
Form1 obj = new Form1();
string Client = obj.DataGridView1.Rows[0].Cells[0].Value.ToString();
}
}


Note: before accessing the cells of the DGV, make sure the data is binded to the DGV.
Lot of validation to be done..
 
Share this answer
 
Comments
JOHNNYDEMICHAEL 9-Feb-14 17:13pm    
But I need to access the instance already available in another cell.
Select the DataGridView and open the properties window. Then set the 'modifiers' property to 'Public'.

That should do it.

If you try to access the DataGridView from anywhere in the application you may have some problems though.
 
Share this answer
 
Thanks, but I could not get any of the suggestions to work. I substantiated it in the class outside of any method.
 
Share this answer
 
Let's say you're having GridView in Deafault.aspx and you want to access it on Page1.aspx, Page2.aspx and Page3.aspx.

So what you can do is, make a public property for it and with the help of page instance you can call that Grid.
For example,

Default.aspx
C#
public GridView MyGrid
{ 
    get { return GridView1; } 
    set { GridView1 = value; }
}

Page_Load(...)
{
    /*
    ...
    */
}

Page1.aspx / Page2.aspx / page3.aspx
C#
Page_Load()
{
    Default df = new Default();
    GridView2 = df.MyGrid;
}

It's just my blind assumption that it's gonna work. If it is not, let us know :)

-KR
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900