// 数据源 source ---排序列(字段) sortfield -----List的对象Type jjType----排序属性PropertyInfo
List
private string sortfield = string.Empty;
Type jjType = typeof(jj);
System.Reflection.PropertyInfo field;
// 初始化datagridView
private void btnCSV_Click(object sender,EventArgs e)
{
System.Random r = new Random(2000);
for(int i = 0;i < 10;i++)
{
jj j = new jj();
j.J1 = r.Next().ToString();
j.J2 = r.Next().ToString();
j.J3 = r.Next().ToString();
j.J4 = r.Next().ToString();
j.J5 = r.Next().ToString();
source.Add(j);
}
this.dataGridView1.DataSource = source;
}
//自定义表头排序
private void dataGridView1_ColumnHeaderMouseClick(object sender,DataGridViewCellMouseEventArgs e)
{
this.sortfield = dataGridView1.Columns[e.ColumnIndex].Name;
source.Sort(compare);
this.dataGridView1.Invalidate();
}
// 对象
public class jj
{
private object j1;
public object J1
{
get { return j1; }
set { j1 = value; }
}
private object j2;
public object J2
{
get { return j2; }
set { j2 = value; }
}
private object j3;
public object J3
{
get { return j3; }
set { j3 = value; }
}
private object j4;
public object J4
{
get { return j4; }
set { j4 = value; }
}
private object j5;
public object J5
{
get { return j5; }
set { j5 = value; }
}
}
// 比较大小
public int compare(jj a,jj b)
{
foreach(System.Reflection.PropertyInfo p in jjType.GetProperties())
{
if(p.Name == sortfield)
{
field = p;
break;
}
}
if(field == null)
{
return 0;
}
string aa = field.GetValue(a,null).ToString();
string bb = field.GetValue(b,null).ToString();
return aa.CompareTo(bb);
}
供参考,仅示例.要用的化优化一下.尤其是compare里面的foreach.数据量多的时候影响执行速度
用BindingSource,间接绑定就可以了,或者一行行增加datagridview.Rows.Add()
我也是这个原因啊,不知道你解决了没有,我也遇到这个原因了,用datatable就可以默认排序,用List<>就不行
你说的是asp.net web里面的Gridview 列头点击排序么?