26
Reply

Sorting a DataTable by Changing Column Type

Farhan Shariff

Farhan Shariff

May 27 2014 8:27 AM
2.9k
I want to know how to acess the table8_sorted outside of the for loop
when I try to use it I get error
does not exists in current context


//--------------------------------------------------------------------------------------------
            DataTable table8; //table8 used for sorting and then later for plotting
            table8 = table7.Copy(); //table7 is the unsorted table

// cloning table8 is cloned to change the type of columns

            DataTable dtSorted = table8.Clone();
            for (int w = 0; w < table8.Columns.Count; w++)
            {
                dtSorted.Columns[w].DataType = typeof(Double);
            }
            foreach (DataRow row in table8.Rows)
            {
                dtSorted.ImportRow(row);
            }

// sorting dtSorted to get table8_sorted (sorted table)      

            for (int loop = 0; loop < dtSorted.Columns.Count; loop++)
            {
                DataView dataview = dtSorted.DefaultView;
                dataview.Sort = dtSorted.Columns[loop].ColumnName;
         
                DataTable table8_sorted = dataview.ToTable(); 
//how to acess this out side of the loop
            }

//Does not exists in current context
   table8_sorted.Columns.Add("plot", typeof(double));           
  double terms = table8_sorted.Rows.Count;


            int t = 1;

            for (int i = 0; i < terms; i++)
            {

               double ap;
                ap = (t - 0.3) / (terms + 0.4);
                table8_sorted.Rows[i]["plot"] = ap;

                t++;
            }

Answers (26)