我有一个填充 DataGridView 的对象列表(所有字符串),但是我无法使用列标题进行排序。我一直在阅读 SortableBindingList 来解决这个问题,但遗憾的是,由于我只学习了几天的代码,我无法理解如何实现它。任何让我再次动起来的建议将不胜感激(请尽可能简单)。
到目前为止,这是我的代码
{
public class Product
{
public string itemCode;
public string description;
public string currentCount;
public string onOrder;
public string ItemCode
{
get
{
return itemCode;
}
set
{
itemCode = value;
}
}
public string Description
{
get
{
return description;
}
set
{
description = value;
}
}
public string CurrentCount
{
get
{
return currentCount;
}
set
{
currentCount = value;
}
}
public string OnOrder
{
get
{
return onOrder;
}
set
{
onOrder = value;
}
}
}
{
class Program
{
public static List<Product> itemList = new List<Product>();
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
//Reads csv file
var filestream = new FileStream(@"c:\StockFile\stocklist.csv", FileMode.Open,
FileAccess.Read, FileShare.ReadWrite);
var file = new StreamReader(filestream, Encoding.UTF8, true, 128);
string lineOfText;
bool firstLine = true;
while ((lineOfText = file.ReadLine()) != null)
{
if (!firstLine)
{
// splits the values
string[] elements;
Product newItem = new Product();
elements = lineOfText.Split(',');
newItem.itemCode = elements[0];
newItem.description = elements[1];
newItem.currentCount = elements[2];
newItem.onOrder = elements[3];
// add to list
itemList.Add(newItem);
}
else
firstLine = false;
}
//loads grid
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
//Output to file
using (TextWriter tw = new StreamWriter(@"C:\StockFile\stocklist.csv"))
{
tw.WriteLine("Item Code,Item Description,Current Count,On Order");
foreach (Product newItem in itemList)
{
tw.WriteLine(newItem.ItemCode + "," + newItem.Description + "," + newItem.CurrentCount + "," + newItem.OnOrder);
}
}
}
}
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//Binds data to Grid
private void Form1_Load(object sender, EventArgs e)
{
var source = new BindingSource();
source.DataSource = Program.itemList;
dataGridView1.DataSource = source;
dataGridView1.AutoGenerateColumns = true;
this.Controls.Add(dataGridView1);
dataGridView1.Refresh();
foreach (DataGridViewColumn column in dataGridView1.Columns)
{
dataGridView1.Columns[column.Name].SortMode = DataGridViewColumnSortMode.Automatic;
}
//Make Colomns read only
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
if (col.Name == "CurrentCount")
{
col.ReadOnly = false;
}
else
{
col.ReadOnly = true;
}
}
}
}
最佳答案
这里有 SortableBindingList 的示例代码...
https://stackoverflow.com/a/40051526/2093531
要将列表转换为 SortableBindingList...
SortableBindingList<YourListType> sortableBindingList = new SortableBindingList<YourListType>(list);
关于c# 如何从 List<T> 创建 SortableBindingList,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30907040/