DataTable会自动重新初始化

时间:2018-08-24 14:54:19

标签: c#

为什么我的DataTable会在事件内自动重置为null的值?

for循环结束后,DataTable重置为null,并且不将值保留在公共字段中。即使我有另一个事件执行相同的操作,但它可以容纳DataTable

Public DataTable d = new DataTable();

private void btnCSVgetter_Click(object sender, EventArgs e)
{
    emptyDataGrid();

    var csv   = new OpenFileDialog();
    csv.Title = "Select CSV to Upload";
    csv.DefaultExt = "*.csv";
    csv.Filter = "CSV files| *.csv";

    if (csv.ShowDialog() == DialogResult.OK)
    {
        string safeName = csv.SafeFileName;
        string filename = csv.FileName;
        string filedirectory = csv.FileName.Substring(0, filename.IndexOf(safeName));

        if (IsFileLocked(filename)) { MessageBox.Show("File is in use by another user, close and try again"); return; }

        var con = new OleDbConnection(String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Text;HDR=YES;FMT=Delimited\"", filedirectory));
        var cmd = new OleDbCommand(String.Format("select * from [" + safeName + "]"), con);
        con.Open();

        var csvDA = new OleDbDataAdapter(cmd);
        var d = new DataTable();

        csvDA.Fill(d);
        DGVUpload.DataSource = d;

        con.Close();
        d.Columns.Remove("Symbol");

        foreach (DataColumn col in d.Columns)
        {
            if (col.ColumnName == "Ric Code")
                col.ColumnName = "Symbol";
            else if (col.ColumnName == "AveragePrice")
                col.ColumnName = "Avg_Price";
            else if (col.ColumnName == "Accounts")
                col.ColumnName = "ClientAcct";
            else if (col.ColumnName == "Executed")
                col.ColumnName = "Quantity";

        } // After this line datatable d resets to null

      // MoreCode...
 }

1 个答案:

答案 0 :(得分:4)

您的代码段中有两个DataTable d声明:

Public DataTable d = new DataTable(); <---- here

private void btnCSVgetter_Click(object sender, EventArgs e)
{
    emptyDataGrid();

    OpenFileDialog csv = new OpenFileDialog();
    csv.Title = "Select CSV to Upload";
    csv.DefaultExt = "*.csv";
    csv.Filter = "CSV files| *.csv";

    if (csv.ShowDialog() == DialogResult.OK)
    {
        string safeName = csv.SafeFileName;

        string filename = csv.FileName;
        string filedirectory = csv.FileName.Substring(0, filename.IndexOf(safeName));

        if (IsFileLocked(filename) == true) { MessageBox.Show("File is in use by another user, close and try again"); return; }

        OleDbConnection con = new OleDbConnection(String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Text;HDR=YES;FMT=Delimited\"", filedirectory));
        OleDbCommand cmd = new OleDbCommand(String.Format("select * from [" + safeName + "]"), con);
        con.Open();
        OleDbDataAdapter csvDA = new OleDbDataAdapter(cmd);
        DataTable d = new DataTable(); <----- here
        csvDA.Fill(d);

执行此操作时,内部if语句将对局部d进行操作,而不是对方法外部声明的类变量进行操作。本地d超出范围后,您可以使用的唯一d是类级别的一个,为空。