private void Form1_Load(object sender, System.EventArgs e) ...{ DataTable dt = new DataTable("test"); dt.Columns.Add("col1",typeof(string)); DataColumn dc = new DataColumn("sys_id",typeof(int)); dc.AutoIncrement = true; dc.AutoIncrementSeed = 1; dc.AutoIncrementStep = 1; dt.Columns.Add(dc); dt.Columns.Add("col2",typeof(string)); DataColumn dc2 = new DataColumn("col3",typeof(Boolean)); dc2.DefaultValue = false; dt.Columns.Add(dc2); dt.Columns.Add("col4",typeof(decimal)); dt.Columns.Add("col5",typeof(System.DateTime)); DataRow dr = dt.NewRow(); dr["col1"] = "test"; dr["col2"] = "col2"; try ...{ dr["col3"] = true; } catch(Exception ex) ...{ MessageBox.Show(ex.ToString()); } dr["col4"] = 1.2; dr["col5"] = DateTime.Today; dt.Rows.Add(dr); DataRow dr2 = dt.NewRow(); dr2["col1"] = "test"; dr2["col2"] = "col2"; dr2["col3"] = false; dr2["col4"] = 5; dr2["col5"] = DateTime.Now; dt.Rows.Add(dr2); dataGrid1.DataSource = dt; string[] col_map,col_name; col_map = new string[6]...{"col1","col2","col3","sys_id","col4","col5"}; col_name = new string[6]...{"测试一","测试二","正确/错误","系统编号","金额","时间"}; set_styles(dataGrid1,col_map,col_name); } private void set_styles(DataGrid dg,string[] col_map,string[] col_name) ...{ DataGridTableStyle dts = new DataGridTableStyle(); DataTable dt = null; int num_col =0; string str_db_type; int li_i; if(dg.DataSource is DataView) ...{ dt = (dg.DataSource as DataView).Table; } else if(dg.DataSource is DataTable) ...{ dt = dg.DataSource as DataTable; } else if(dg.DataSource is DataSet) ...{ dt = (dg.DataSource as DataSet).Tables[0]; } dts.MappingName = dt.TableName; num_col = col_map.Length; DataGridTextBoxColumn dgbc; DataGridBoolColumn dgbl; for(li_i = 0;li_i<num_col;li_i++) ...{ str_db_type = dt.Columns[col_map[li_i].ToString().Trim()].DataType.ToString(); //MessageBox.Show(str_db_type); if(str_db_type == "System.Boolean") ...{ dgbl = new DataGridBoolColumn(); dgbl.HeaderText = col_name[li_i]; dgbl.MappingName = col_map[li_i]; dts.AlternatingBackColor = Color.Teal; dts.GridColumnStyles.Add(dgbl); } else ...{ dgbc = new DataGridTextBoxColumn(); dgbc.HeaderText = col_name[li_i]; dgbc.MappingName = col_map[li_i]; dgbc.Alignment = HorizontalAlignment.Center; dts.AlternatingBackColor = Color.Teal; dts.GridColumnStyles.Add(dgbc); } } dg.TableStyles.Add(dts); } private void button1_Click(object sender, System.EventArgs e) ...{ DataTable dt; dt = dataGrid1.DataSource as DataTable; DataRow dr = dt.NewRow(); dt.Rows.Add(dr); }