這是一個解決方案,用於添加到列表的頂部 - 我不知道它是否是最好的解決方案,但它的工作原理。還有很多其他方法可以解決這個問題,其中包括製作自己的綁定集合以允許插入到已排序列表中,這可以使代碼形成某些觀點,但這至少很簡單。
這裏是代碼,其中包括創建一個數據表。
public partial class Form1 : Form
{
BindingSource bs;
DataTable dt;
public Form1()
{
InitializeComponent();
dt = new DataTable("Customers");
DataColumn dc;
dc = new DataColumn();
dc.DataType = typeof(int);
dc.ColumnName = "CustomerID";
dt.Columns.Add(dc);
dt.Columns.Add(new DataColumn("LastName"));
dt.Columns.Add(new DataColumn("FirstName"));
// Concatenation of first and last names
dt.Columns.Add(new DataColumn("FullName"));
dt.Columns.Add(new DataColumn("Address"));
dt.Columns.Add(new DataColumn("City"));
dt.Columns.Add(new DataColumn("State"));
dt.Columns.Add(new DataColumn("Zip"));
dt.Columns.Add(new DataColumn("Phone"));
dc = new DataColumn();
dc.DataType = typeof(DateTime);
dc.ColumnName = "LastPurchaseDate";
dt.Columns.Add(dc);
dc = new DataColumn();
dc.DataType = typeof(int);
dc.ColumnName = "CustomerType";
dt.Columns.Add(dc);
dt.Columns.Add("HiddenSort", typeof(bool));
// Populate the table
dt.Rows.Add(2, "Baggins", "Bilbo", "Baggins, Bilbo", "Bagshot Row #1", "Hobbiton", "SH", "00001", "555-2222", DateTime.Parse("9/9/2008"), 1, false);
dt.Rows.Add(1, "Baggins", "Frodo", "Baggins, Frodo", "Bagshot Row #2", "Hobbiton", "SH", "00001", "555-1111", DateTime.Parse("9/9/2008"), 1, false);
dt.Rows.Add(6, "Bolger", "Fatty", "Bolger, Fatty", "ProudFeet Creek", "Hobbiton", "SH", "00001", "555-1111", DateTime.Parse("9/9/2008"), 1); dt.Rows.Add(4, "Elessar", "Aragorn", "Elessar, Aragorn", "Citadel", "Minas Tirith", "Gondor", "00000", "555-0000", DateTime.Parse("9/9/2008"), 4, false);
dt.Rows.Add(5, "Evenstar", "Arwin", "Evenstar, Arwin", "Citadel", "Minas Tirith", "Gondor", "00000", "555-0001", DateTime.Parse("9/9/2008"), 4, false);
dt.Rows.Add(3, "Greyhame", "Gandalf", "Grayhame, Gandalf", DBNull.Value, DBNull.Value, DBNull.Value, DBNull.Value, DBNull.Value, DBNull.Value, 3, false);
BindingSource bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
dataGridView1.Columns["HiddenSort"].Visible = false;
dataGridView1.Sorted += new EventHandler(dataGridView1_Sorted);
}
void dataGridView1_Sorted(object sender, EventArgs e)
{
foreach (DataRow dr in dt.Rows)
{
dr["HiddenSort"] = false;
}
}
private void button1_Click(object sender, EventArgs e)
{
DataRow dr = dt.Rows.Add(2, "Testing", "Bilbo", "Baggins, Bilbo", "Bagshot Row #1", "Hobbiton", "SH", "00001", "555-2222", DateTime.Parse("9/9/2008"), 1, true);
DataView dv = dt.DefaultView;
if (dataGridView1.SortedColumn == null)
{
dv.Sort = "[HiddenSort] desc";
}
else
{
string sortname = dataGridView1.SortedColumn.Name;
dv.Sort = "[HiddenSort] desc, [" + sortname + "] asc";
}
}
}
訣竅這裏增加一個新列HiddenSort來,使我們能夠進行排序基於行是否是新的或不DataTable中的數據表。結合抓取DataGridView中的排序列,可以保留舊的排序順序並保持新行的位置。
我不認爲有直接的方法來做到這一點。我能想到的唯一想法是添加一列,然後填充它,以便排序工作。 – 2012-02-21 01:14:45