[英]Check if a dataGridView has errorText set on any of it's cells
[英]Forcing ErrorText to show in a DataGridView
我已经用谷歌和谷歌搜索过这个......
当我的应用程序启动时,它会加载一个配置文件并在 DataGridView 中显示其内容 - 包括在配置文件中发现的错误。
所以当我的方法 Main() 退出时,这里有一些关键值:
dgv.Rows[0].Cells[3].ErrorText
包含“只允许使用字母数字字符”dgv.Visible
是假的dgv.Rows[0].Cells[3].IsInEditMode
为假这是相关的代码:
public Main()
{
InitializeComponent();
dgvStationConfiguration.DataSource = FileReaderWriter.GetStationsFromConfigFile();
StationConfigurationValidator.ValidateAllCellsAndSetAllErrorMessages(dgvStationConfiguration);
}
和
public static bool ValidateAllCellsAndSetAllErrorMessages(DataGridView dgv)
{
bool areAllCellsValid = true;
foreach (DataGridViewRow row in dgv.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
bool isCellValid = ValidateCellAndSetErrorMessage(cell); // validate all cells in order to set their error text/glyphs; this flag is just to be able to return a summary
if (isCellValid == false)
{
areAllCellsValid = false;
}
}
}
return areAllCellsValid;
}
和
public static bool ValidateCellAndSetErrorMessage(DataGridViewCell cell)
{
string columnName = cell.OwningColumn.Name;
string cellValue = cell.EditedFormattedValue.ToString();
cell.ErrorText = StationConfigurationValidator.GetCellErrorMessage(columnName, cellValue);
return cell.ErrorText == string.Empty;
}
当方法完成并向用户显示 DataGridView 时,看不到红色错误字形。 如果我点击进入然后退出该单元格(即 [0][3]) - 字形出现。
我的印象是,主要问题是当设置 ErrorText 时(在方法 Main 中),DataGridView 仍然不可见。
我变得如此绝望,以至于我想到了这个令人难以置信的黑客:让计时器在 10 毫秒内关闭(以允许 Main 方法退出)以设置 ErrorText - 然后禁用(取消挂接)计时器。 这是一个我无法忍受的黑客......只是说明我的绝望...... :-(
所以......我需要做什么才能让那个字形显示???
将数据网格验证代码放在Load
事件中,而不是在构造函数中,字形将立即显示,无需处理VisibleChanged
事件。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
List<KeyValuePair<int, string>> list1 = new List<KeyValuePair<int, string>>();
list1.Add(new KeyValuePair<int, string>(1, "string 1"));
list1.Add(new KeyValuePair<int, string>(2, "string 2"));
list1.Add(new KeyValuePair<int, string>(3, "string 3 is too long."));
list1.Add(new KeyValuePair<int, string>(4, "string 4"));
list1.Add(new KeyValuePair<int, string>(5, "string 5"));
dataGridView1.DataSource = list1;
DgvValidator();
}
private void DgvValidator()
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (((string)row.Cells[1].Value).Length > 10)
row.Cells[1].ErrorText = "ERROR!";
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.