using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WinformDataGridViewComboBoxDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
InitDataGridView();
}
private void InitDataGridView()
{
DataGridViewTextBoxColumn column1 = new DataGridViewTextBoxColumn();
column1.DataPropertyName = "Id";
this.dataGridView1.Columns.Add(column1);
DataGridViewTextBoxColumn column2 = new DataGridViewTextBoxColumn();
column2.DataPropertyName = "Name";
this.dataGridView1.Columns.Add(column2);
DataGridViewComboBoxColumn column3 = new DataGridViewComboBoxColumn();
column3.DataPropertyName = "Sex";
column3.DataSource = GetSex();
column3.ValueMember = "sId";
column3.DisplayMember = "sValue";
this.dataGridView1.Columns.Add(column3);
DataGridViewTextBoxColumn column4= new DataGridViewTextBoxColumn();
column4.DataPropertyName = "Comment";
this.dataGridView1.Columns.Add(column4);
List<Model> model = new List<Model>();
model.Add(new Model() { Id = 1, Name = "Name1", Sex = "b", Comment = "boy" });
model.Add(new Model() { Id = 2, Name = "Name2", Sex = "g", Comment = "gril" });
model.Add(new Model() { Id = 3, Name = "Name3", Sex = "b", Comment = "boy" });
model.Add(new Model() { Id = 4, Name = "Name4", Sex = "b", Comment = "boy" });
this.dataGridView1.DataSource = model;
}
private List<sexClass> GetSex()
{
List<sexClass> sexs = new List<sexClass>();
sexs.Add(new sexClass() { sId = "b", sValue="boy"});
sexs.Add(new sexClass() { sId = "g", sValue = "gril" });
return sexs;
}
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dataGridView1.CurrentCell.RowIndex != -1 && dataGridView1.CurrentCell.OwningColumn is DataGridViewComboBoxColumn)
{
((ComboBox)e.Control).SelectedIndexChanged += new EventHandler(Form1_SelectedIndexChanged);
}
}
void Form1_SelectedIndexChanged(object sender, EventArgs e)
{
if (((ComboBox)sender).SelectedValue.ToString() == "b")
{
dataGridView1.CurrentRow.Cells[3].Value = "boy";
}
else
{
dataGridView1.CurrentRow.Cells[3].Value = "gril";
}
((ComboBox)sender).SelectedIndexChanged -= new EventHandler(Form1_SelectedIndexChanged);
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
}
}
class sexClass
{
public string sId{get;set;}
public string sValue{get;set;}
}
}
浙公网安备 33010602011771号