VS+C# DataGridView用法

动态创建行

//方法一 向每行的单元格中添加文本信息
Random rd = new Random();
for (int i = 0; i < 5; i++) 
{    int index = this.dataGridView1.Rows.Add();      
     this.dataGridView1.Rows[index].Cells[0].Value = "Component" + i;    
     float l_value1 = (float)rd.Next(100, 900) / (float)10;      
     this.dataGridView1.Rows[index].Cells[1].Value = 
     string.Format("{0:0.00}", l_value1);    
     this.dataGridView1.Rows[index].Cells[2].Value = "%";    
     this.dataGridView1.Rows.Add(row);
}
//方法二 向每行的单元格中添加控件
Random rd = new Random();
for (int i = 0; i < 5; i++)   
{    DataGridViewRow row = new DataGridViewRow();    
     DataGridViewButtonCell dgv_btn_cell = new DataGridViewButtonCell();    
     dgv_btn_cell.Value = "Component" + i;
     row.Cells.Add(dgv_btn_cell);
     dataGridView1.Rows.Add(row);
}

动态创建列

DataGridViewTextBoxColumn dgv_column = new DataGridViewTextBoxColumn();
dgv_column.Name = "column_component";
dgv_column.DataPropertyName = "column_component";
dgv_column.HeaderText = "Component";
dataGridView1.Columns.Add(dgv_column);

获取当前选中行

i = int.Parse(dataGridView1.SelectedRows[0].Index.ToString());
i = dataGridView1.CurrentRow.Index;
i = dataGridView1.CurrentCell.RowIndex;

基本属性

设置所有行字体

dataGridView1.RowsDefaultCellStyle.Font = new Font("宋体", 10F, FontStyle.Regular);
设置标题字体

dataGridView1.ColumnHeadersDefaultCellStyle.Font = new Font("宋体", 20F, FontStyle.Regular);
DataGridView列高行宽设置为不能编辑
DataGridView1.AllowUserToResizeColumns = False;
 DataGridView1.AllowUserToResizeRows = False;
指定列高行宽设置为不能编辑
DataGridView1.Columns(0).Resizable = DataGridViewTriState.False;
DataGridView1.Rows(0).Resizable = DataGridViewTriState.False;
行列表头部分列高行宽设置为不能编辑
DataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
DataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing;
列高行宽最小值设定
DataGridView1.Columns(0).MinimumWidth = 100;
DataGridView1.Rows(0).MinimumHeight = 50;
隐藏行列表头
dataGridView1.RowHeadersVisible = false;
dataGridView1.AllowUserToAddRows = false;
DataGridView列高行宽自动调整
DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
标题列高行宽自动调整
DataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
DataGridView1.RowHeadersWidthSizeMode =  DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
设置标题的高度
dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
dataGridView1.ColumnHeadersHeight = 40;
指定列自动调整
DataGridView1.Columns(0).AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
DataGridView指定行列冻结

列冻结(当前列以及左侧做所有列)

DataGridView1.Columns(1).Frozen = True;

行冻结(当前行以及上部所有行)

DataGridView1.Rows(2).Frozen = True;

指定单元格冻结(单元格所在行上部分所有行,列左侧所有列)

DataGridView1(0, 0). Frozen = True;
设置单元格的前景色与背景色
DataGridViewButtonCell dgv_btn_cell = new DataGridViewButtonCell();
dgv_btn_cell.Style.BackColor = Color.DarkGray;
dgv_btn_cell.Style.ForeColor = Color.Black;
动态修改单元格的前景色与背景色
private void dataGridView1_CellFormatting(object sender,DataGridViewCellFormattingEventArgs e)
{    
if (e.RowIndex != -1 && e.ColumnIndex == 1)    
  {        
   e.CellStyle.BackColor = Color.Red;            
   e.CellStyle.ForeColor = Color.Blue;    
  }
}
设置标题的前景色与背景色
dataGridView1.EnableHeadersVisualStyles = false;
dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Red;
dataGridView1.ColumnHeadersDefaultCellStyle.ForeColor= Color.Blue;
设置单元格文字居中
DataGridViewButtonCell dgv_btn_cell = new DataGridViewButtonCell();
dgv_btn_cell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
设置标题文字居中
dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
DataGridView列顺序可否变更
DataGridView1.AllowUserToOrderColumns = True;
//但是如果列冻结的情况下,冻结的部分不能变更到非冻结的部分。
//变更后列位置取得
Console.WriteLine(DataGridView1.Columns("Column1").DisplayIndex);
DataGridView1.Columns("Column1").DisplayIndex = 0;
DataGridView行复数选择
DataGridView1.MultiSelect = False;   //不可以同时选择多行,单元格选择的时候默认为选择整行
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

向单元格中添加图片[代码尚未经过验证]

https://www.cnblogs.com/huatao/p/4758418.html
https://blog.csdn.net/i1tws/article/details/77454110
https://blog.csdn.net/chengxuxiaoming/article/details/38518603

//行高列宽自动调整
DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
//
DataGridViewRow row = new DataGridViewRow();
DataGridViewImageCell imageCell = new DataGridViewImageCell();
//从资源文件中读取图片,并且规定图片大小
imageCell.Value = new BitMap(System.Drawing.Image类型的图像, width,height);
imageCell.ImageLayout = DataGridViewImageCellLayout.Stretch;//设置图形布局,对图形进行拉伸
//将图片添加至行的单元格中
row.Cells.Add(imageCell);
//将行添加至dgv中
dataGridView1.Rows.Add(row);

光标问题

在DataGridView中选中某一行后,光标总自动返回至第一行的原因

这是由于在对dgv的数据源属性进行赋值后,dgv会自动刷新,使得光标更新到第一行。
如:根据以下代码,可判断:点击dgv中某一行后光标不会更新到第一行;而点击BUTTON后光标会刷新至第一行。

修改BUTTON
注意:先求i,在对设定数据源,否则i永远为0

i = dataGridView1.CurrentRow.Index;//求当前行序号
dataGridView1.DataSource = dat.Tables[0];//设置数据源
dt = dat.Tables[0];//数据集中第一个表
dr = dt.Rows[i];//表的第i行

dgv的MouseDown事件

// hittest全局变量DataGridView.HitTestInfo hittest;
hittest = dataGridView1.HitTest(e.X, e.Y);
//MessageBox.Show(hittest.ToString());
this.dataGridView1.Rows[hittest.RowIndex].Selected = true;

dgv的MouseUp事件

i = dataGridView1.CurrentRow.Index;//i为所选行的行序号
dt = dat.Tables[0];//将dat的第一张表赋给dt
dr = dt.Rows[i];//将dt的第i行赋给dr
使光标停留在选中行

注意:将以下代码写到最后,防止其他语句隐藏着刷新操作。

dataGridView1.FirstDisplayedScrollingRowIndex = hittest.RowIndex;
dataGridView1.Rows[hittest.RowIndex].Selected = true;
dataGridView1.Rows[0].Selected = false; 

数据绑定

(1)、利用SqlDataAdapter对象向dgv中填充数据

//方法一
  //使用DataSet绑定时,同时指明DateMember 
  conn = new SqlConnection("server = DESKTOP-TP0M4VK ; database = 企业人事管理系统; Trusted_Connection=yes");//连接数据库
    conn.Open();//打开连接
  cmd = "select ID,name,sex,birplace,polistatus,birdate,edu,idcard,nation,password from person";
    adapter = new SqlDataAdapter(cmd, conn);//执行连接
    DataSet Ds = new DataSet();
    adapter.Fill(Ds);
    this.dataGridView1.DataSource = Ds; 
  this.dataGridView1.DataMember = "表名"; 
  conn.Close();//关闭连接
//方法二
    //使用DataSet绑定时,直接用DataTable来绑定 
    DataSet Ds = new DataSet();
  this.dataGridView1.DataSource = Ds.Table[0]; 
    //this.dataGridView1.DataSource = Ds.Table["表名"];
//方法三 
    //直接用DataTable绑定
    conn = new SqlConnection("server = DESKTOP-TP0M4VK ; database = 企业人事管理系统; Trusted_Connection=yes");//连接数据库
    conn.Open();//打开连接
  cmd = "select ID,name,sex,birplace,polistatus,birdate,edu,idcard,nation,password from person";
    adapter = new SqlDataAdapter(cmd, conn);//执行连接          
    DataTable Dt = new DataTable();
    adapter.Fill(Dt);
    this.dataGridView1.DataSource = Dt;
    conn.Close();
//方法四 
    //使用DataView进行绑定
    conn = new SqlConnection("server = DESKTOP-TP0M4VK ; database = 企业人事管理系统; Trusted_Connection=yes");//连接数据库
    conn.Open();//打开连接
  cmd = "select ID,name,sex,birplace,polistatus,birdate,edu,idcard,nation,password from person";
    adapter = new SqlDataAdapter(cmd, conn);//执行连接   
    DataView dv = new DataView();
    adapter.Fill(dv.ToTable());
    this.dataGridView1.DataSource = Dt;
    conn.Close();

(2)、利用ArrayList对象向dgv中填充数据

//方法一
   ArrayList Al = new ArrayList();
   for (int i = 0; i < 10; i++) 
  { 
    list.Add(new DictionaryEntry(i.ToString(),i.ToString()+"_List")); 
  } 
   this.dataGridView1.DataSource = Al;
//方法二
    ArrayList Al = new ArrayList();
    Al.Add(new PersonInfo("a","-1")); 
  Al.Add(new PersonInfo("b","-2")); 
  Al.Add(new PersonInfo("c","-3")); 
  this.dataGridView1.DataSource = Al;

(3)、利用Dictionary<string, string> 泛型对象向dgv中填充数据

   Dictionary<string, string> dic = new Dictionary<string, string>();
   for (int i = 0; i < 10; i++) 
  { 
    dic.Add(i.ToString(),i.ToString()+" "); 
  } 
   this.dataGridView1.DataSource = dic;

例:

private void Form1_Load(object sender, EventArgs e)  
{  
    //使用Dictionary<>泛型集合填充DataGridView  
    Dictionary<String, Student> students = new Dictionary<String, Student>();  
    Student hat = new Student("Hathaway", "12", "Male");  
    Student peter = new Student("Peter","14","Male");  
    Student dell = new Student("Dell","16","Male");  
    Student anne = new Student("Anne","19","Female");  
    students.Add(hat.StuName,hat);  
    students.Add(peter.StuName,peter);  
    students.Add(dell.StuName,dell);  
    students.Add(anne.StuName,anne);  
    //在这里必须创建一个BindIngSource对象,用该对象接收Dictionary<>泛型集合的对象  
    BindingSource bs = new BindingSource();  
    //将泛型集合对象的值赋给BindingSourc对象的数据源  
    bs.DataSource = students.Values;  
    this.dataGridView1.DataSource = bs;  
}

(4)、利用List 泛型对象向dgv中填充数据

   this.dataGridVi.DataSource = new BindingList<Object>(List<Object>);

例:

private void Form1_Load(object sender, EventArgs e)  
{  
    //使用List<>泛型集合填充DataGridView  
    List<Student> students = new List<Student>();  
    Student hat = new Student("Hathaway", "12", "Male");  
    Student peter = new Student("Peter","14","Male");  
    Student dell = new Student("Dell","16","Male");  
    Student anne = new Student("Anne","19","Female");  
    students.Add(hat);  
    students.Add(peter);  
    students.Add(dell);  
    students.Add(anne);  
    this.dataGridView1.DataSource = students;  
}

(5)、利用SqlDataReader对象向dgv中填充数据

SqlCommand command = new SqlCommand("select * from tablename", conn)  
SqlDataReader dr = command.ExecuteReader();  
BindingSource bs = new BindingSource();  
bs.DataSource = dr;  
this.dataGridView1.DataSource = bs;  
自定义DataGridView列的字段名称

在进行数据源绑定之后,DataGridView列的字段名称与数据库中的列字段名称一致,修改方法为:

dataGridView1.Columns[filedName].HeaderText = name;
判断绑定到DataGridView的数据是否被修改
//首先将绑定的数据源强制转化为数据表DataTable
DataTable dt = ((DataView)(this.dgvFenxzgl.DataSource)).Table.DataSet.Tables[0];  
//获得表中被修改的数据
DataTable dtModified = dt.GetChanges(DataRowState.Modified);
if (dtModified.Rows.Count > 0)//如果行数大于0.表示已经有数据被修改了
{
      //在这里我们可以获得被修改的数据
      //获得被修改的数据
      foreach (DataRow   item in dtModified.Rows)
      {
          //根据表结构获得它每行每列的值
          /*
         * item["MEIKMC"].ToString();
         * ...
         */
      }
}
检验添加至DataGridView中的数据格式是否正确
private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
    KryptonMessageBox.Show(e.Exception.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    e.Cancel = true;
}

用户点击某单元格进行编辑时,触发事件的顺序及使用

CellBeginEdit事件----CellParsing事件----CellEndEdit事件
注意:CellParsing事件中以下两句代码非常重要

  e.Value = e.Value.ToString().ToUpper();//必须是通过e.Value来获得重新输入的值,如果是通过this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()这种方法获得,那么获得值将是原来的值,并不是用户刚刚输入的值;同时该语句也正可以对用户输入的数据进行验证,如果不符合则将原来的值再赋给该单元格,不进行修改
  e.ParsingApplied = true;//必须将e.ParsingApplied属性设置为true,否则刚刚用户输入的值不会更新,还是会将原来的值赋给该单元格

去除DataGridView中自带的一行

绑定数据后,为了使用户能在这里添加数据,DataGridView控件下面会默认添加以*打头的一条新行。若希望在绑定后不显示该行,及不可以在DataGridView中直接添加行,而只能通过按钮的形式进行添加。

this.dataGridView1.AllowUserToAddRows=false;

这也是dataGridView1.Rows.Count总是比数据行数大一的原因

此外,dataGridView1.Rows.Count会随着dataGridView1.DataSource = dat.Tables[0];语句的执行而变化。变化规律我暂时没发现,等之后补充。欢迎大佬指点,感激不尽!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值