DataGridView控件-学习笔记总结
1、GridColor属性用来获取或设置网格线的颜色
dataGridView1.GridColor=Color.Blue;
2、设置宽度 、高度
dataGridView1.Columns[0].Width=200; dataGridView1.Rows[0].Height = 100;
3、设置字体
dataGridView1.DefaultCellStyle.Font = new Font("隶书",14); dataGridView1.Columns[0].DefaultCellStyle.Font = new Font("宋体", 12); dataGridView1.Rows[1].DefaultCellStyle.Font = new Font("行楷", 13);
4、设置货币在DataGridView控件中的显示
dataGridView1.Columns[2].DefaultCellStyle.Format = "c";
5、设置DataGridView单元格的文本对齐方式
dataGridView1.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
6、DataGridView控件可编辑的时候验证数据输入
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { if (e.ColumnIndex == 1) { int result = 0; string before = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(); if(!int.TryParse(e.FormattedValue.ToString(),out result)) { dataGridView1.Rows[e.RowIndex].ErrorText = "年龄必须为数值类型"; e.Cancel = true; } } }
7、获取DataGridView控件中鼠标单击表格任意单元格的文本
//单击单元格 private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { //MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()); } //单击单元格内容 private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()); }
8、在单元格中换行
dataGridView1.DefaultCellStyle.WrapMode=DataGridViewTriState.True;
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace DataGridView { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btn_GridColor_Click(object sender, EventArgs e) { dgv_ShowGridColor.DataSource = new List<Student>() { new Student("张三",12,1000), new Student("李四",18,4000), new Student("王五",16,3000) }; //设置表头文本 dgv_ShowGridColor.Columns[0].HeaderText = "姓名"; dgv_ShowGridColor.Columns[1].HeaderText = "年龄"; //设置列宽度 dgv_ShowGridColor.Columns[0].Width = 100; dgv_ShowGridColor.Columns[1].Width = 70; //设置网格线颜色 dgv_ShowGridColor.GridColor = Color.Blue; //设置全局字体 dgv_ShowGridColor.Font = new Font("隶书", 12); //设置数据字体 dgv_ShowGridColor.DefaultCellStyle.Font = new Font("楷体", 11); //设置数字数据显示 dgv_ShowGridColor.Columns[2].DefaultCellStyle.Format = "c"; //设置数据填充样式 dgv的宽度一定要够长 dgv_ShowGridColor.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; //设置对齐样式 dgv_ShowGridColor.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; //全局对齐样式 //dgv_ShowGridColor.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; //换行显示过长文本 dgv_ShowGridColor.DefaultCellStyle.WrapMode = DataGridViewTriState.True; //设置行高 //dgv_ShowGridColor.Rows[2].Height = 100; ////添加列 //dgv_ShowGridColor.Columns.Add("day", "日期"); //dgv_ShowGridColor.Columns.Remove("day"); //禁止添加行和列 //dgv_ShowGridColor.AllowUserToAddRows = false; //dgv_ShowGridColor.AllowUserToDeleteRows = false; //自动排序 //for (int i = 0; i < dgv_ShowGridColor.Columns.Count; i++) //{ // dgv_ShowGridColor.Columns[i].SortMode = DataGridViewColumnSortMode.Automatic; //} //隔行换色 //for (int i = 0; i < dgv_ShowGridColor.Rows.Count; i++) //{ // if (i % 2 == 0) // { // dgv_ShowGridColor.Rows[i].DefaultCellStyle.BackColor = Color.Gray; // } //} } private void Form1_Load(object sender, EventArgs e) { //SqlConnection myConn = new SqlConnection("server=(local);database=testDB;integrated security=true"); //SqlDataAdapter mysda = new SqlDataAdapter("select * from student", myConn); //DataSet ds = new DataSet(); //mysda.Fill(ds); //dgv_ShowGridColor.DataSource = ds.Tables[0]; ////dgvData.RowHeadersVisible = false; ////btnAdd.Enabled = false; //dgv_ShowGridColor.Columns[0].ReadOnly = true; } private void button1_Click(object sender, EventArgs e) { dgv_ShowGridColor.DataSource = new List<Images>() { new Images(){_Im=Image.FromFile(System.Environment.CurrentDirectory+"\\Image\\1.bmp")}, new Images(){_Im=Image.FromFile(System.Environment.CurrentDirectory+"\\Image\\2.bmp")}, new Images(){_Im=Image.FromFile(System.Environment.CurrentDirectory+"\\Image\\3.bmp")}, new Images(){_Im=Image.FromFile(System.Environment.CurrentDirectory+"\\Image\\4.bmp")}, new Images(){_Im=Image.FromFile(System.Environment.CurrentDirectory+"\\Image\\5.bmp")}, new Images(){_Im=Image.FromFile(System.Environment.CurrentDirectory+"\\Image\\6.bmp")}, new Images(){_Im=Image.FromFile(System.Environment.CurrentDirectory+"\\Image\\7.bmp")} }; dgv_ShowGridColor.Columns[0].HeaderText = "图片"; dgv_ShowGridColor.Columns[0].Width = 70; for (int i = 0; i < dgv_ShowGridColor.Rows.Count; i++) { dgv_ShowGridColor.Rows[i].Height = 70; } } } class Student { private string name; private int age; private int money; public string _Name { get; set; } public int _Age { get; set; } public int _Money { get; set; } public Student(string name, int age,int money) { this._Name = name; this._Age = age; this._Money = money; } } class Images { private Image im; public Image _Im { get; set; } } }
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 DataGridView中添加合计和平均值 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } List<Fruit> fruit; private void button1_Click(object sender, EventArgs e) { fruit = new List<Fruit>() { new Fruit(){Name="ada",Price=12}, new Fruit(){Name="adfa",Price=23}, new Fruit(){Name="fddd",Price=22} }; dataGridView1.Columns.Add("Fruit", "水果"); dataGridView1.Columns.Add("Price", "价格"); //dataGridView1.DataSource = fruit; foreach (Fruit f in fruit) { dataGridView1.Rows.Add(new string[] { f.Name, f.Price.ToString() }); } float sum = 0; fruit.ForEach( (pp) => { sum += pp.Price; } ); dataGridView1.Rows.Add(new string[]{ "合计:"+sum.ToString(),"均价:"+(sum/fruit.Count).ToString() }); } } class Fruit { private string name; private int price; public string Name { get; set; } public int Price { get; set; } } }
eg
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Data; namespace _19事务01 { class SqlHelper { public static bool ExecDataBySqls(List<string> strSqls, string strConn) { SqlConnection sqlConn = new SqlConnection(strConn); bool boolIsSucceed = false; SqlCommand sqlCmd = new SqlCommand(); sqlCmd.Connection = sqlConn; if (sqlConn.State == ConnectionState.Closed) { sqlConn.Open(); } SqlTransaction sqlTran = sqlConn.BeginTransaction();//启动一个事务 try { sqlCmd.Transaction = sqlTran;//为事务创建一个命令 foreach (string item in strSqls) { sqlCmd.CommandType = CommandType.Text; sqlCmd.CommandText = item; sqlCmd.ExecuteNonQuery(); } sqlTran.Commit();//提交事务 boolIsSucceed = true; } catch { sqlTran.Rollback();//回滚事务,恢复数据 boolIsSucceed = false; } finally { sqlConn.Close(); strSqls.Clear(); } return boolIsSucceed; } public static DataSet DataBanding(string connStr,string selectCmdText) { using (SqlConnection conn = new SqlConnection(connStr)) { if (conn.State == ConnectionState.Closed) { conn.Open(); } SqlDataAdapter sda = new SqlDataAdapter(selectCmdText, conn); DataSet ds = new DataSet(); sda.Fill(ds, "Student"); return ds; } } } }
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; using System.Data.SqlClient; namespace _19事务01 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } string connStr = "Server=(local);DataBase=testDB;Integrated Security=true"; string selectCmdText = "select * from Student"; private void Form1_Load(object sender, EventArgs e) { dataGridView1.DataSource = SqlHelper.DataBanding(connStr, selectCmdText).Tables[0]; } private void button1_Click(object sender, EventArgs e) { List<string> strSqls = new List<string>(); string strDelete =string.Format("delete from student where stuNumber='{0}'",txtDStuNumber.Text); string strInsert = string.Format("insert into student values('{0}','{1}',{2})", txtStuNumber.Text, txtStuName.Text, txtStuAge.Text); string strSelect = "select * from student where stuNumber='2010181055'"; strSqls.Add(strDelete); strSqls.Add(strInsert); strSqls.Add(strSelect); if (SqlHelper.ExecDataBySqls(strSqls, connStr)) { MessageBox.Show("事务执行成功"); } //dataGridView1.DataSource = SqlHelper.DataBanding(connStr, selectCmdText).Tables[0]; Form1_Load(sender,e); MessageBox.Show("加载成功"); } } }
using(SqlConnection myConn=new SqlConnection(connectionText))
{
if(myConn.State==ConnectionState.Closed)
{
myConn.Open();
}
//将数据显示到DataGridView中
string selectCommandText = "select * from student";
SqlDataAdapter mySDA = new SqlDataAdapter(selectCommandText,myConn);
DataSet myDS = new DataSet();
mySDA.Fill(myDS,"student");
dgvShow.DataSource=myDS.Tables[0];
//DataTable myDT = new DataTable();
//for (int i = 0; i < dgvShow.Rows.Count;i++ )
//{
//}
}