强制ErrorText显示在DataGridView中

问题描述 投票:2回答:1

我已经用Google搜索并用Google搜索了... 当我的应用程序启动时,它会加载一个配置文件并在DataGridView中显示其内容 - 包括在配置文件中找到的错误。

所以当我的方法Main()退出时,这里有一些关键值:

  • qazxsw poi包含“只允许使用字母数字字符”
  • 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;
    }

当方法完成并向用户显示DataGridView时,没有可见的红色错误字形。如果我单击然后单击该单元格(即[0] [3]) - 将出现字形。 我得到的印象是主要的问题是,当设置ErrorText时(在方法Main中),DataGridView仍然不可见。 我变得非常绝望,我正在考虑这个令人难以置信的黑客:让计时器在10ms内关闭(允许方法Main退出)设置ErrorText - 然后禁用(取消)计时器。这是一个我无法忍受的黑客...只是说明我的绝望...... :-( 所以...我需要做什么才能使该字形显示???

c# .net winforms data-binding datagridview
1个回答
1
投票

将您的数据网格验证代码放在 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; } 事件中,而不是放在构造函数中,字形将立即显示,无需处理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!"; } } }

© www.soinside.com 2019 - 2024. All rights reserved.