如何对除单行值之外的数据表进行排序

本文关键字:数据表 排序 单行值 | 更新日期: 2023-09-27 18:28:16

我需要对数据表进行排序,并将该数据表值加载到组合框中。然后我需要添加一个名为"全部"的新行,它应该出现在组合框项目的顶部。,这是我迄今为止的工作

DataTable dt = bLStatus.GetStatusDetail();
if (dt != null && dt.Rows.Count > 0)
 {
    dt.DefaultView.Sort= "Description ASC";
    cmbCurrentStatus.DataSource = dt;
    cmbCurrentStatus.ValueMember = "Description";
    cmbCurrentStatus.DisplayMember = "Description";
    DataRow row = dt.NewRow();
    row["Description"] = "All";
    dt.Rows.InsertAt(row, 0);                 
  }             

问题是行"All"也会被排序,我需要在顶部显示行。如何解决这个问题?任何帮助都将不胜感激。

如何对除单行值之外的数据表进行排序

您可以尝试在第0个索引处的组合框中插入"All"。语法如下:

Insert(int insertIndex, object insertItem);

例如:

cmbCurrentStatus.Items.Insert(0, (new myClass { Description = ""}));

参考:https://social.msdn.microsoft.com/Forums/en-US/762a58f5-667d-4e97-a107-86312942f966/can-i-add-items-to-a-combobox-at-a-specific-index?forum=wpf

SO中的类似帖子:在从数据库绑定数据之前,将项目添加到组合框

如果不起作用,请告诉我。

我回答了我的问题,我只需要将我的Sorted defaultView复制到另一个新的数据表中,并将行"All"添加到该数据表中并将其绑定到组合框中。如下图所示,

   DataTable dt = bLStatus.GetStatusDetail();
            if (dt != null && dt.Rows.Count > 0)
            {
                dt.DefaultView.Sort = "Description ASC";
                DataTable dt2 = dt.DefaultView.ToTable();
                DataRow row1 = dt2.NewRow();
                row1["Description"] = "All";
                dt2.Rows.InsertAt(row1, 0);
                cmbCurrentStatus.DataSource = dt2;
                cmbCurrentStatus.ValueMember = "Description";
                cmbCurrentStatus.DisplayMember = "Description";
            }