- 设置 DropDownStyle 为 DropDownList
- 将 DrawMode 改为 OwnerDrawFixed
- 添加 DrawItem 事件
- 样式就变为下面这样,但是只能在列表中选择,而不能手动输入
public class ComBox : ComboBox
{
public ComBox()
{
this.DropDownStyle = ComboBoxStyle.DropDownList;
this.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
this.DrawItem += new DrawItemEventHandler(ComBox_DrawItem);
}
void ComBox_DrawItem(object sender, DrawItemEventArgs e)
{
ComboBox cb = sender as ComboBox;
if (e.Index < 0)
{
return;
}
e.DrawBackground();
e.DrawFocusRectangle();
e.Graphics.DrawString(cb.GetItemText(cb.Items[e.Index]).ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds.X, e.Bounds.Y + 3);
}
}
public class CmbInfo
{
public int ID { get; set; }
public object ObjEnum { get; set; }
public string Name { get; set; }
}
List<CmbInfo> listCmbInfo = new List<CmbInfo>();
listCmbInfo.Add(new CmbInfo() { ID = 100, Name = "100" });
listCmbInfo.Add(new CmbInfo() { ID = 120, Name = "120" });
listCmbInfo.Add(new CmbInfo() { ID = 150, Name = "150" });
this.cmb1.DisplayMember = "Name";
this.cmb1.ValueMember = "ID";
this.cmb1.DataSource = listCmbInfo;
//这样显示的是 Name 属性,取值时可以取 ID 属性 (this.cmb1.SelectedValue)