日期:2014-05-19  浏览次数:20897 次

如何在vs2003 winform的datagrid里增加一列checkbox?
如题

------解决方案--------------------
好久 都没有用 VS2003

工具也被我 卸掉了.
------解决方案--------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace test
{
public partial class f_datagrid : Form
{
public f_datagrid()
{
InitializeComponent();
PopulateGrid();
}

private void f_datagrid_Load(object sender, EventArgs e)
{

}
// public FrmCustomerDataGrid()
//{
// InitializeComponent();
// PopulateGrid();
//}
DataTable dt;
private void PopulateGrid()
{
///创建填充数据的表结构
dt = new DataTable ( "dtPerson ");
string [] strTitles = new string [3] { "姓名 ", "学历 ", "职务 "};
DataColumn dc = null;

//创建前面三列,全部是字符串类型,第一列列名为 "姓名 ",第二列为“学历”,第三列“职务”
for(int i = 0; i < 3; i++)
{
dc = new DataColumn(strTitles[i]);
dc.DataType = Type.GetType( "System.String ");
dc.DefaultValue = string.Empty;
dt.Columns.Add(dc);
}

//创建第四列,Bool类型,列名 "在职 "
dc = new DataColumn( "在职 ");
dc.DataType = System.Type.GetType( "System.Boolean ");
dc.DefaultValue = false;
dt.Columns.Add(dc);

//指定DataGrid数据源
dbgNewGrid.DataSource = dt;

//为定义的DataGrid取名 "Style_Person "

if(!dbgNewGrid.TableStyles.Contains( "Style_Person "))
{
//定制DataGridTableStyle,用于整个DataGrid
DataGridTableStyle dbgStyle = new DataGridTableStyle();
dbgStyle.MappingName = dt.TableName;
dbgNewGrid.TableStyles.Add(dbgStyle);
dbgStyle.RowHeadersVisible = false;
dbgStyle.HeaderBackColor = Color.LightSteelBlue;
dbgStyle.AllowSorting = false;
dbgStyle.HeaderBackColor = Color.FromArgb(8,36,107);
dbgStyle.RowHeadersVisible = false;
dbgStyle.HeaderForeColor = Color.White;
dbgStyle.HeaderFont = new System.Drawing.Font( "Microsoft Sans Serif ", 9F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
dbgStyle.GridLineColor = Color.DarkGray;
dbgStyle.PreferredRowHeight = 22;
dbgNewGrid.BackgroundColor = Color.White;

//通过GridColumnStyles设置列属性,以下设置列的宽度
GridColumnStylesCollection colStyle = dbgNewGrid.TableStyles[0].GridColumnStyles;
colStyle[0].Width = 50;//姓名
colStyle[1].Width = 100;//学历
colStyle[2].Width = 50;//职务
colStyle[3].Width = 40;//是否在职
}

//下面定制“学历”列,这里若要定制其他列可以修改GridColumnStyles[1]中的数值
DataGridTextBoxColumn dgTextBoxColumn = (DataGridTextBoxColumn)dbgNewGrid.TableStyles[0].GridColumnStyles[1];
//定制为ComboBox类型,若想定义成其他类型的可以在这里定制
ComboBox dgComboBoxColumn = new ComboBox();
dgComboBoxColumn.Items.AddRange(new object[]{ "本科 ", "硕士 ", "博士 "});//添加选项
dgComboBoxColumn.Cursor = Cursors.Arrow;
dgComboBoxColumn.DropDownStyle= ComboBoxStyle.DropDownList;
dgComboBoxColumn.Dock = DockStyle.Fill;
///在选定项发生更改并且提交了该更改后发生

dgComboBoxColumn.SelectionChangeCommitted += new EventHandler(dgComboBoxColumn_SelectionChangeCommitted);
///把ComboBox添加到DataGridTableStyle的第一列