如何使 DataGridViewLinkColumn 与 DataGridView 的其余部分一起排序

2023-12-26

我使用 DataTable 作为数据源填充了 DataGridView。该数据源有一个包含注释的列。我隐藏此列作为要求的一部分,并添加了一个新的 DataGridVewLinkColumn,单击该列时用户将能够看到该评论。

我的问题是,当我通过单击 DataGridView 中的任何标题进行排序时,所有 DataGridViewLinkColumn 链接都会消失。我已在此 LinkColumn 中将 SortMode 设置为“自动”,但似乎我需要执行其他操作,因为一旦我单击网格中其他列的标题,链接就会消失。

任何人都知道如何确保当 DataGridView 排序时链接列也相应地排序?

非常感谢

好吧,我明白了。问题是因为我使用 DataTable 作为数据源,它绑定到网格,并且无法向已绑定的网格源添加额外的列并期望它将与源绑定。 为了解决这个问题我只是修改了数据表。在数据表中添加额外的列,其中包含将成为 DataGridView 中的链接的字符串,并按照中的建议以编程方式填充 DataGridViewhttp://msdn.microsoft.com/en-us/library/bxt3k60s(v=vs.90).aspx http://msdn.microsoft.com/en-us/library/bxt3k60s(v=vs.90).aspx


Windows 窗体 DataGridView 控件中的列排序模式 http://msdn.microsoft.com/en-us/library/95scxcdy(v=vs.110).aspx

当对同时包含绑定列和未绑定列的 DataGridView 控件进行排序时,无法自动维护未绑定列中的值。要维护这些值,必须通过将 VirtualMode 属性设置为 true 并处理 CellValueNeeded 和 CellValuePushed 事件来实现虚拟模式。

这有点复杂,所以最简单的解决方案是在数据表中添加一个额外的列。

我将在下面留下一个示例以供将来参考。

要点是:

  • VirtualMode应该true.
  • CellValueNeeded应正确处理以显示指定的单元格值。
  • ColumnHeaderMouseClick应正确处理以按未绑定列进行排序,并显示排序字形。

Note:

  • 为了使事情简单,本示例中的 DataGridView 是只读的。

该示例表单包含:

  • 一个类型化的 DataSet,它具有DataTable1与列ID(细绳),Comment(细绳):

    private DataSet1 dataSet1;
    
  • 绑定源:

    private BindingSource dataTable1BindingSource;
        .DataMember = "DataTable1";
        .DataSource = this.dataSet1;
    
  • 数据网格视图:

    private DataGridView dataTable1DataGridView;
        .DataSource = this.dataTable1BindingSource;
        .VirtualMode = true;
        .CellValueNeeded += this.dataTable1DataGridView_CellValueNeeded;
        .ColumnHeaderMouseClick += this.dataTable1DataGridView_ColumnHeaderMouseClick;
        .ReadOnly = true;
        .AllowUserToAddRows = false;
        .AllowUserToDeleteRows = false;
    
  • 其栏目:

    private DataGridViewTextBoxColumn iDDataGridViewTextBoxColumn;      // bound column
    private DataGridViewTextBoxColumn commentDataGridViewTextBoxColumn; // bound column
    private DataGridViewLinkColumn linkColumn;                          // unbound column
        .SortMode = DataGridViewColumnSortMode.Automatic;
    

代码如下:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    // Hold the link texts, in a dictinary
    // keyed by ID (= unique key in DataTable1), to be bound to each row.
    private SortedDictionary<string, string> _linkTexts
        = new SortedDictionary<string, string>();

    private void Form1_Load(object sender, EventArgs e)
    {
        // Bound data sample
        this.dataSet1.DataTable1.AddDataTable1Row("1", "Comment1");
        this.dataSet1.DataTable1.AddDataTable1Row("2", "Comment2");
        this.dataSet1.DataTable1.AddDataTable1Row("3", "Comment3");

        // Unbound data sample
        this._linkTexts.Add("1", "linkA");
        this._linkTexts.Add("2", "linkC");
        this._linkTexts.Add("3", "linkB");
    }

    // Handles ColumnHeaderMouseClick to do custom sort.
    private void dataTable1DataGridView_ColumnHeaderMouseClick(
        object sender, DataGridViewCellMouseEventArgs e)
    {
        // When the unbound column header is clicked,
        if (e.ColumnIndex == this.linkColumn.Index)
        {
            // Create a new DataView sorted by the link text
            // with toggling the sort order.
            DataView newView;
            switch (this.linkColumn.HeaderCell.SortGlyphDirection)
            {
                case SortOrder.None:
                case SortOrder.Descending:
                    this.linkColumn.HeaderCell.SortGlyphDirection
                        = SortOrder.Ascending;
                    newView = this.dataSet1.DataTable1
                        .OrderBy(row => this._linkTexts[row.ID])
                        .AsDataView();
                    break;

                default:
                    this.linkColumn.HeaderCell.SortGlyphDirection
                        = SortOrder.Descending;
                    newView = this.dataSet1.DataTable1
                        .OrderByDescending(row => this._linkTexts[row.ID])
                        .AsDataView();
                    break;
            }

            // Set it as DataSource.
            this.dataTable1BindingSource.DataSource = newView;

            // Clear sort glyphs on the other column headers.
            foreach (DataGridViewColumn col
                     in this.dataTable1DataGridView.Columns)
            {
                if (col != this.linkColumn)
                    col.HeaderCell.SortGlyphDirection = SortOrder.None;
            }
        }
        // The bound column header is clicked,
        else
        {
            // Sorting has done automatically.
            // Reset the sort glyph on the unbound column.
            this.linkColumn.HeaderCell.SortGlyphDirection = SortOrder.None;
        }
    }

    // Handles CellValueNeeded to show cell values in virtual mode.
    private void dataTable1DataGridView_CellValueNeeded(
        object sender, DataGridViewCellValueEventArgs e)
    {
        // Extract the bound row from the current data view.
        DataSet1.DataTable1Row row
            = (this.dataTable1BindingSource[e.RowIndex] as DataRowView)
              .Row as DataSet1.DataTable1Row;

        // For the unbound column,
        if (e.ColumnIndex == this.linkColumn.Index)
        {
            if (row.IsIDNull())
                e.Value = DBNull.Value;
            else
                // get the value from the dictionary.
                e.Value = this._linkTexts[row.ID];
        }
        // For the bound columns,
        else
        {
            // get the value from the data source.
            string propName = this.dataTable1DataGridView
                              .Columns[e.ColumnIndex].DataPropertyName;
            e.Value = row[propName];
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使 DataGridViewLinkColumn 与 DataGridView 的其余部分一起排序 的相关文章

  • 使用 gcc 在 Linux 上运行线程构建块 (Intel TBB)

    我正在尝试为线程构建块构建一些测试 不幸的是 我无法配置 tbb 库 链接器找不到库 tbb 我尝试在 bin 目录中运行脚本 但这没有帮助 我什至尝试将库文件移动到 usr local lib 但这又失败了 任何的意见都将会有帮助 确定您
  • 结构化绑定中缺少类型信息

    我刚刚了解了 C 中的结构化绑定 但有一件事我不喜欢 auto x y some func is that auto正在隐藏类型x and y 我得抬头看看some func的声明来了解类型x and y 或者 我可以写 T1 x T2 y
  • STL 迭代器:前缀增量更快? [复制]

    这个问题在这里已经有答案了 可能的重复 C 中的预增量比后增量快 正确吗 如果是 为什么呢 https stackoverflow com questions 2020184 preincrement faster than postinc
  • C# 异步等待澄清?

    我读了here http blog stephencleary com 2012 02 async and await html that 等待检查等待的看看它是否有already完全的 如果 可等待已经完成 那么该方法将继续 运行 同步
  • 没有特殊字符的密码验证器

    我是 RegEx 的新手 已经进行了大量搜索 但没有找到任何具体内容 我正在编写一个验证密码字符串的正则表达式 可接受的字符串必须至少具有 4 种字符类型中的 3 种 数字 小写字母 大写字母 特殊字符 我对包含有一个想法 也就是说 如果这
  • 通过引用传递 [C++]、[Qt]

    我写了这样的东西 class Storage public Storage QString key const int value const void add item QString int private QMap
  • C++11 删除重写方法

    Preface 这是一个关于最佳实践的问题 涉及 C 11 中引入的删除运算符的新含义 当应用于覆盖继承父类的虚拟方法的子类时 背景 根据标准 引用的第一个用例是明确禁止调用某些类型的函数 否则转换将是隐式的 例如最新版本第 8 4 3 节
  • std::vector 与 std::stack

    有什么区别std vector and std stack 显然 向量可以删除集合中的项目 尽管比列表慢得多 而堆栈被构建为仅后进先出的集合 然而 堆栈对于最终物品操作是否更快 它是链表还是动态重新分配的数组 我找不到关于堆栈的太多信息 但
  • 为什么 GCC 不允许我创建“内联静态 std::stringstream”?

    我将直接前往 MCVE include
  • -webkit-box-shadow 与 QtWebKit 模糊?

    当时有什么方法可以实现 webkit box shadow 的工作模糊吗 看完这篇评论错误报告 https bugs webkit org show bug cgi id 23291 我认识到这仍然是一个问题 尽管错误报告被标记为RESOL
  • 使用 C# 中的 CsvHelper 将不同文化的 csv 解析为十进制

    C 中 CsvHelper 解析小数的问题 我创建了一个从 byte 而不是文件获取 csv 文件的类 并且它工作正常 public static List
  • x:将 ViewModel 方法绑定到 DataTemplate 内的事件

    我基本上问同样的问题这个人 https stackoverflow com questions 10752448 binding to viewmodels property from a template 但在较新的背景下x Bind V
  • 两个类可以使用 C++ 互相查看吗?

    所以我有一个 A 类 我想在其中调用一些 B 类函数 所以我包括 b h 但是 在 B 类中 我想调用 A 类函数 如果我包含 a h 它最终会陷入无限循环 对吗 我能做什么呢 仅将成员函数声明放在头文件 h 中 并将成员函数定义放在实现文
  • LINQ:使用 INNER JOIN、Group 和 SUM

    我正在尝试使用 LINQ 执行以下 SQL 最接近的是执行交叉联接和总和计算 我知道必须有更好的方法来编写它 所以我向堆栈团队寻求帮助 SELECT T1 Column1 T1 Column2 SUM T3 Column1 AS Amoun
  • C# 动态/expando 对象的深度/嵌套/递归合并

    我需要在 C 中 合并 2 个动态对象 我在 stackexchange 上找到的所有内容仅涵盖非递归合并 但我正在寻找能够进行递归或深度合并的东西 非常类似于jQuery 的 extend obj1 obj2 http api jquer
  • 有没有办法让 doxygen 自动处理未记录的 C 代码?

    通常它会忽略未记录的 C 文件 但我想测试 Callgraph 功能 例如 您知道在不更改 C 文件的情况下解决此问题的方法吗 设置变量EXTRACT ALL YES在你的 Doxyfile 中
  • C# 中的 IPC 机制 - 用法和最佳实践

    不久前我在 Win32 代码中使用了 IPC 临界区 事件和信号量 NET环境下场景如何 是否有任何教程解释所有可用选项以及何时使用以及为什么 微软最近在IPC方面的东西是Windows 通信基础 http en wikipedia org
  • 当文件流没有新数据时如何防止fgets阻塞

    我有一个popen 执行的函数tail f sometextfile 只要文件流中有数据显然我就可以通过fgets 现在 如果没有新数据来自尾部 fgets 挂起 我试过ferror and feof 无济于事 我怎样才能确定fgets 当
  • DotNetZip:如何提取文件,但忽略zip文件中的路径?

    尝试将文件提取到给定文件夹 忽略 zip 文件中的路径 但似乎没有办法 考虑到其中实现的所有其他好东西 这似乎是一个相当基本的要求 我缺少什么 代码是 using Ionic Zip ZipFile zf Ionic Zip ZipFile
  • 类型或命名空间“MyNamespace”不存在等

    我有通常的类型或命名空间名称不存在错误 除了我引用了程序集 using 语句没有显示为不正确 并且我引用的类是公共的 事实上 我在不同的解决方案中引用并使用相同的程序集来执行相同的操作 并且效果很好 顺便说一句 这是VS2010 有人有什么

随机推荐