Datagridview对特定列进行排序

时间:2014-06-13 17:40:36

标签: c# sqlite

我有2个datagridview,我试图按一个特定列排序。我想要做的是当程序启动时我希望DGV通过降序自动按一列排序。我一直在寻找,似乎无法找到我想要的东西。

这是我要问的图像。我希望journalID列从最高位开始,然后从那里开始。

What it starts as

What I am looking for

提前致谢

3 个答案:

答案 0 :(得分:0)

private void Form1_Load(object sender, EventArgs e)
            {
                string connectionstring = @"Data Source=|DataDirectory|\Database1.sdf";
                SqlCeConnection connection = new SqlCeConnection(connectionstring);
                SqlCeCommand command = new SqlCeCommand(" SELECT * FROM journalTbl ORDER BY journalId DESC ;", connection);
                try
                {
                    SqlCeDataAdapter adapter = new SqlCeDataAdapter();
                    adapter.SelectCommand = command;
                    DataTable datatable = new DataTable();
                    adapter.Fill(datatable);
                    BindingSource bindingsource = new BindingSource();

                    bindingsource.DataSource = datatable;
                    dataGridView1.DataSource = bindingsource;
                    adapter.Update(datatable);
                }

                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);


}




        }       
  • 创建与数据库的连接,然后通过选择所需的表 一个命令
    • 在命令中包含特定功能(在本例中通过journalId Desending排序)
    • 创建数据适配器以允许数据集和数据源之间的通信
    • 创建数据表并通过数据适配器填充
    • 创建绑定源并将其分配给数据表
    • 将datagridview数据源设置为绑定源。
    • 更新适配器

Order By SQL - SQL参考

Order By clause C# MSDN参考

请注意:自订单会自动按升序排序。我也在使用Sql Compact Edition。

答案 1 :(得分:0)

我将在 Form1_Load(...)方法中添加这些行。

DataGridViewColumn columnToSort = dataGridView1.Columns["ColumnNameToSortGoesHere"];
dataGridView1.Sort(columnToSort, ListSortDirection.Descending);

答案 2 :(得分:0)

你不应该使用Code Behind。你应该学习MVVM模型和Linq库。你的工作会更好,也会更清洁。

在模型MVVM中,您解决此问题的方法是

在您的ViewModel

private ObservableCollection<string> _listModelBinding;
public ObservableCollection<string> ListModelBinding
{
    get { return _listModelBinding; }
    set { _listModelBinding= value; RaisePropertyChanged("ListModelBinding"); }
}

public MainViewModel()
{

    ListModelBinding = ListModelBinding.OrderBy(x => x.ToString());

}

在你的xaml中只需创建绑定

<DataGrid ItemsSource="{Binding ListModelBinding}" />

就是这样。

您可以使用MVVM Light NuGet在项目中使用MVVM。