小项目的感悟学习一下:
窗体的Load事件:
private void Form1_Load(object sender, EventArgs e)
{
DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
column.Name = "ID";
column.DataPropertyName = "id";//对应数据源的字段
column.HeaderText = "ID";
column.Width = 80;
this.dataGridView1.Columns.Add(column);
List<string> ListData = new List<string> { "张三", "里斯", "王六" };
DataGridViewComboBoxColumn column1 = new DataGridViewComboBoxColumn();
column1.Name = "Name";
column1.DataPropertyName = "Name";//对应数据源的字段
column1.HeaderText = "姓名";
column1.Width = 80;
this.dataGridView1.Columns.Add(column1);
column1.DataSource = ListData; //这里需要设置一下combox的itemsource,以便combox根据数据库中对应的值自动显示信息
//column1.DisplayMember = "Name";
//column1.ValueMember = "Name";
//绑定数据源
dataGridView1.DataSource = CreateTable();
}
private DataTable CreateTable()
{
DataTable dt = new DataTable();
DataColumn column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "id";
dt.Columns.Add(column);
column = new DataColumn();
column.DataType = Type.GetType("System.String");
column.ColumnName = "Name";
dt.Columns.Add(column);
DataRow row = dt.NewRow();
row["id"] = 0;
row["Name"] = "张三";
dt.Rows.Add(row);
return dt;
}
当想修改Combox列的数据时,或是想通过Combox的改变做文章的要用到dataGridView1_EditingControlShowing这个事件,即编辑dataGriview中的数据就会触发该事件
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
ComboBox combo = e.Control as ComboBox;
if (combo != null)
{
combo.SelectedIndexChanged +=
new EventHandler(ComboBox_SelectedIndexChanged);
}
}
private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox combo = sender as ComboBox;
string selectedItem = combo.Text;//拿到选择后的值
}
时间有限,写的有些匆忙!