下面的类是我处理的是什么一个例子:如何将值设置为绑定的DataGridView的单元格的标记?
class Item
{
public int ID {get;set;}
public string Name {get;set;}
public int Quantity {get;set;}
public string Unit {get;set;}
public override string ToString()
{
return string.Format("{0}({1}){2}{3}", Name,Quantity,Environment.NewLine,Unit);
}
}
class Items
{
List<Item> _items;
public DataTable AllItems()
{
var dt = new DataTable();
// Some manipulation to convert the list to a datatable
// ...
return dt;
}
}
class UI
{
public void PopulateDatagridview()
{
//Some code to create the items
// ...
datagridview1.DataSource = items.AllItems();
}
private void datagridview1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.C) // Control + c
{
// here I need to copy only the item name
}
}
}
我只需要项目名称从电网复制,简单的和“丑陋”的解决方法是将分析单元格文本,然后获取项目名称。 但我必须每次更新我的Item.ToString()时更新此代码。 我的一个解决方案是将项目ID保存在每个单元格中,这样我就可以轻松地从项目对象中检索项目名称。 我想将Item ID保存到单元格的Tag属性,但由于我通过将DataTable绑定到它的DataSource来填充DataGridView,我无法保存它。
有没有办法将值保存到绑定的DataGridView的单元格的标记?
如何在DataTable中创建DataGridView不可见的新列? – vasek
它实际上是复制datagridview,id是针对每个单元的 – ehh
对不起,您的Item类表示Cell而不是Row的事实对我来说并不明显。 – vasek