Farhan Shariff

Farhan Shariff

  • NA
  • 933
  • 241.6k

GUI freezes. Running methods in background

Mar 25 2014 10:23 AM
I want to run  table3 = CompareTwoDataTable(table1, table2); in background.
when I try to browse the file path the GUI freezes how do I run the methods in background and stop GUI from freezing 

private void bt_nw_browse_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
// To list only csv files, we need to add this filter
openFileDialog.Filter = "|*.csv";
DialogResult result = openFileDialog.ShowDialog();
if (result == DialogResult.OK)
{
tbCSVPath2.Text = openFileDialog.FileName;
}
table2 = GetDataTabletFromCSVFile1(tbCSVPath2.Text);

table3 = CompareTwoDataTable(table1, table2);

}


private static DataTable GetDataTabletFromCSVFile1(string csv_file_path1)
{
DataTable table2 = new DataTable("Real");
using (TextFieldParser csvReader1 = new TextFieldParser(csv_file_path1))
{
csvReader1.SetDelimiters(new string[] { "," });
csvReader1.HasFieldsEnclosedInQuotes = true;
string[] colFields = csvReader1.ReadFields();
foreach (string column in colFields)
{
DataColumn datecolumn2 = new DataColumn(column);
datecolumn2.AllowDBNull = true;
table2.Columns.Add(datecolumn2);
}
while (!csvReader1.EndOfData)
{
string[] fieldData1 = csvReader1.ReadFields();
//Making empty value as null
for (int i = 0; i < fieldData1.Length; i++)
{
if (fieldData1[i] == "")
{
fieldData1[i] = null;
}
}
table2.Rows.Add(fieldData1);
}
}
return table2;
}


private static DataTable CompareTwoDataTable(DataTable table1, DataTable table2)
{
  DataTable table3 = new DataTable();
   DataRow dr = null;
  string filterExp = string.Empty;
   for (int i = 0; i < table1.Rows.Count; i++)
  {
     string col = table1.Rows[i]["Par Name"].ToString();
     if (table2.Columns.Contains(col)) 
     {
          if (!table3.Columns.Contains(col))
          {
            table3.Columns.Add(col, typeof(double));
            filterExp = filterExp + col + " asc ,";
          }
      for (int j = 0; j < table2.Rows.Count; j++) 
   {
          if (table3.Rows.Count != table2.Rows.Count)
         {
           dr = table3.NewRow();
         table3.Rows.Add(dr);
          }
            table3.Rows[j][col] = table2.Rows[j][col];
     }
}
}
      DataTable resultDt = table3.Clone();
      for (int m = 0; m < table3.Columns.Count; m++)
     {
           DataView dv = new DataView(table3);
          dv.Sort = filterExp.Split(',')[m];
           table3 = dv.ToTable();
           for (int i = 0; i < table3.Rows.Count; i++)
       {
         if (resultDt.Rows.Count != table3.Rows.Count)
       {
         resultDt.Rows.Add();
        }
          resultDt.Rows[i][m] = table3.Rows[i][m];
       }
     }
        return resultDt;

}
 

Answers (6)