【发布时间】:2021-01-05 10:57:45
【问题描述】:
【问题讨论】:
-
您可以在 DataGridView 的客户区域内的可见位置滚动 NewRow,而不是唯一可见的 Row。你想如何触发这个动作?单击左上角的单元格?
标签: c# .net windows winforms datagridview
【问题讨论】:
标签: c# .net windows winforms datagridview
无法将添加新行移动到数据网格视图的顶部。有一个名为 bindingSource 的控件,它具有 MoveLast 等方法,可以更轻松地导航到最后一行数据。
private void Form_Load(object sender, EventArgs e)
{
BindingList<DataInfo> data = new BindingList<DataInfo>();
for (int x = 1; x <= 100; x++)
{
data.Add(new DataInfo()
{
id = x,
Name = $"User{x}"
});
}
this.bindingSource1.DataSource = data;
this.dataGridView1.DataSource = bindingSource1;
}
private void button1_Click(object sender, EventArgs e)
{
bindingSource1.MoveLast();
}
}
public class DataInfo
{
public int id { get; set; }
public string Name { get; set; }
}
【讨论】:
[DataGridView].FirstDisplayedScrollingRowIndex = [DataGridView].NewRowIndex;
请注意“空行”和“添加新行”之间的区别,这似乎是一个空行,但实际上它还不是数据的一部分。
假设我们的 DataGridView 显示了一系列客户的多个属性。
要获得顶部的空行,您必须定义“空行”:
问题,问题。显然,您需要使用属性 IsEmpty 扩展您的客户:
public bool IsEmpty => ... // TODO code that returns true if customer is "Empty".
为了排序使得 Empty Customers 位于顶部,您需要创建一个 CustomerComparer 类,该类实现了IComparer<Customer>,
并告诉 DataGridView 使用此比较器进行排序:
IComparer<Customer> customerComparer = ...
this.DataGridView1.Sort(customerComparer);
Customer Comparer 类的示例:
class CustomerComparer<Tproperty> : Comparer<Customer>
{
public bool EmptyRowsFirst {get; set;} = true;
// sort the non-empty customers ascending or descending:
public SortDirection SortDirection {get; set;} = SortDirection.Ascending;
// which property to use to sort the non-empty customers:
public Func<Customer, TProperty> PropertySelector
public override int Compare (Customer x, Customer y)
{
if (this.EmptyRowsFirst)
{
if (x.IsEmpty)
return y.IsEmpty ? 0 : +1
else
return y.IsEmpty ? -1 : this.CompareByProperty;
}
else
return this.CompareByProperty;
}
}
方法 CompareByProperty:
private int CompareByProperty(Customer x, Customer y)
{
IComparer<TProperty> propertyComparer = Comparer<T>.Default;
TProperty propertyX = this.PropertySelector(x);
TProperty propertyY = this.PropertySelector(y);
int compareResult = propertyComparer(propertyX, propertyY);
if (this.SortDirection == SortDirection.Descending)
compareResult = -compareResult;
return compareResult;
}
用法:
// Sort by Customer.BirthDay, Ascending, empty rows First:
IComparer<Customer> customerComparer = new CustomerComparer<DateTime>
{
EmptyRowsFirst = true,
SortDirection = SortDirection.Ascending,
customer => customer.BirthDay,
};
this.DataGridView.Sort(customerComparer);
// Sort by Customer.City, rest as default:
IComparer<Customer> customerComparer = new CustomerComparer<String>
{
customer => customer.City,
};
this.DataGridView.Sort(customerComparer);
【讨论】: