form1.cs
来自「csharp课本的源代码」· CS 代码 · 共 307 行
CS
307 行
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace DataGridViewExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void buttonBindingDataSource_Click(object sender, EventArgs e)
{
if (dataGridView1.DataSource != null)
{
bindingNavigator1.BindingSource = null;
dataGridView1.DataSource = null;
}
else
{
//先绑定后填充与先填充后绑定效果相同
myTable1TableAdapter1.Fill(myDatabaseDataSet1.MyTable1);
myTable2TableAdapter1.Fill(myDatabaseDataSet1.MyTable2);
//绑定到数据源全部字段
bindingSource1.DataSource = myDatabaseDataSet1.MyTable2;
bindingNavigator1.BindingSource = bindingSource1;
dataGridView1.DataSource = bindingSource1;
}
}
private void buttonShowExpectedField_Click(object sender, EventArgs e)
{
dataGridView1.Columns["照片"].Visible = !dataGridView1.Columns["照片"].Visible;
}
private void buttonExchangeColumn_Click(object sender, EventArgs e)
{
int columnIndex = dataGridView1.Columns["学号"].DisplayIndex;
dataGridView1.Columns["学号"].DisplayIndex = dataGridView1.Columns["姓名"].DisplayIndex;
dataGridView1.Columns["姓名"].DisplayIndex = columnIndex;
}
private void buttonAutoAdjustWidth_Click(object sender, EventArgs e)
{
//根据字段和标题的最大长度调整单元格宽度
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
}
private void buttonSetAlternatingStyle_Click(object sender, EventArgs e)
{
if (dataGridView1.AlternatingRowsDefaultCellStyle.BackColor != Color.MistyRose)
{
dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.MistyRose;
}
else
{
dataGridView1.AlternatingRowsDefaultCellStyle.BackColor
= dataGridView1.RowsDefaultCellStyle.BackColor;
}
}
private void butttonFixFieldPosition_Click(object sender, EventArgs e)
{
if (dataGridView1.Columns["学号"].Frozen == false)
{
dataGridView1.Columns["学号"].Frozen = true;
dataGridView1.Columns["姓名"].Frozen = true;
dataGridView1.Dock = DockStyle.None;
dataGridView1.Width = 500;
}
else
{
dataGridView1.Columns["学号"].Frozen = false;
dataGridView1.Columns["姓名"].Frozen = false;
dataGridView1.Dock = DockStyle.Top;
}
}
private void buttonChangeCurrentCell_Click(object sender, EventArgs e)
{
Random r = new Random();
int row = r.Next(dataGridView1.Rows.Count);
int col = r.Next(dataGridView1.Columns.Count);
dataGridView1.CurrentCell = dataGridView1.Rows[row].Cells[col];
}
private void buttonModifyHeaderText_Click(object sender, EventArgs e)
{
DataGridViewColumn column = dataGridView1.Columns["学号"];
if (column.HeaderText != column.DataPropertyName)
{
//让标题与绑定的字段名称相同
column.HeaderText = column.DataPropertyName;
}
else
{
column.HeaderText = "Student ID";
}
}
private void buttonShowSelectedRows_Click(object sender, EventArgs e)
{
string selectedXueHao = "";
for (int i = dataGridView1.SelectedRows.Count - 1; i >= 0; i--)
{
selectedXueHao += string.Format("第{0}行: 学号为{1}\n",
dataGridView1.SelectedRows[i].Index,
dataGridView1.SelectedRows[i].Cells["学号"].Value);
}
MessageBox.Show(selectedXueHao, "选中的行信息");
}
private void buttonDeleteCurrentColumn_Click(object sender, EventArgs e)
{
DataGridViewCell currentCell = dataGridView1.CurrentCell;
DialogResult result = MessageBox.Show(
string.Format("确实删除[{0}]一列吗?",
dataGridView1.Columns[currentCell.ColumnIndex].HeaderText),
"小心", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
dataGridView1.Columns.Remove(
dataGridView1.Columns[currentCell.ColumnIndex]);
}
}
private void buttonShowSelectedCells_Click(object sender, EventArgs e)
{
string selectedCells = "";
for (int i = dataGridView1.SelectedCells.Count - 1; i >= 0; i--)
{
DataGridViewCell cell = dataGridView1.SelectedCells[i];
selectedCells += string.Format("第{0}行第{1}列:{2}\n",
cell.RowIndex,
cell.ColumnIndex,
cell.Value);
cell.Style.ForeColor = Color.Red;
}
MessageBox.Show(selectedCells, "选中的单元格信息");
}
private void buttonFormattedShow_Click(object sender, EventArgs e)
{
DataGridViewColumn column = dataGridView1.Columns["出生日期"];
//按年.月的形式显示
column.DefaultCellStyle.Format = "yy.M";
column.DefaultCellStyle.BackColor = Color.GreenYellow;
column.DefaultCellStyle.Font = new Font(dataGridView1.Font, FontStyle.Italic);
column.DefaultCellStyle.ForeColor = Color.Red;
column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
}
private void buttonFilter_Click(object sender, EventArgs e)
{
dataGridView1.CurrentCell.Selected = false;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
object cellValue = row.Cells["性别"].Value;
if (cellValue != null)
{
if (cellValue.ToString() == "男")
{
row.Selected = true;
}
}
}
}
private void buttonSetCellFormat_Click(object sender, EventArgs e)
{
dataGridView1.CellFormatting +=
new DataGridViewCellFormattingEventHandler(CellFormatting);
dataGridView1.Refresh();
}
private void CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dataGridView1.Columns[e.ColumnIndex].HeaderText == "成绩")
{
if (e.Value != null)
{
int grade;
if (int.TryParse(e.Value.ToString(), out grade) == true)
{
if (grade <= 60)
{
e.CellStyle.ForeColor = Color.Red;
e.CellStyle.BackColor = Color.GreenYellow;
}
}
}
}
}
private void buttonCatchException_Click(object sender, EventArgs e)
{
dataGridView1.DataError +=
new DataGridViewDataErrorEventHandler(DataError);
MessageBox.Show("添加事件成功,可以输入大于8位的学号测试捕获的异常");
}
private void DataError(object sender, DataGridViewDataErrorEventArgs e)
{
MessageBox.Show(e.Exception.Message, "出错了");
}
private void buttonCellValidating_Click(object sender, EventArgs e)
{
dataGridView1.CellValidating +=
new DataGridViewCellValidatingEventHandler(CellValidating);
MessageBox.Show("添加事件成功,可以输入不够8位或非数字学号测试捕获的异常");
}
private void CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
string errorMessage = "";
if (dataGridView1.Columns[e.ColumnIndex].Name == "学号")
{
if (e.FormattedValue == null)
{
errorMessage = "不允许空值";
}
else
{
string xuehao = e.FormattedValue.ToString();
if (xuehao.Length != 8)
{
errorMessage = "学号必须为8位数字";
}
else
{
for (int i = 0; i < xuehao.Length; i++)
{
if (char.IsDigit(xuehao[i]) == false)
{
errorMessage = "学号必须为8位数字";
break;
}
}
}
}
}
if (errorMessage.Length > 0)
{
MessageBox.Show(errorMessage, string.Format("第{0}行第{1}列有错",
e.RowIndex, e.ColumnIndex));
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = errorMessage;
}
else
{
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = null;
}
}
private void buttonUsingComboBox_Click(object sender, EventArgs e)
{
//创建下拉框对象并添加到dataGridview1中
DataGridViewComboBoxColumn comboBoxColumn = new DataGridViewComboBoxColumn();
dataGridView1.Columns.Add(comboBoxColumn);
//将新对象放在显示学院编码的原来的列位置,并删除原来的列
comboBoxColumn.DisplayIndex = dataGridView1.Columns["学院编码"].DisplayIndex;
dataGridView1.Columns.Remove(dataGridView1.Columns["学院编码"]);
//绑定MyTable2中的字段
comboBoxColumn.DataPropertyName = "学院编码";
//绑定MyTable1中的字段供选择用
comboBoxColumn.DataSource = myDatabaseDataSet1.MyTable1;
//显示的是MyTable2中编码对应的名称
comboBoxColumn.DisplayMember = "名称";
//保存的实际值是MyTable1中名称对应的编码
comboBoxColumn.ValueMember = "编码";
//设置显示的标题和Name属性,
comboBoxColumn.HeaderText = "所在学院名称";
//设置Name属性的用处是为了在代码中引用该列
comboBoxColumn.Name = "学院编码";
}
private void buttonUpdate_Click(object sender, EventArgs e)
{
try
{
myTable2TableAdapter1.Update(myDatabaseDataSet1);
MessageBox.Show("保存成功!");
}
catch (Exception err)
{
MessageBox.Show(err.Message, "保存失败");
}
}
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?