我有几个单元格DataGridView
。如何验证所有细胞并突出显示无效细胞?
填充单元后验证应该有效。
我试着用这种方式:
void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
}
但我需要为每个字段(列)设置一些验证规则。例如,检查数字或字符串。
答案 0 :(得分:4)
您可以尝试使用此代码。 当我们要编辑单元格('EmployeeName')时,它避免使用整数值。 焦点在选定单元格中丢失时显示错误消息。
这是我的模特
namespace WindowsFormsApplication1
{
public class Employee
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
public string EmployeeAddress { get; set; }
}
}
这是我的代码
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
List<Employee> EmployeeList = new List<Employee>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Employee emp = new Employee();
emp.EmployeeAddress = "polonnaruwa";
emp.EmployeeId = 1;
emp.EmployeeName = "Kasun";
EmployeeList.Add(emp);
Employee emp1 = new Employee();
emp1.EmployeeAddress = "Kandy";
emp1.EmployeeId = 2;
emp1.EmployeeName = "Bimal";
EmployeeList.Add(emp1);
Employee emp2 = new Employee();
emp2.EmployeeAddress = "New Town";
emp2.EmployeeId = 3;
emp2.EmployeeName = "ASheain";
EmployeeList.Add(emp2);
dataGridView1.DataSource = EmployeeList;
}
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (this.dataGridView1.Columns[e.ColumnIndex].Name == "EmployeeName")
{
int RowIndex = e.RowIndex;
int columnIndex = e.ColumnIndex;
if (e.Value != null)
{
string stringValue = (string)e.Value;
int val;
if (int.TryParse(stringValue, out val))
{
label1.Text = "it is integer";
dataGridView1.Rows[RowIndex].Cells[columnIndex].Value = "Please Enter String Value";
}
else
{
label1.Text = "it is not integer";
}
}
}
}
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
}
}
}