范围 。 。为什么我不能访问csvData(A DataTable) [英] SCOPE . . why can't I access csvData (A DataTable)

查看:134
本文介绍了范围 。 。为什么我不能访问csvData(A DataTable)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面我的Form1.cs部分文件有一个绑定到datatable(csvData)的datagridview。 。为什么我不能在addNewRowButton事件中访问datatable(csvData)。 。 。向DataGridView添加了一个按钮。错误说不在上下文中。我试图给你最少量的代码。我在哪里可以定义我的数据表以确保它可以从Form1.cs中的所有方法访问?

My Form1.cs partial file below has a datagridview bound to datatable (csvData) . . why can't I access the datatable (csvData) in addNewRowButton event . . . added a button to the DataGridView. Error says not in context. I'm trying to give you only a minimum amount of code. Where can I define my datatable to be sure it is accessible from all methods in Form1.cs?

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }



    private void Form1_Load(object sender, EventArgs e)
    {


        DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;


        string csv_file_path = @"C:\\TaxLtrExport\\ClientInfoMaster.csv";
    System.Data.DataTable csvData = GetDataTableFromCSVFile(csv_file_path);

    DataGridView1.DataSource = csvData; //This is where rows in datatable are copied to dgv.



    private void addNewRowButton_Click(object sender, EventArgs e)
    {
        csvData.NewRow(); // Out of context error . .

        //why can't I access csvData (a DataTable) here?

    }


}

推荐答案

目前你在Load事件处理程序方法中声明它,这意味着它只在该方法中可用。

在外面声明它:

At the moment you declare it within the Load event handler method, which means it is only available within that method.
Declare it outside:
private System.Data.DataTable csvData;
private void Form1_Load(object sender, EventArgs e)
{


DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;

 
string csv_file_path = @"C:\\TaxLtrExport\\ClientInfoMaster.csv";
csvData = GetDataTableFromCSVFile(csv_file_path); 

它应该可以工作。


在Class Level定义它。



修改后的代码看起来像什么如下所示。

Define it at Class Level.

Modified code would look something like below.
public partial class Form1 : Form
{
    System.Data.DataTable csvData;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
        
        string csv_file_path = @"C:\\TaxLtrExport\\ClientInfoMaster.csv";
        csvData = GetDataTableFromCSVFile(csv_file_path);
        
        DataGridView1.DataSource = csvData; //This is where rows in datatable are copied to dgv.
    }
    
    private void addNewRowButton_Click(object sender, EventArgs e)
    {
        csvData.NewRow();   
    }
}


这篇关于范围 。 。为什么我不能访问csvData(A DataTable)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆