English 中文(简体)
如何在Windows表格应用中实施控制验证?
原标题:How to implement control validation in a Windows Forms application?

我正试图更好地了解验证如何在视窗申请中发挥作用。 互联网完全是三维例子,但我找不到解释控制验证的单一非属地例子。 经由、SwDevMan81 Hans Passant 我的起点比昨天要好得多。

“实际应用”与许多文本Box控制有方言。 每一项控制都实施。 如你能见到,ValidateChildren是因为。 附录还使用ErrorProvider控制,以提供用户反馈。 昨天,我不理解如何利用奥克塔顿克事件来进行这一验证。 今天,我的方言按预期奏效。 击落Okotaton使ErrorProvider在控制无效、方言不意关闭的情况下做事。

因此,虽然这似乎奏效,但我仍认为我“不在此列”。 是否有“最佳做法”文件/网站在Windows格式应用中进行控制验证?

在仍然混淆了我的许多事情中,我无法在奥克塔顿·拉夫=“http://msdn.microsoft.com/en-us/library/system.windows.forms.form.dialogresult.aspx” rel=“nofollow noreferer”_DialogResult 财产被送回

我昨天(似乎)出现的问题主要来自不理解ValidateChildren方法,以及我把奥克塔顿·迪亚洛Result财产交给DialogResult。 OK。 将该财产交给DialogResult。 表格类别中的一些自动行为似乎没有改变。

TIA

using System;
using System.ComponentModel;
using System.Windows.Forms;

namespace ConsoleApp
{
    class Program
    {
        static void Main( string[] args )
        {
            Dialog dialog = new Dialog();

            if( dialog.ShowDialog() == DialogResult.OK )
                Console.Beep();
        }
    }

    public class Dialog : Form
    {
        TextBox m_TextBox0;
        TextBox m_TextBox1; // not validated
        TextBox m_TextBox2;

        Button m_OkBtn;
        Button m_CancelBtn;

        ErrorProvider m_ErrorProvider;

        public Dialog()
        {
            m_TextBox0 = CreateTextBox( 0, "TextBox 0" );
            m_TextBox1 = CreateTextBox( 1, "TextBox 1" );
            m_TextBox2 = CreateTextBox( 2, "TextBox 2" );

            m_OkBtn     = CreateButton( 3, "Ok" );
            m_CancelBtn = CreateButton( 4, "Cancel" );

            m_ErrorProvider = new ErrorProvider( this );

            //m_BtnOk.DialogResult = DialogResult.OK;
            m_OkBtn.Click += new EventHandler( BtnOk_Click );
            m_OkBtn.CausesValidation = true;

            m_CancelBtn.DialogResult = DialogResult.Cancel;
            m_CancelBtn.CausesValidation = false;
        }

        void BtnOk_Click( object sender, EventArgs e )
        {
            if( ValidateChildren() )
            {
                DialogResult = DialogResult.OK;
                Close();
            }
        }

        void TextBox_Validating( object sender, CancelEventArgs e )
        {
            m_ErrorProvider.Clear();

            TextBox textBox = sender as TextBox;

            // m_TextBox1 is always valid, the others are valid if they have text.
            bool valid = textBox.TabIndex == 1 || textBox.Text.Length > 0;

            if( !valid )
                m_ErrorProvider.SetError( textBox, "Error " + textBox.Name );

            e.Cancel = !valid;
        }

        Button CreateButton( int index, string name )
        {
            Button button = new Button();

            button.TabIndex = index;
            button.Text = name;
            button.Location = new System.Drawing.Point( 0, index * 30 );

            Controls.Add( button );

            return button;
        }

        TextBox CreateTextBox( int index, string name )
        {
            Label label = new Label();
            label.Text = name;
            label.Location = new System.Drawing.Point( 0, index * 30 );

            TextBox textBox = new TextBox();

            textBox.TabIndex = index;
            textBox.CausesValidation = true;
            textBox.Validating += new CancelEventHandler( TextBox_Validating );
            textBox.Location = new System.Drawing.Point( 100, index * 30 );

            Controls.Add( label );
            Controls.Add( textBox );

            return textBox;
        }
    }
}

Edit:这里是最终解决办法。 我认为,在满足所有其他要求的同时,很容易使用。 我预先对该问题持续多久表示歉意。 如果我能向大家展示所有真正的应用,那将更有意义。 无论如何,由于帮助这一老的狗学习了一个新的trick。

答案是为需要验证的每一种控制创建一名ErrorProvider(五)为整个方言提供一名ErrorProvider。 之后,这完全简单。

using System;
using System.ComponentModel;
using System.Windows.Forms;

namespace ConsoleApp
{
    class Program
    {
        static void Main( string[] args )
        {
            Dialog dialog = new Dialog();

            if( dialog.ShowDialog() == DialogResult.OK )
                Console.Beep();
        }
    }

    public class CompositeControl
    {
        Label         m_Label;
        TextBox       m_TextBox;
        ErrorProvider m_ErrorProvider;

        Dialog m_Dialog;

        public CompositeControl( int index, string name, Dialog dialog )
        {
            m_Label = new Label();
            m_Label.Text = name;
            m_Label.Location = new System.Drawing.Point( 0, index * 30 );

            m_TextBox = new TextBox();

            m_TextBox.TabIndex = index;
            m_TextBox.CausesValidation = true;
            m_TextBox.Validating += new CancelEventHandler( TextBox_Validating );
            m_TextBox.Location = new System.Drawing.Point( 100, index * 30 );

            m_Dialog = dialog;

            m_ErrorProvider = new ErrorProvider( m_Dialog );

            m_Dialog.Controls.Add( m_Label );
            m_Dialog.Controls.Add( m_TextBox );
        }

        void TextBox_Validating( object sender, CancelEventArgs e )
        {
            TextBox textBox = sender as TextBox;

            if( !m_Dialog.IsClosing && textBox.Text.Length == 0 )
                return;

            // m_TextBox1 is always valid, the others are valid if they have text.
            bool valid = textBox.TabIndex == 1 || textBox.Text.Length > 0;

            if( !valid )
                m_ErrorProvider.SetError( textBox, "Error " + textBox.Name );
            else
                m_ErrorProvider.Clear();

            e.Cancel = !valid;
        }
    }

    public class Dialog : Form
    {
        CompositeControl m_CompositeControl0;
        CompositeControl m_CompositeControl1; // not validated
        CompositeControl m_CompositeControl2;

        Button m_OkBtn;
        Button m_CancelBtn;

        bool m_IsClosing = false;

        public Dialog()
        {
            m_CompositeControl0 = new CompositeControl( 0, "TextBox 0", this );
            m_CompositeControl1 = new CompositeControl( 1, "TextBox 1", this );
            m_CompositeControl2 = new CompositeControl( 2, "TextBox 2", this );

            m_OkBtn     = CreateButton( 3, "Ok" );
            m_CancelBtn = CreateButton( 4, "Cancel" );

            //m_BtnOk.DialogResult = DialogResult.OK;
            m_OkBtn.Click += new EventHandler( BtnOk_Click );
            m_OkBtn.CausesValidation = true;

            m_CancelBtn.DialogResult = DialogResult.Cancel;
            m_CancelBtn.CausesValidation = false;
        }

        void BtnOk_Click( object sender, EventArgs e )
        {
            m_IsClosing = true;

            if( ValidateChildren() )
            {
                DialogResult = DialogResult.OK;
                Close();
            }

            m_IsClosing = false;
        }

        Button CreateButton( int index, string name )
        {
            Button button = new Button();

            button.TabIndex = index;
            button.Text = name;
            button.Location = new System.Drawing.Point( 0, index * 30 );

            Controls.Add( button );

            return button;
        }

        public bool IsClosing { get { return m_IsClosing; } }
    }
}

这个问题是one的后续问题。 我昨天曾问过这一点。

最佳回答

转让<代码>DialogResult 财产是指使方言终结。 该系统在设计成<条码>时保持运行。 页: 1 电话ShowDialog()的代码有<代码>DialogResult,价值被指定为收益价值。 因此,委员会知道该方言是否与科索沃关闭,还是刚刚取消。

Also note that the way you wrote the validation event handler, you don t need ValidateChildren(). You set e.Cancel = true to prevent the user from moving away from the text box. Which means that she can only get to the OK button when the text box was validated to be okay. You do however have to make sure that a control that has validation is selected first when the dialog is shown.

一种友好的方言是,用户可以自由在控制与轻松的控制之间穿刺。 现在,你们需要两个验证,一个是,如果输入值有效,就进行核查,另一个是,如果不存在缺失的数值,则进行检查。 你们通过在瓦莱德事件手里接受空洞的str。 但是,后者没有得到Winforms的支持,你们需要制定法典。

问题回答

我知道这一点有些晚了,但我想在汉斯的答复中再补充一点。 创立一个文本箱活动,并转而移动。 明确无误。 在确认完整(e.cancel = 虚假)时,便发射经证实的事件。 因此,你会这样做:


void TextBox_Validating( object sender, CancelEventArgs e ) {
    TextBox textBox = sender as TextBox;

    bool valid = textBox.TabIndex == 1 || textBox.Text.Length > 0;

    if( !valid )
        m_ErrorProvider.SetError( textBox, "Error " + textBox.Name );

    e.Cancel = !valid;
}

private void TextBox_Validated(object sender, System.EventArgs e) {
    TextBox textBox = sender as TextBox;
    m_ErrorProvider.SetError(textBox, "");
}




相关问题
Bring window to foreground after Mutex fails

I was wondering if someone can tell me what would be the best way to bring my application to the foreground if a mutex was not able to be created for a new instance. E.g.: Application X is running ...

How to start WinForm app minimized to tray?

I ve successfully created an app that minimizes to the tray using a NotifyIcon. When the form is manually closed it is successfully hidden from the desktop, taskbar, and alt-tab. The problem occurs ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

Handle DataTable.DataRow cell change event

I have a DataTable that has several DataColumns and DataRow. Now i would like to handle an event when cell of this DataRow is changed. How to do this in c#?

Apparent Memory Leak in DataGridView

How do you force a DataGridView to release its reference to a bound DataSet? We have a rather large dataset being displayed in a DataGridView and noticed that resources were not being freed after the ...

ALT Key Shortcuts Hidden

I am using VS2008 and creating forms. By default, the underscore of the character in a textbox when using an ampersand is not shown when I run the application. ex. "&Goto Here" is not ...

WPF-XAML window in Winforms Application

I have a Winforms application coded in VS C# 2008 and want to insert a WPF window into the window pane of Winforms application. Could you explain me how this is done.

热门标签