Tomas Pangonis
Tomas Pangonis

Reputation: 29

Access Object created in another method C#

In this code I'm creating Few DataGridViews. Number of those depends on file which within each launch of application will be different, so is number of DataGridViews.

How can I Access particular dataGridView grid[i] and modify it from which event Form1_UserAddedRow was called in that method?

Code:

public void Form1_Load(object sender, EventArgs e)
{
    string[] lines = System.IO.File.ReadAllLines(@"..\..\Base.txt");

    int diet_num = 0;
    int grid_num = 0;

    foreach (string x in lines) diet_num++;

    grid_num = (diet_num / Constant.DATAGRID_DIETS_IN_GRID) + 1;

    DataGridView[] grid = new DataGridView[grid_num];
    for (int i = 0; i < grid_num; i++)
    {
        grid[i] = new DataGridView();
        grid[i].Tag = i;
        grid[i].Parent = this;
        grid[i].Location = new Point(12, 12 + (8 + Constant.DATAGRID_ROW_HEIGHT * 2) * i);
        grid[i].Visible = true;
        grid[i].RowHeadersVisible = false;
        grid[i].Height = Constant.DATAGRID_ROW_HEIGHT * 2;
        grid[i].Width = Constant.DATAGRID_COLUMN_SIZE * Constant.DATAGRID_DIETS_IN_GRID + 3;
        grid[i].UserAddedRow += Form1_UserAddedRow;
    }
    this.Width = Constant.DATAGRID_COLUMN_SIZE * Constant.DATAGRID_DIETS_IN_GRID + 40;


    foreach (string x in lines)
    {
        DataGridViewColumn col = new DataGridViewTextBoxColumn();
        col.Width = Constant.DATAGRID_COLUMN_SIZE;

        col.HeaderText = x;
        int colIndex = grid[0].Columns.Add(col);
    }
}

private void Form1_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
    //I want to access grid[i] and modify it here.
}

Upvotes: 1

Views: 89

Answers (3)

CHS
CHS

Reputation: 138

private void Form1_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
    var grid = sender as DataGridView;
    if (grid == null) return;

    //... do something

}

Upvotes: 0

PentaPenguin
PentaPenguin

Reputation: 216

You should be able to cast the Sender object parameter in your event handler to the type of DataGridView to retrieve the grid which has been effected.

Upvotes: 1

Rahul
Rahul

Reputation: 77926

You are getting the DataGridViewRowEventArgs e as the argument to your event handler and thus you can access the Row property like

e.Row.Cells["somename"].Value = "some_value";

Upvotes: 0

Related Questions