【问题标题】:How can I display different values in a DataGridViewComboBoxColumn drop list than in the text box?如何在 DataGridViewComboBoxColumn 下拉列表中显示与文本框中不同的值?
【发布时间】:2010-07-01 16:23:46
【问题描述】:

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

DataGridViewComboBoxColumn name/value how?

就我而言,我正在显示具有 ID 和描述的设备列表。所以我绑定的数据类看起来像这样:

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 子类并进行大量重载(呃)。 ..

【问题讨论】:

    标签: c# .net winforms datagridview


    【解决方案1】:

    这似乎有效:

    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 ); }
            }
        }
    }
    

    【讨论】:

    • 似乎工作得很好。在选择期间和之后有一些奇怪的行为(完整的 id 和描述出现在下拉列表打开时和之后立即出现在单元格中),但是一旦焦点离开网格单元格,它就会启动并执行我们想要的操作。我把它从我们的 QA 中弹回来,看看我们是否能忍受这种奇怪,但我怀疑它会没事的。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-10
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    相关资源
    最近更新 更多