在另一个方法C#中创建的Access对象

时间:2017-05-24 13:22:05

标签: c# forms winforms datagridview

在这段代码中,我创建了很少的DataGridViews。这些数量取决于每次启动应用程序时不同的文件,DataGridViews的数量也不同。

如何访问特定的dataGridView grid[i]并修改该方法中调用的事件Form1_UserAddedRow

代码:

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.
}

3 个答案:

答案 0 :(得分:1)

您应该能够将事件处理程序中的Sender对象参数强制转换为DataGridView类型,以检索已经生效的网格。

答案 1 :(得分:0)

您将DataGridViewRowEventArgs e作为事件处理程序的参数,因此您可以访问Row属性,如

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

答案 2 :(得分:0)

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

    //... do something

}