我有一个 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/