gpt4 book ai didi

c# - 重新排序 DatagridViews 列并以编程方式保存新位置

转载 作者:行者123 更新时间:2023-11-30 21:44:57 27 4
gpt4 key购买 nike

我的 Windows 窗体中有一个数据 GridView 。我需要允许用户对列重新排序,然后永久保存更改。我设置myGrid.AllowUserToOrderColumns = true;但这只会改变设计上的显示索引。

最佳答案

也许是一个老问题,但我想出了一些我认为更简单的问题。

首先,在您的表单类的开头,添加以下字段:

public partial class MyForm : Form
{
//So whenever you change the filename, you write it once,
//everyone will be updated
private const string ColumnOrderFileName = "ColumnOrder.bin";
//To prevent saving the data when we don't want to
private bool refreshing = false;

... // the rest of your class

然后,使用以下方法附加到事件 ColumnDisplayIndexChanged:

private void MyDataGridView_ColumnDisplayIndexChanged(object sender, DataGridViewColumnEventArgs e)
{
//Because when creating the DataGridView,
//this event will be raised many times and we don't want to save that
if (refreshing)
return;

//We make a dictionary to save each column order along with its name
Dictionary<string, int> order = new Dictionary<string, int>();
foreach (DataGridViewColumn c in dgvInterros.Columns)
{
order.Add(c.Name, c.DisplayIndex);
}

//Then we save this dictionary
//Note that you can do whatever you want with it...
using (FileStream fs = new FileStream(ColumnOrderFileName, FileMode.Create))
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, order);
}
}

然后是 OrderColumns 方法:

private void OrderColumns()
{
//Will happen the first time you launch the application,
// or whenever the file is deleted.
if (!File.Exists(ColumnOrderFileName))
return;
using (FileStream fs = new FileStream(ColumnOrderFileName, FileMode.Open))
{
IFormatter formatter = new BinaryFormatter();
Dictionary<string, int> order = (Dictionary<string, int>)formatter.Deserialize(fs);
//Now that the file is open, we run through columns and reorder them
foreach (DataGridViewColumn c in MyDataGridView.Columns)
{
//If columns were added between two versions, we don't bother with it
if (order.ContainsKey(c.Name))
{
c.DisplayIndex = order[c.Name];
}
}
}
}

最后,当您填充 DataGridView 时:

private void FillDataGridView()
{
refreshing = true; //To prevent data saving while generating the columns

... //Fill you DataGridView here

OrderColumns(); //Reorder the column from the file
refreshing = false; //Then enable data saving when user will change the order
}

关于c# - 重新排序 DatagridViews 列并以编程方式保存新位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40542518/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com