最近常在使用DataGridView這個元件然而使用上很多好玩的地方,比如自己加上欄位然後設定欄位屬性等等,那我來介紹如何用程式自己加DataGridViewComboBoxColumn欄位格式
先新增2個物件,因為DataGridView使用的是DataGridViewComboBoxColumn而不是CombBox
DataGridViewComboBoxColumn cboProductCast = new DataGridViewComboBoxColumn();
DataGridViewComboBoxCell cellProductCast = new DataGridViewComboBoxCell();
# region 自訂ComboData物件
///
/// 設定取的自訂ComboData內容
///
public class ComboData
{
private string m_display = string.Empty;
private string m_value = string.Empty;
public ComboData(string display, string value)
{
this.m_display = display;
this.m_value = value;
}
public string Display
{
get { return this.m_display; }
set { this.m_display = value; }
}
public string Value
{
get { return this.m_value; }
set { this.m_value = value; }
}
}
# endregion
private void Form_Load(object sender, EventArgs e)
{
cellProductCast.Items.Add(new ComboData("男生","W"));
cellProductCast.Items.Add(new ComboData("女生","M"));
cellProductCast.DisplayMember = "Display";
cellProductCast.ValueMember = "Value";
cellProductCast.MaxDropDownItems = 12;
cellProductCast.DropDownWidth = 10;
cellProductCast.Sorted = true;
cellProductCast.DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox;
cellProductCast.AutoComplete = true;
cboProductCast.CellTemplate = cellProductCast;
cboProductCast.Width = 150;
cboProductCast.HeaderText = "性別";
dataGridView1.Columns.Add(cboProductCast);
dataGridView1.Columns[6].DisplayIndex = 0; //<---Columns[6]是我自訂的欄位編號
}
沒有留言:
張貼留言