开发者

How to catch the control name that caused exception in C#?

I have few text boxes that should allow a certain format, but when a user enters it in a wrong format in a textbox, I would like to catch the control name and cl开发者_StackOverflow中文版ear the text of the textbox.


Clearing the user input because it's not in a given format is very user-unfriendly. What if only one of ten characters was wrong? They'd have to type it all over again. Just use a MaskedTextBox with a Mask for the pattern you expect.

When using a MaskedTextBox, you can subscribe to the MaskInputRejected event as described here:

public void Form1_Load(Object sender, EventArgs e) 
{
    ... // Other initialization code
    maskedTextBox1.Mask = "00/00/0000";
    maskedTextBox1.MaskInputRejected += new MaskInputRejectedEventHandler(maskedTextBox1_MaskInputRejected)
}

void maskedTextBox1_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
{
    toolTip1.ToolTipTitle = "Invalid Input";
    toolTip1.Show("We're sorry, but only digits (0-9) are allowed in dates.", maskedTextBox1, maskedTextBox1.Location, 5000);
}


Throwing exceptions for expected behaviour is never right as they are very expensive. If you need to see where the exception originated just check the top line of the stack trace.


debug only

you can get control name in debug mode from the yourForm.cs . i dont think this code will run on relese cuz. the source file wont be in ther release right?

using System.Diagnostics;

public void ParseControlText()
{
    try
    {
        var doubleval = Double.Parse(tb_double.Text);
        var intval    = Int32.Parse(tb_int.Text);

        //... bunch of controls need to be parssed to calculate  something

    }
    catch (FormatException ex)
    {
        var stlast = new StackTrace(ex,true).GetFrames().Last();

       //this requires   form.cs to exist . how am i gonna do this in release? idk
        var stLine = File.ReadLines(stlast.GetFileName())
            .ToList()[stlast.GetFileLineNumber()-1];
        var m = Regex.Match(stLine ,@"\((.*?)\..*?\)"); 
        var ctrlname = m.Groups[1].Value;

        MessageBox.Show( ctrlname + " control's text coundnt be Parsed! " );

    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜