dataGridView添加下拉框列
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 DataGridViewMX
{
public partial class FrmMain : Form
{
bool _启动 = true;
public FrmMain()
{
InitializeComponent();
}
private void FrmMain_Load(object sender, EventArgs e)
{
int 列数 = 5;
int 行数 = 10;
int 选项数 = 10;
// 1 建立数据
DataTable dt1 = new DataTable();
for (int i = 0; i < 列数; i++)
{
dt1.Columns.Add("第 " + i.ToString() + " 列");
}
for (int i = 0; i < 行数; i++)
{
dt1.Rows.Add();
for (int j = 0; j < 列数; j++)
{
dt1.Rows[i][j] = "测试" + (i + j).ToString();
}
}
dataGridView1.DataSource = dt1;
// 2 搜建ComboBox
DataGridViewComboBoxColumn dcon = new DataGridViewComboBoxColumn();
dcon.Name = "选项";
dataGridView1.Columns.Insert(0, dcon);
// 3 赋值ComboBox
DataTable dt2 = new DataTable();
dt2.Columns.Add("选项");
for (int i = 0; i < 选项数; i++)
{
dt2.Rows.Add();
dt2.Rows[i][0] = "测试" + i.ToString();
}
dcon.DataSource = dt2;
dcon.DisplayMember = "选项";
dcon.ValueMember = "选项";
// 4 选择ComboBox
try
{
for (int i = 0; i < 行数; i++)
{
((DataGridViewComboBoxCell)dataGridView1.Rows[i].Cells[0]).Value = dt1.Rows[i][0].ToString();
}
}
catch { }
_启动 = false;
}
private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
//MessageBox.Show("第 " + e.RowIndex.ToString() + " 行,第 " + e.ColumnIndex.ToString() + " 列");
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
//MessageBox.Show("第 " + e.RowIndex.ToString() + " 行,第 " + e.ColumnIndex.ToString() + " 列");
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
//if (!_启动) MessageBox.Show("第 " + e.RowIndex.ToString() + " 行,第 " + e.ColumnIndex.ToString() + " 列");
}
}
}
运行效果截图