c# - 如何在 DataGridViewComboBoxColumn 下拉列表中显示与文本框中不同的值?

标签 c# .net winforms datagridview

我有一个 DataGridViewComboBoxColumn,我应该在其中显示与所选值不同的值,就像这个问题中发生的事情一样:

DataGridViewComboBoxColumn name/value how?

在我的例子中,我显示的是具有 ID 和描述的设备列表。所以我的绑定(bind)数据类如下所示:

public class AURecord
{
    // member vars and constructors omitted for brevity
    public string ID { get { return _id; } }
    public string Description { get { return _description; } }
    public string FullDescription
    {
        get { return string.Format("{0} - {1}", _id, _description); }
    }
}

所以我将 DisplayMember 和 ValueMember 分别设置为 FullDescription 和 ID。到目前为止一切顺利。

问题是,要求要求在下拉列表中显示 FullDescription,但是一旦做出选择,只有 ID 应该出现在文本框中(要显示的描述在相邻的只读列中,我也有这个工作)。

我希望有一个解决方案只涉及更改我的网格中 DataGridViewComboBoxColumn 对象的一些属性,但我担心答案将更多地沿着创建 DataGridViewComboBoxColumn 子类和执行一堆重载的路线(呃)。 ..

最佳答案

这似乎可行:

namespace WindowsFormsApplication2
{
    using System;
    using System.Windows.Forms;

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

            _grid.CellFormatting += new DataGridViewCellFormattingEventHandler( OnGridCellFormatting );

            Column1.DisplayMember = "FullDescription";
            Column1.ValueMember = "ID";
            Column1.Items.Add( new AURecord( "1", "First Item" ) );
            Column1.Items.Add( new AURecord( "2", "Second Item" ) );
        }

        void OnGridCellFormatting( object sender, DataGridViewCellFormattingEventArgs e )
        {
            if ( ( e.ColumnIndex == Column1.Index ) && ( e.RowIndex >= 0 ) && ( null != e.Value ) )
            {
                e.Value = _grid.Rows[ e.RowIndex ].Cells[ e.ColumnIndex ].Value;
            }
        }
    }

    public class AURecord
    {
        public AURecord( string id, string description )
        {
            this.ID = id;
            this.Description = description;
        }
        public string ID { get; private set; }
        public string Description { get; private set; }
        public string FullDescription
        {
            get { return string.Format( "{0} - {1}", this.ID, this.Description ); }
        }
    }
}

关于c# - 如何在 DataGridViewComboBoxColumn 下拉列表中显示与文本框中不同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3159710/

相关文章:

c# - 如果线程还在等待,异步连接的目的是什么?

.net - 使用 DocumentViewer 控件时如何设置打印作业的名称?

vb.net - 右键单击 : menu options

c# - 强制 WinForms 重新生成 .designer.cs 文件

c# - 存储库模式中的类映射错误

c# - MSIL : Why does Array initializer use dup

c# - 使用母版页 ASP.net 时的 DefaultButton

.net - Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll的副本之间的差异

.net - 使用 Dapper 从存储过程中获取字段名称

vb.net - 将表适配器添加到数据集时出错