Home > OS >  How to save reordered DataGridView columns in the updated order?
How to save reordered DataGridView columns in the updated order?

Time:02-15

I have a datagridview in a winform that I read data into. I name each column after the count in the loop I use. Part of the function reading the data is below. The file I read from is a csv created from excel.

while (!parser.EndOfData)
{
   string[] fields = parser.ReadFields(); //read in the next row of data
   dgv_data.Rows.Add(); // add new row
   rowCount  ;
   //put row number inside left margin
   dgv_data.Rows[rowCount - 1].HeaderCell.Value = rowCount.ToString(); 
  

   for (int i = 0; i < col; i  )
   {
      dgv_data.Rows[rowCount - 1].Cells[i].Value = fields[i]; //put the data into the cell

     //If the cell is true or a number greater than 1 then we colour it green 
     if (fields[i].ToLower() == "true") dgv_data.Rows[rowCount - 1].Cells[i].Style.BackColor = Color.SpringGreen;
     if (int.TryParse(fields[i], out num))
     {
      if (int.Parse(fields[i]) > 0) dgv_data.Rows[rowCount - 1].Cells[i].Style.BackColor = Color.SpringGreen;
     }
     dgv_data.Rows[rowCount - 1].Cells[i].Tag = (rowCount - 1).ToString()   ":"   i.ToString(); //Unique cell tag
     }
}

I need to reorder the columns as I need to save in a different order BUT I also need to reorder them back to original order so flip-flop between the two different orders. This I do with a simple function, I only show a few of the columns here as there are 30 in total. This works well even if a bit inefficient.

private void btn_reorder_Click(object sender, EventArgs e)
{
    if (flag)
    {
        flag = false;

        dgv_data.Columns[22].DisplayIndex = 0;
        dgv_data.Columns[20].DisplayIndex = 1;
        dgv_data.Columns[12].DisplayIndex = 2;
     }
     else
     {
         flag = true;

         dgv_data.Columns[0].DisplayIndex = 0;
         dgv_data.Columns[1].DisplayIndex = 1;
         dgv_data.Columns[2].DisplayIndex = 2;
      }
      dgv_data.Refresh();
}

The issue comes when I need to save the data to a csv file, I do not get them saved in the new order. Before I save it I need to manipulate a few columns e.g change seconds to milliseconds. Using the following method, I can do this but when I save the file it always has the original layout.

var sb = new StringBuilder();

foreach (DataGridViewRow row in dgv_data.Rows)
{
   row.Cells[1].Value = (int.Parse(row.Cells[1].Value.ToString()) * 1000).ToString();

   var cells = row.Cells.Cast<DataGridViewCell>();
   sb.AppendLine(string.Join(",", cells.Select(cell => "\""   cell.Value   "\"").ToArray()));
}

  File.WriteAllText(saveFileDialog1.FileName, sb.ToString());

I found on internet a different method and this does save the new layout but I cannot manipulate the cells before I save them.

dgv_data.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText;

// Select all the cells
dgv_data.SelectAll();
// Copy selected cells to DataObject
DataObject dataObject = dgv_data.GetClipboardContent();
// Get the text of the DataObject, and serialize it to a file
File.WriteAllText(saveFileDialog1.FileName, 
dataObject.GetText(TextDataFormat.CommaSeparatedValue));

How can I make sure that when I reorder the columns that I can save them in the same order as they are show in the DataGridView and still be able to flip-flop between the two column orders?

CodePudding user response:

DataGridView Column have many ways you can address them, two are their name or their index number in the DataGridView Collection.

The user creates the Column name, but the Index is created by the system when columns are created, and I cannot see a way to ever edit this number.

If you want to reorder, the visual order of your columns in the GUI you change the DisplayIndex. This does not Change the Index number of the column. It just changes how the DGV looks in the UI.

I created a small example which you can download from https://github.com/zizwiz/DataGridView_ReorderColumn_Example

When you save the left hand reordered DGV by copy to clipboard you get the view in the GUI but if you save by parsing through the grid you get the original Index view. To get round this if you want to reorder and then save that by parsing through the DGV then you must Copy the original DGV to a new DGV column by column in the order you now want. There are many ways to do this I just show on simple way what you would probably want to do is put the column in a temporary list, remove all columns and add them again.

I cannot find a way of changing the Index property of a column after it has been created, so this copy method although cumbersome is what I have used.

As this is only a quick example it does not have all the bells and whistles one might want to use, it just illustrates how I got over a problem I encountered. The files you save are put in the same folder as the "exe" you run.

  • Related