我有一个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子类并进行一堆重载(ugh)。 ..
答案 0 :(得分:2)
这似乎有效:
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 ); }
}
}
}