我想在表单加载时对网格进行排序,但Visual Studio不喜欢我的代码。任何帮助将不胜感激!
dataGridView1.Sort(dataGridView1.Columns[0], ListSortDirection.Descending);
答案 0 :(得分:2)
您可以在绑定数据之前对数据进行排序。例如,如果您有DataTable
,则可以执行以下操作:
dataTable.DefaultView.Sort("Cola DESC");
然后绑定已排序的数据。
答案 1 :(得分:1)
private void Form_Load(object sender, EventArgs e)
{
//bind u r collection to datagridview
DataGridView1.Sort( new RowComparer( SortOrder.Ascending ) );
}
private class RowComparer : System.Collections.IComparer
{
private static int sortOrderModifier = 1;
public RowComparer(SortOrder sortOrder)
{
if (sortOrder == SortOrder.Descending)
{
sortOrderModifier = -1;
}
else if (sortOrder == SortOrder.Ascending)
{
sortOrderModifier = 1;
}
}
public int Compare(object x, object y)
{
DataGridViewRow DataGridViewRow1 = (DataGridViewRow)x;
DataGridViewRow DataGridViewRow2 = (DataGridViewRow)y;
// Try to sort based on the Last Name column.
int CompareResult = System.String.Compare(
DataGridViewRow1.Cells[1].Value.ToString(),
DataGridViewRow2.Cells[1].Value.ToString());
// If the Last Names are equal, sort based on the First Name.
if ( CompareResult == 0 )
{
CompareResult = System.String.Compare(
DataGridViewRow1.Cells[0].Value.ToString(),
DataGridViewRow2.Cells[0].Value.ToString());
}
return CompareResult * sortOrderModifier;
}
}
答案 2 :(得分:1)
我通过将此行添加到BindingSource
来实现它this.carCheckoutBindingSource.Sort = "startMiles DESC";
答案 3 :(得分:0)
datagridview是否绑定到集合?如果是,则对集合执行排序并将已排序的集合重新绑定到datagridview
前:
collection.OrderBy(i=> i.<PropertyName>);
datagridview.DataSource = collection;
注:
我的收藏品是List。