Windows Forms - Validate DataGridView input

限于喜欢 提交于 2019-12-24 17:16:00

问题


I have a Windows Forms application with a DataGridView in one of the forms. The DataGridView can insert and update through a Typed Data Set generated by Visual Studio.

I want to show user friendly error messages when a user doesnt fill in a required field or enters the wrong data type, etc. instead of the ugly huge one that is shown by default.

This page here gives some guidance. It advises me to validate input on my data sources property setters.

How can I do this with a typed dataset? I am used to working with Linq To Sql, which generated partial classes, but I am not sure about typed datasets.

Thanks.


回答1:


In terms of winforms visual feedback, I think you should look at a concept like the ErrorProvider.

If you are only focusing on input validation, like a string into an integer field this is a good approach, but please, please be aware that real validation of non-trivial mistakes shouldn't be enforced by winform's control validation event model! For example, 'EndDate < StartDate', really should be pushed down into the business layer.




回答2:


I made a generic user-friendly error message for basic validations using this code:

dataGrid.DataError += (s, e) =>
{
    if (e.Exception != null)
    {
        e.ThrowException = false;
        MessageBox.Show(this,
            String.Format("Invalid {0}",
                dataGrid.Columns[e.ColumnIndex].HeaderText),
            "Error");
    }
};

From MSDN: Walkthrough: Handling Errors that Occur During Data Entry in the Windows Forms DataGridView Control



来源:https://stackoverflow.com/questions/787360/windows-forms-validate-datagridview-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!