怎么在代码中设置dataGridView中的某个单元格为选定状态

2024-11-27 08:56:34
推荐回答(1个)
回答1:

namespace WinFormCSharp
{
public partial class Form1 : Form
{
DataGridView dv = new DataGridView();
DataTable dt = new DataTable();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{

dv.Parent = this;
dv.Dock = DockStyle.Fill;
dv.DataError += new DataGridViewDataErrorEventHandler(dv_DataError);
dv.CellValidated +=new DataGridViewCellEventHandler(dv_CellValidated);
dt.Columns.Add("money", typeof(decimal));
dt.Rows.Add(10.2m);
dv.DataSource = dt;
dt.AcceptChanges();
}
void dv_CellValidated(object sender, DataGridViewCellEventArgs e)
{
//通过了检测,保存上一次的数值
dt.AcceptChanges();
}
void dv_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
//出错时候,自动更正为默认值
MessageBox.Show("输入数据错误,自动恢复到原来数值!");
dv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = dt.Rows[e.RowIndex][e.ColumnIndex, DataRowVersion.Original]; //恢复成默认数值
e.Cancel = false;
}
}
}