c#控件DataGridView单击列头没有自动排序,为什么?

想问一下如果用List对象来对DataGridView的DataSource进行填充,如何使其列头可以点击排序?有实现过这个的师兄请指点一下,谢谢
不是 是在winform里面

第1个回答  2011-03-18
// 数据源 source ---排序列(字段) sortfield -----List的对象Type jjType----排序属性PropertyInfo
List<jj> source = new List<jj>();
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.数据量多的时候影响执行速度
第2个回答  2011-03-18
用BindingSource,间接绑定就可以了,或者一行行增加datagridview.Rows.Add()本回答被提问者采纳
第3个回答  2013-03-17
我也是这个原因啊,不知道你解决了没有,我也遇到这个原因了,用datatable就可以默认排序,用List<>就不行
第4个回答  2011-03-18
你说的是asp.net web里面的Gridview 列头点击排序么?
相似回答