问题描述
当使用自定义SortComparer时如何冻结Datagridview中的第一行?
没有SortComparer row [x] .froozen = true;
会这样做。
但是使用SortComparer它不工作
How to freeze first row in Datagridview when using a custom SortComparer?Without SortComparer row[x].froozen = true;
would do it.But with a SortComparer it doesnt work
这是我的SortComparer代码:
Here is my SortComparer Code:
DataGridView dg = (DataGridView)sender;
if (e.Column.Index == 0)
{
e.SortResult = System.String.Compare(e.CellValue1.ToString(), e.CellValue2.ToString());
if (e.SortResult == 0)
{
e.SortResult = System.String.Compare(
dg.Rows[e.RowIndex1].Cells[1].Value.ToString(),
dg.Rows[e.RowIndex2].Cells[1].Value.ToString());
}
e.Handled = true;
}
else if (e.Column.Index == 1)
{
e.SortResult = System.String.Compare(e.CellValue1.ToString(), e.CellValue2.ToString());
if (e.SortResult == 0)
{
e.SortResult = System.String.Compare(
dg.Rows[e.RowIndex1].Cells[0].Value.ToString(),
dg.Rows[e.RowIndex2].Cells[0].Value.ToString());
}
e.Handled = true;
}
推荐答案
您可以将SortComparer检查第一行索引是否为顶行。如果是,请设置 e.SortResult = 0
或者运行您要排序的任何代码。
You could extend your SortComparer to check if the first row index is the top row or not. If it is, set the e.SortResult = 0
or else run whatever code you want to sort with.
private void dataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
{
DataGridView dg = (DataGridView)sender;
if (e.RowIndex1 == 0) {
e.SortResult = 0;
e.Handled = true;
} else {
// rest of your comparison code
}
}
,或者您可以通过检查该行是否冻结来使其变得更加流行:
or you can make it more fancy by checking if the row is frozen or not:
编辑因为某些原因,默认情况下,Row的Frozen属性设置为false
EDIT the following does not work since the Frozen property of a Row gets set to false by default for some reason
private void dataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
{
DataGridView dg = (DataGridView)sender;
if (dg.Rows[e.RowIndex1].Frozen) {
e.SortResult = -1;
e.Handled = true;
} else {
// rest of your comparison code
}
}
编辑 e.SortResult = 0
而不是-1作为相等的行将根据其当前的排序位置。
EDIT The e.SortResult = 0
instead of -1 as rows that are equal will be sorted based on their current position.
这篇关于使用自定义SortComparer时如何冻结datagridview中的第一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!