DataGridView Usage C#

DataGridView Usage C# | DataGridView控件详细解说

  • 更改控件中的字体 | change font
// 控件中字体修改
dataGridView1.DefaultCellStyle.Font = new Font("宋体", 12); 
1
2
  • 更改控件中的字体颜色 | change font color
// 第2行第6列的字体设置成绿色
dataGridView1.Rows[1].Cells[5].Style.ForeColor = System.Drawing.Color.Green; 
1
2
  • 更改某单元格背景色 | change cell back color
// 第3行第6列单元格背景色设置为绿色
dataGridView1.Rows[2].Cells[5].Style.BackColor = System.Drawing.Color.Green; 
1
2
  • 在本控件的最下面一行,添加一条记录:| append a new row, and fill with data:
int index = this.dataGridView1.Rows.Add(); 
dataGridView1.Rows[index].Cells[0].Value = "第1列内容"; 
dataGridView1.Rows[index].Cells[1].Value = "第2列内容"; 
dataGridView1.Rows[index].Cells[2].Value = "第3列内容"; 
dataGridView1.Rows[index].Cells[3].Value = "第4列内容"; 
dataGridView1.Rows[index].Cells[4].Value = "第5列内容";
1
2
3
4
5
6
  • 在最下面一行添加一条空白行 | append a new empty row
// 添加一个空行
dataGridView2.Rows.Add(); 
1
2
  • 清空所有内容(不包含列标题)| clear all data
dataGridView2.Rows.Clear();
1
  • 清空某一行 | remove a line at specified index
dataGridView1.Rows.RemoveAt(0); //清除第一行内容(最上面一行) 
dataGridView1.Rows.RemoveAt(1); //清除第二行内容, 以此类推
1
2
  • 得到选中行的内容,选定单元格的内容 | get the current cursor row
int i = dataGridView2.CurrentRow.Index; // i表示选中行的行号(如选中第3行,则 i =2) 
textBox_x.Text = dataGridView2.Rows[i].Cells[0].Value.ToString(); //选中行的第1列放入文本框中 
textBox_y.Text = dataGridView2.Rows[i].Cells[1].Value.ToString(); //选中行的第2列放入文本框中 
textBox_z.Text = dataGridView2.Rows[i].Cells[2].Value.ToString(); //选中行的第3列放入文本框中 
textBox_u.Text = dataGridView2.Rows[i].Cells[3].Value.ToString(); //选中行的第4列放入文本框中 
textBox1.Text = dataGridView2.CurrentCell.Value.ToString(); //选中单元格的内容放入文本框中
1
2
3
4
5
6
  • 给某单元格添加内容 | change some value at row 2 and cell 3, or data[2,3]
dataGridView2.Rows[2].Cells[3].Value = “ABC”; //为第3行第4列的单元格添加内容“ABC”
1

Reference

评论