开发者

How can I display different values in a DataGridViewComboBoxColumn drop list than in the text box?

开发者 https://www.devze.com 2023-01-05 15:12 出处:网络
I have a DataGridViewComboBoxColumn where I\'m supposed to display different values than are selected, much like what\'s going on in this question:

I have a DataGridViewComboBoxColumn where I'm supposed to display different values than are selected, much like what's going on in this question:

DataGridViewComboBoxColumn name/value how?

In my case, I'm displaying lists of equipment which have an ID and a description. So my bound data class looks like this:

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

So I have the DisplayMember and ValueMember set up to开发者_如何学Python be the FullDescription and the ID, respectively. So far so good.

The problem is, the requirements call for the FullDescription to be displayed in the drop list, but once a selection is made only the ID should appear in the text box (the description is to be displayed in a neighboring read-only column, and I have that working as well).

I'm hoping for a solution that only involves changing some properties on the DataGridViewComboBoxColumn object in my grid, though I fear the answer will be more along the lines of creating a DataGridViewComboBoxColumn subclass and doing a bunch of overloading (ugh)...


This seems to work:

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

精彩评论

暂无评论...
验证码 换一张
取 消