我已经在 Google 上搜索了一遍……
当我的应用程序启动时,它会加载一个配置文件并在 DataGridView 中显示其内容 - 包括在配置文件中发现的错误。
因此,当我的方法 Main() 退出时,以下是一些关键值:
dgv.Rows[0].Cells[3].ErrorText
包含“仅允许字母数字字符”dgv.Visible
为 Falsedgv.Rows[0].Cells[3].IsInEditMode
为 False
相关代码如下:
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 - 然后禁用(取消 Hook )计时器。这真是一个黑客,我无法忍受...只是说明我的绝望... :-(
所以... 我需要什么如何使该字形显示???
最佳答案
将数据网格验证代码放在 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!";
}
}
}
关于c# - 强制 ErrorText 显示在 DataGridView 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31750507/