在使用过程中..DataGridView的列为字符类型..
如
dataGridView1.Columns.Add("123", "33");
dataGridView1.Rows.Add(8);
dataGridView1.Rows[0].Cells[0].Value = "10";
dataGridView1.Rows[1].Cells[0].Value = "5";
dataGridView1.Rows[2].Cells[0].Value = "11278.0";
dataGridView1.Rows[3].Cells[0].Value = "201";
dataGridView1.Rows[4].Cells[0].Value = "22";
dataGridView1.Rows[5].Cells[0].Value = "320";
dataGridView1.Rows[6].Cells[0].Value = "1.45";
dataGridView1.Rows[7].Cells[0].Value = "0.950";
我们要对这样的列进行排序
使用 ColumnHeaderMouseClick事件
private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.ColumnIndex == 0)
{
//System.Windows.Forms.DataGridViewColumnHeaderCell
if (dataGridView1.Columns[0].HeaderCell.SortGlyphDirection == SortOrder.Ascending)
{
dataGridView1.Columns[0].HeaderCell.SortGlyphDirection = SortOrder.Descending;
dataGridView1.Sort(new DataGridViewComparer(dataGridView1.Columns[0]));
}
else
{
dataGridView1.Columns[0].HeaderCell.SortGlyphDirection = SortOrder.Ascending;
dataGridView1.Sort(new DataGridViewComparer(dataGridView1.Columns[0]));
}
}
}
具体代码
/// <summary>
/// DataGridView排序
/// zgke@sina.com
/// qq:116149
/// </summary>
public class DataGridViewComparer : IComparer
{
private DataGridViewColumn m_Column;
/// <summary>
/// dataGridView1.Columns[0].HeaderCell.SortGlyphDirection = SortOrder.Descending; 根据这个进行排序列
/// </summary>
/// <param name="p_Column"></param>
public DataGridViewComparer(DataGridViewColumn p_Column)
{
m_Column = p_Column;
}
int IComparer.Compare(Object x, Object y)
{
if (m_Column == null) return -1;
decimal _X;
decimal _Y;
bool _XConvert = decimal.TryParse(((DataGridViewRow)x).Cells[m_Column.Name].Value.ToString(), out _X);
bool _YConvert = decimal.TryParse(((DataGridViewRow)y).Cells[m_Column.Name].Value.ToString(), out _Y);
int _CompareValue = _X.CompareTo(_Y);
if (m_Column.HeaderCell.SortGlyphDirection == SortOrder.Descending) return _CompareValue * -1;
return _CompareValue;
}
}