Page 1 of 2 1 2 LastLast
Results 1 to 30 of 31
  1. #1
    Rusted... dashing.sujay's Avatar
    Join Date
    Nov 2009
    Location
    Bhopal
    Posts
    4,113

    Default C#: Exception handling(?)

    I have recently started learning C#. I was making a simple form application to calculate sum of fruits (checked through checkboxes) and quantity entered.

    Problem is coming in quantity.

    Code:
    if (Convert.ToInt32(textBox1.Text) > 0)
                {
                    if (checkBox1.Checked)
                    {
                        qua1 = Convert.ToInt32(textBox1.Text);
                    }
                    else
                    {
                        MessageBox.Show("Please Check the respective items before entering values.");
                    }
                }
                else
                {
                    MessageBox.Show("Value of Quantity should be positive");
                    qua1 = 0;
                    textBox1.Text = "0";
                }
    Exception is occuring in bold line when I'm running the program without entering any value textBox1 (quantity). Default value is 0. One thing is understood that exception is occuring due to the fact the compiler is in dilemma when it has to convert a blank value (" ") to an int which is rendering an exception. How to handle it?

    Another query. I have restricted entry of values in textBoxes to numerics only by using this-

    Code:
    private void textBox1_KeyPress_1(object sender, KeyPressEventArgs e)
            {
                e.Handled = !char.IsDigit(e.KeyChar);
            }
    But this is also blocking backspace to work, del is working though. I want backspace to work. My teacher told me a solution based on e.handled only but it was too complex for me too understand (its been few days since I started learning it).

    TIY
    FAQ + answers for new members (Read before asking / messaging any moderator for any query)

    Drop Box: Get 500MB free


    Spoiler:

    Quote Originally Posted by axes2t2 View Post
    Before working on a master piece you have to first master the pieces.
    Sony Vaio CB35 Asus U32U ATH M20 Fiio E6

    Sony Vaio CB35 UnBoxing & Review

    How fast can you type?

  2. #2
    VIP RazorbladeXtreme's Avatar
    Join Date
    May 2008
    Location
    Jaipur
    Posts
    239

    Default Re: C#: Exception handling(?)

    why not change if (Convert.ToInt32(textBox1.Text) > 0)
    to if (textBox1.Text !="" && Convert.ToInt32(textBox1.Text) > 0)
    Twitter: twitter.com/SharmaTushar
    Facebook: facebook.com/tushar.sharma

  3. #3
    XLr8 arpanmukherjee1's Avatar
    Join Date
    Sep 2008
    Posts
    626

    Default Re: C#: Exception handling(?)

    Change this
    Quote Originally Posted by dashing.sujay View Post
    Code:
    private void textBox1_KeyPress_1(object sender, KeyPressEventArgs e)
            {
                e.Handled = !char.IsDigit(e.KeyChar);
            }
    to something

    Code:
    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
            {
                bool isValidKey = char.IsDigit(e.KeyChar) || 
                                           e.KeyChar == '\b';
                e.Handled = !isValidKey;
            }
    if e.Handled is TRUE then the key press is muted
    see ref. KeyPressEventArgs.Handled Property (System.Windows.Forms)
    There are more things in heaven and earth, Horatio,
    Than are dreamt of in your philosophy.

  4. #4
    Master KOD3R nbaztec's Avatar
    Join Date
    Sep 2010
    Location
    New Delhi
    Posts
    342

    Default Re: C#: Exception handling(?)

    Quote Originally Posted by dashing.sujay View Post
    Exception is occuring in bold line when I'm running the program without entering any value textBox1 (quantity). Default value is 0. One thing is understood that exception is occuring due to the fact the compiler is in dilemma when it has to convert a blank value (" ") to an int which is rendering an exception. How to handle it?
    You are doing things wrong and/or you got the basics wrong.

    Convert.ToInt32() expects a number as a string (in the current overloaded form), An empty string is NOT a number, it's NOT null, it's just a string with length 0, i.e. an empty string. On the other hand "0", "1234", "65535" are numeric strings.
    You might be confused since in C++, NULL was an int(0).

    You should instead be handling the FormatException:
    Code:
         int value = 0;
         try{
              value = Convert.ToInt32(value);
         } catch(FormatException){
               MessageBox.show("Please enter only numbers", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
    But looking closely you don't need Convert.ToInt32() since it's primarily used for much complex conversions from bytes, you can do away with just :
    Code:
         int.Parse(value);
    or better, simply use:
    Code:
         int intVal;
         if(int.TryParse(value, out intVal)){
              // intVal is initialized to either the value or 0
         } else{
              MessageBox.show("Please enter only numbers", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }

    Quote Originally Posted by dashing.sujay View Post
    Code:
    private void textBox1_KeyPress_1(object sender, KeyPressEventArgs e)
            {
                e.Handled = !char.IsDigit(e.KeyChar);
            }
    But this is also blocking backspace to work, del is working though. I want backspace to work. My teacher told me a solution based on e.handled only but it was too complex for me too understand (its been few days since I started learning it).

    TIY
    I remember doing a similar thing eons ago. What I learnt was it wasn't worth it using this validation approach. Using this way, you effectively block out numerous valid keys out of the textbox which are not numeric, eg: Backspace, Del, Home, Ctrl/Shift, +/-, etc.
    The proper way is to just validate on form submit, or if you are hell bent upon a KeyEvent validation, might I suggest doing it like this (the way I did it long ago):

    Code:
            private string _valid = "";
            private void textBox1_TextChanged(object sender, EventArgs e)
            {
                int t;
                if (int.TryParse(this.textBox1.Text + "0", out t))
                    this._valid = this.textBox1.Text;
                else
                    this.textBox1.Text = this._valid;
            }
    Last edited by nbaztec; 29-07-2012 at 02:08 PM.
    AMD Phenom II X6 1055T|MSI 880GMA-E45|MSI 7770|2x2 Corsair DDR3 1333MHz|CM Elite 310|Corsair CX400W|DELL ST2320L
    Myself @ nbaztec.co.in
    Build Your Rig! (XBlade) @ nbaztec.co.in - Build Your Rig!
    My Inner Artist @ nbaztec.co.in - Designs

  5. #5
    122.26.11.85 Zangetsu's Avatar
    Join Date
    Jan 2008
    Location
    Soul Society
    Posts
    6,702

    Default Re: C#: Exception handling(?)

    Quote Originally Posted by dashing.sujay View Post
    Another query. I have restricted entry of values in textBoxes to numerics only by using this-

    Code:
    private void textBox1_KeyPress_1(object sender, KeyPressEventArgs e)
            {
                e.Handled = !char.IsDigit(e.KeyChar);
            }
    But this is also blocking backspace to work, del is working though. I want backspace to work. My teacher told me a solution based on e.handled only but it was too complex for me too understand (its been few days since I started learning it).
    use java script function for blocking keys which will much easier & faster than server-side validation
    HTC One V | Nokia 5233 | Nikon D3100 | Apple Ipod Touch 4G | Sound Magic PL21 | Sound Magic ES18

  6. #6
    Rusted... dashing.sujay's Avatar
    Join Date
    Nov 2009
    Location
    Bhopal
    Posts
    4,113

    Default Re: C#: Exception handling(?)

    ^I don't know JS.
    FAQ + answers for new members (Read before asking / messaging any moderator for any query)

    Drop Box: Get 500MB free


    Spoiler:

    Quote Originally Posted by axes2t2 View Post
    Before working on a master piece you have to first master the pieces.
    Sony Vaio CB35 Asus U32U ATH M20 Fiio E6

    Sony Vaio CB35 UnBoxing & Review

    How fast can you type?

  7. #7
    Rubik's Uncle!! RCuber's Avatar
    Join Date
    Sep 2004
    Location
    ಬೆಂಗಳೂರು (Bengaluru)
    Posts
    5,879

    Default Re: C#: Exception handling(?)

    ^^ its a windows app

    Sujay, when are you initiating the calculation?
    the cake is a lie
    621311.251521

  8. #8
    Master KOD3R nbaztec's Avatar
    Join Date
    Sep 2010
    Location
    New Delhi
    Posts
    342

    Default Re: C#: Exception handling(?)

    Quote Originally Posted by Zangetsu View Post
    use java script function for blocking keys which will much easier & faster than server-side validation
    I'm guessing it's a Windows Form Application.
    AMD Phenom II X6 1055T|MSI 880GMA-E45|MSI 7770|2x2 Corsair DDR3 1333MHz|CM Elite 310|Corsair CX400W|DELL ST2320L
    Myself @ nbaztec.co.in
    Build Your Rig! (XBlade) @ nbaztec.co.in - Build Your Rig!
    My Inner Artist @ nbaztec.co.in - Designs

  9. #9
    122.26.11.85 Zangetsu's Avatar
    Join Date
    Jan 2008
    Location
    Soul Society
    Posts
    6,702

    Default Re: C#: Exception handling(?)

    ^Oops...my bad didn't saw the Messagebox
    HTC One V | Nokia 5233 | Nikon D3100 | Apple Ipod Touch 4G | Sound Magic PL21 | Sound Magic ES18

  10. #10
    Rusted... dashing.sujay's Avatar
    Join Date
    Nov 2009
    Location
    Bhopal
    Posts
    4,113

    Default Re: C#: Exception handling(?)

    Quote Originally Posted by RCuber View Post
    ^^ its a windows app

    Sujay, when are you initiating the calculation?
    When I press "OK" button.

    Code:
     private void button1_Click(object sender, EventArgs e)
            {
                if (checkBox1.Checked)
                {
                    if (textBox1.Text != "")
                    {
                        qua1 = Convert.ToInt32(textBox1.Text);
                    }
                    else
                    {
                        MessageBox.Show("Please enter a quantity");
                    }
                }
                else
                {
                    if (Convert.ToInt32(textBox1.Text) > 0)
                    {
                        MessageBox.Show("Please check the respective items after entering the quantity");
                    }
                }
                
                
                textBox5.Text = Convert.ToString(rate_mango * qua1);
    
                if (checkBox2.Checked)
                {
                    if (textBox2.Text != "")
                    {
                        qua1 = Convert.ToInt32(textBox2.Text);
                    }
                    else
                    {
                        MessageBox.Show("Please enter a quantity");
                    }
                }
    
                textBox6.Text = Convert.ToString(rate_pineapple * qua2);
    
                if (checkBox3.Checked)
                {
                    if (textBox3.Text != "")
                    {
                        qua1 = Convert.ToInt32(textBox3.Text);
                    }
                    else
                    {
                        MessageBox.Show("Please enter a quantity");
                    }
                }
                textBox7.Text = Convert.ToString(rate_apple * qua3);
    
                if (checkBox4.Checked)
                {
                    if (textBox4.Text != "")
                    {
                        qua1 = Convert.ToInt32(textBox4.Text);
                    }
                    else
                    {
                        MessageBox.Show("Please enter a quantity");
                    }
                }
                textBox8.Text = Convert.ToString(rate_banana * qua4);
                textBox9.Text = Convert.ToString(Convert.ToInt32(textBox5.Text) + Convert.ToInt32(textBox6.Text) + Convert.ToInt32(textBox7.Text) + Convert.ToInt32(textBox8.Text));
            }
    Its WIP still, making changes as per above suggestions.
    FAQ + answers for new members (Read before asking / messaging any moderator for any query)

    Drop Box: Get 500MB free


    Spoiler:

    Quote Originally Posted by axes2t2 View Post
    Before working on a master piece you have to first master the pieces.
    Sony Vaio CB35 Asus U32U ATH M20 Fiio E6

    Sony Vaio CB35 UnBoxing & Review

    How fast can you type?

  11. #11
    Master KOD3R nbaztec's Avatar
    Join Date
    Sep 2010
    Location
    New Delhi
    Posts
    342

    Default Re: C#: Exception handling(?)

    Quote Originally Posted by dashing.sujay View Post
    When I press "OK" button.

    Code:
     private void button1_Click(object sender, EventArgs e)
            {
                if (checkBox1.Checked)
                {
                    if (textBox1.Text != "")
                    {
                        qua1 = Convert.ToInt32(textBox1.Text);
                    }
                    else
                    {
                        MessageBox.Show("Please enter a quantity");
                    }
                }
                else
                {
                    if (Convert.ToInt32(textBox1.Text) > 0)
                    {
                        MessageBox.Show("Please check the respective items after entering the quantity");
                    }
                }
                
                
                textBox5.Text = Convert.ToString(rate_mango * qua1);
    
                if (checkBox2.Checked)
                {
                    if (textBox2.Text != "")
                    {
                        qua1 = Convert.ToInt32(textBox2.Text);
                    }
                    else
                    {
                        MessageBox.Show("Please enter a quantity");
                    }
                }
    
                textBox6.Text = Convert.ToString(rate_pineapple * qua2);
    
                if (checkBox3.Checked)
                {
                    if (textBox3.Text != "")
                    {
                        qua1 = Convert.ToInt32(textBox3.Text);
                    }
                    else
                    {
                        MessageBox.Show("Please enter a quantity");
                    }
                }
                textBox7.Text = Convert.ToString(rate_apple * qua3);
    
                if (checkBox4.Checked)
                {
                    if (textBox4.Text != "")
                    {
                        qua1 = Convert.ToInt32(textBox4.Text);
                    }
                    else
                    {
                        MessageBox.Show("Please enter a quantity");
                    }
                }
                textBox8.Text = Convert.ToString(rate_banana * qua4);
                textBox9.Text = Convert.ToString(Convert.ToInt32(textBox5.Text) + Convert.ToInt32(textBox6.Text) + Convert.ToInt32(textBox7.Text) + Convert.ToInt32(textBox8.Text));
            }
    Its WIP still, making changes as per above suggestions.
    For the love of God and your own good, please name your controls.
    AMD Phenom II X6 1055T|MSI 880GMA-E45|MSI 7770|2x2 Corsair DDR3 1333MHz|CM Elite 310|Corsair CX400W|DELL ST2320L
    Myself @ nbaztec.co.in
    Build Your Rig! (XBlade) @ nbaztec.co.in - Build Your Rig!
    My Inner Artist @ nbaztec.co.in - Designs

  12. #12
    Rusted... dashing.sujay's Avatar
    Join Date
    Nov 2009
    Location
    Bhopal
    Posts
    4,113

    Default Re: C#: Exception handling(?)

    Update: I have made some changes:

    Code:
     if (checkBox1.Checked)
                {
                    if (textBox1.Text != "")
                    {
                        qua1 = Convert.ToInt32(textBox1.Text);
                    }
                    else
                    {
                        MessageBox.Show("Please enter a quantity");
                    }
                }
                else
                {
                    if (textBox1.Text != "")
                    {
                        if (Convert.ToInt32(textBox1.Text) > 0)
                        {
                            MessageBox.Show("Please check the respective boxes after entering the values");
                        }
                        else
                        {
                            MessageBox.Show("Please check the fruits you want and enter the respective quantity");
                        }
                    }
    How is this approach ? Can some optimisation be done? One thing I want to do but not able to figure out the way.

    else
    {
    MessageBox.Show("Please check the fruits you want and enter the respective quantity");
    }

    I want that the if this else becomes true, it shouldn't do anything but just "skip" the scope (current if-else) and proceed towards calculation without showing any Mesage.Box. But not able to figure out how to make it skip it like that ?

    Some more queries:

    1) Why is if (textBox1.Text != "") working but if (textBox1.Text = "") is not? Error = Cannot implicitly convert type 'string' to 'bool'.

    2) As razerbladeXtreme said to use if (textBox1.Text !="" && Convert.ToInt32(textBox1.Text) > 0), it works. But if I swap both the conditions and write like this if (Convert.ToInt32(textBox1.Text) > 0 && textBox1.Text !="" ), it gives error. I used to think that compiler checks both the conditions in such situations, but here its giving error if first condition is failing (Convert.ToInt32(textBox1.Text) > 0). Is this the way compiler behaves or am I missing something?

    Quote Originally Posted by nbaztec View Post
    For the love of God and your own good, please name your controls.
    I thought to do it in starting then skipped it

    It can help you:
    Spoiler:
    FAQ + answers for new members (Read before asking / messaging any moderator for any query)

    Drop Box: Get 500MB free


    Spoiler:

    Quote Originally Posted by axes2t2 View Post
    Before working on a master piece you have to first master the pieces.
    Sony Vaio CB35 Asus U32U ATH M20 Fiio E6

    Sony Vaio CB35 UnBoxing & Review

    How fast can you type?

  13. #13
    Master KOD3R nbaztec's Avatar
    Join Date
    Sep 2010
    Location
    New Delhi
    Posts
    342

    Default Re: C#: Exception handling(?)

    How is this approach ? Can some optimisation be done? One thing I want to do but not able to figure out the way.
    Your flow of control can use plenty of optimization but I'm guessing this exercise is rather a simple once, so just let it be.

    I want that the if this else becomes true, it shouldn't do anything but just "skip" the scope (current if-else) and proceed towards calculation without showing any Mesage.Box. But not able to figure out how to make it skip it like that ?
    Don't quite get you.

    1) Why is if (textBox1.Text != "") working but if (textBox1.Text = "") is not? Error = Cannot implicitly convert type 'string' to 'bool'.
    You're assigning the value not checking (use ==)

    2) As razerbladeXtreme said to use if (textBox1.Text !="" && Convert.ToInt32(textBox1.Text) > 0), it works. But if swap both the conditions and write like this if (Convert.ToInt32(textBox1.Text) > 0 && textBox1.Text !="" ), it gives error. I used to think that compiler checks both the conditions in such situations, but here its giving error if first condition is failing (Convert.ToInt32(textBox1.Text) > 0). Is this the way compiler behaves or am I missing something?
    This is called short-circuit evaluation, been around since the days of C (if not Pascal too).
    Basically it says if the first expression evaluates to false in a logical AND then other expressions do not need to be checked, same goes for logical OR.
    You need to work on some basics first, take this C example and fire it up to notice the differences.
    Code:
    #include <stdio.h>
    
    int foo()
    {
       printf("foo");
       return 0;
    }
    
    int bar()
    {
       printf("bar");
       return 1;
    }
    
    int main()
    {
       foo() && bar();	// Says foo
       printf("\n");
       bar() && foo();	// Says barfoo
       printf("\n");
       foo() || bar();	// Says foobar
       printf("\n");
       bar() || foo();	// Says bar
       printf("\n");
       return 1;
    }
    AMD Phenom II X6 1055T|MSI 880GMA-E45|MSI 7770|2x2 Corsair DDR3 1333MHz|CM Elite 310|Corsair CX400W|DELL ST2320L
    Myself @ nbaztec.co.in
    Build Your Rig! (XBlade) @ nbaztec.co.in - Build Your Rig!
    My Inner Artist @ nbaztec.co.in - Designs

  14. #14
    Rubik's Uncle!! RCuber's Avatar
    Join Date
    Sep 2004
    Location
    ಬೆಂಗಳೂರು (Bengaluru)
    Posts
    5,879

    Default Re: C#: Exception handling(?)

    first you need to do the validations separately.

    Code:
    string Str = textBox1.Text.Trim();
    int Num;
    
    bool isNum = Int32.TryParse(Str, out Num);
    
    if (!isNum)
    {
    MessageBox.Show("Please enter numeric only");
    return; 
    }
    else
    {
    //continue your program
    }
    the cake is a lie
    621311.251521

  15. #15
    Rusted... dashing.sujay's Avatar
    Join Date
    Nov 2009
    Location
    Bhopal
    Posts
    4,113

    Default Re: C#: Exception handling(?)

    Quote Originally Posted by nbaztec
    You need to work on some basics first
    Yeah

    Quote Originally Posted by Charan
    first you need to do the validations separately.
    For all textBoxes ?


    PS: Thanks to all for helping me , especially nbaztec, you rock buddy

    What is Trim used for? (I can't understand it by explanation of intellisense. )

    Explain this line please:
    Code:
    bool isNum = Int32.TryParse(Str, out Num);
    I mean what its doing? TryParse is for ?

    PS: I'm a newbie in this, so hold on your asses long please
    FAQ + answers for new members (Read before asking / messaging any moderator for any query)

    Drop Box: Get 500MB free


    Spoiler:

    Quote Originally Posted by axes2t2 View Post
    Before working on a master piece you have to first master the pieces.
    Sony Vaio CB35 Asus U32U ATH M20 Fiio E6

    Sony Vaio CB35 UnBoxing & Review

    How fast can you type?

  16. #16
    Rubik's Uncle!! RCuber's Avatar
    Join Date
    Sep 2004
    Location
    ಬೆಂಗಳೂರು (Bengaluru)
    Posts
    5,879

    Default Re: C#: Exception handling(?)

    For all textBoxes ?
    Yes, for every textbox you need to do validation. or you can write a function to do this. ill give a sample soon.

    What is Trim used for? (I can't understand it by explanation of intellisense. )
    trim is used to remove white spaces from a string
    Explain this line please:
    Code:
    bool isNum = Int32.TryParse(Str, out Num);
    The TryParse method is like the Parse method, except the TryParse method does not throw an exception if the conversion fails. It eliminates the need to use exception handling to test for a FormatException in the event that s is invalid and cannot be successfully parsed.
    I mean what its doing? TryParse is for ?

    if the string is a number then the statement will convert the string to numeric and place it in "Num" variable. it will then return "true" to isNum Variable.

    incase the string is not a numeric then "Num" will have "null" and return value will be "false".

    Int32.TryParse Method (String, Int32) (System)

    EDIT: BTW .. the "out" keyword.. its like "ref" keyword, only thing is that "out" doesn't require the variable to be initialized.
    Last edited by RCuber; 30-07-2012 at 03:14 PM.
    the cake is a lie
    621311.251521

  17. #17
    122.26.11.85 Zangetsu's Avatar
    Join Date
    Jan 2008
    Location
    Soul Society
    Posts
    6,702

    Default Re: C#: Exception handling(?)

    @dashing.sujay: can u post the scenario of validation u need when clicking submit button?
    so we can optimise the code more.
    HTC One V | Nokia 5233 | Nikon D3100 | Apple Ipod Touch 4G | Sound Magic PL21 | Sound Magic ES18

  18. #18
    Rusted... dashing.sujay's Avatar
    Join Date
    Nov 2009
    Location
    Bhopal
    Posts
    4,113

    Default Re: C#: Exception handling(?)

    I guess I am validating all the textboxes separately. All the validations are done on clicking "OK" button, or am I taking it wrong?
    FAQ + answers for new members (Read before asking / messaging any moderator for any query)

    Drop Box: Get 500MB free


    Spoiler:

    Quote Originally Posted by axes2t2 View Post
    Before working on a master piece you have to first master the pieces.
    Sony Vaio CB35 Asus U32U ATH M20 Fiio E6

    Sony Vaio CB35 UnBoxing & Review

    How fast can you type?

  19. #19
    Rubik's Uncle!! RCuber's Avatar
    Join Date
    Sep 2004
    Location
    ಬೆಂಗಳೂರು (Bengaluru)
    Posts
    5,879

    Default Re: C#: Exception handling(?)

    ^^what you are doing is fine for a beginner. you need to learn the basic things your self.. once you are a little comfortable with the language, you can go ahead learning advanced techniques.

    don't get worried if you are getting errors. try to check the flow once or twice before posting here.. we can help you without any problem,but that's not the point.. you need to learn about the issues which come up when you are coding.
    the cake is a lie
    621311.251521

  20. #20
    122.26.11.85 Zangetsu's Avatar
    Join Date
    Jan 2008
    Location
    Soul Society
    Posts
    6,702

    Default Re: C#: Exception handling(?)

    Quote Originally Posted by dashing.sujay View Post
    I guess I am validating all the textboxes separately. All the validations are done on clicking "OK" button, or am I taking it wrong?
    I mean to put down what type of validation u need as point here

    e.g: mandatory fields,blank check,invalid no etc.

    just like a client requirement in a project
    HTC One V | Nokia 5233 | Nikon D3100 | Apple Ipod Touch 4G | Sound Magic PL21 | Sound Magic ES18

  21. #21
    Rusted... dashing.sujay's Avatar
    Join Date
    Nov 2009
    Location
    Bhopal
    Posts
    4,113

    Default Re: C#: Exception handling(?)

    Quote Originally Posted by RCuber View Post
    ^^what you are doing is fine for a beginner. you need to learn the basic things your self.. once you are a little comfortable with the language, you can go ahead learning advanced techniques.

    don't get worried if you are getting errors. try to check the flow once or twice before posting here.. we can help you without any problem,but that's not the point.. you need to learn about the issues which come up when you are coding.
    Roger that!

    Quote Originally Posted by Zangetsu View Post
    I mean to put down what type of validation u need as point here

    e.g: mandatory fields,blank check,invalid no etc.

    just like a client requirement in a project
    Let me complete it and I'll post it if any issue arises.
    FAQ + answers for new members (Read before asking / messaging any moderator for any query)

    Drop Box: Get 500MB free


    Spoiler:

    Quote Originally Posted by axes2t2 View Post
    Before working on a master piece you have to first master the pieces.
    Sony Vaio CB35 Asus U32U ATH M20 Fiio E6

    Sony Vaio CB35 UnBoxing & Review

    How fast can you type?

  22. #22
    Rubik's Uncle!! RCuber's Avatar
    Join Date
    Sep 2004
    Location
    ಬೆಂಗಳೂರು (Bengaluru)
    Posts
    5,879

    Default Re: C#: Exception handling(?)

    Quote Originally Posted by dashing.sujay View Post
    Roger that! .
    lets rescue Sid first and then we will get Roger.
    the cake is a lie
    621311.251521

  23. #23
    Section Moderator gopi_vbboy's Avatar
    Join Date
    Mar 2007
    Location
    Hyderabad
    Posts
    1,296

    Default Re: C#: Exception handling(?)

    Welcome to world of c#.

    So here are few code suggestions-
    1.Always have some good naming conventions.This helps
    to improve code readability
    Eg-chkFruits,nMangoes,etc

    2.You can use String.Empty instead of "" for readability

    3.I think as you want to validate four times using same
    logic.A functions will make code tidy.

    Alternate way as per OOPS ideology
    is creating a validation class for you objects
    which is pretty high level for now.


    Like
    Code:
    public void ValidateControlandAssign(CheckBox targetChkbox,TextBox tValue,TextBox tAssign,int rate )
                {
                 private const string senterqty="Please enter a quantity";
    			 private const string scheck="Please check the respective items after entering the quantity");
                 private int tempval;
                if (targetChkbox.Checked)
                {
                    if (tValue.Text != String.Empty)
    				tempval = Convert.ToInt32(tvalue);
                    else 
    				MessageBox.Show(senterqty);
                    
                }
                else
                {
                    if (Convert.ToInt32(tValue.Text) > 0)
                        MessageBox.Show(scheck);               
                
                }			
    			tAssign.Text= = Convert.ToString(rate * tempval);
                 }
    
    
    
    			 
    private void button1_Click(object sender, EventArgs e)
            {
    		..
    		//as per your code call
    		//observe how  names of control of your code  doesnt make sense except mango
    		ValidateControlandAssign(checkBox1,textBox1,textBox5.Text, rate_mango);
    		..
              }
    4.Remove {} for single statements of if.
    Code:
    if (true) singlestatment;
    else singlestatment;
    5.Dont hardcode strings.Put it in either config file
    or constants.

    Spoiler:
    Code:
     private void button1_Click(object sender, EventArgs e)
            {
                if (checkBox1.Checked)
                {
                    if (textBox1.Text != "")
                    {
                        qua1 = Convert.ToInt32(textBox1.Text);
                    }
                    else
                    {
                        MessageBox.Show("Please enter a quantity");
                    }
                }
                else
                {
                    if (Convert.ToInt32(textBox1.Text) > 0)
                    {
                        MessageBox.Show("Please check the respective items after entering the quantity");
                    }
                }
                
                
                textBox5.Text = Convert.ToString(rate_mango * qua1);
    
                if (checkBox2.Checked)
                {
                    if (textBox2.Text != "")
                    {
                        qua1 = Convert.ToInt32(textBox2.Text);
                    }
                    else
                    {
                        MessageBox.Show("Please enter a quantity");
                    }
                }
    
                textBox6.Text = Convert.ToString(rate_pineapple * qua2);
    
                if (checkBox3.Checked)
                {
                    if (textBox3.Text != "")
                    {
                        qua1 = Convert.ToInt32(textBox3.Text);
                    }
                    else
                    {
                        MessageBox.Show("Please enter a quantity");
                    }
                }
                textBox7.Text = Convert.ToString(rate_apple * qua3);
    
                if (checkBox4.Checked)
                {
                    if (textBox4.Text != "")
                    {
                        qua1 = Convert.ToInt32(textBox4.Text);
                    }
                    else
                    {
                        MessageBox.Show("Please enter a quantity");
                    }
                }
                textBox8.Text = Convert.ToString(rate_banana * qua4);
                textBox9.Text = Convert.ToString(Convert.ToInt32(textBox5.Text) + Convert.ToInt32(textBox6.Text) + Convert.ToInt32(textBox7.Text) + Convert.ToInt32(textBox8.Text));
            }


    6.You can also use
    Int.TryParse for readability

  24. #24
    Wise Old Owl
    Join Date
    Jul 2010
    Location
    Mumbai
    Posts
    1,171

    Default Re: C#: Exception handling(?)

    Have not read the complete thread but seen this in condition statement

    textBox1.Text != ""

    Instead use this

    IsNullOrWhiteSpace or IsNullOrEmpty
    http://stackoverflow.com/questions/6...itespacestring

    String.IsNullOrWhiteSpace Method (System)
    Core-i5 2400 | Intel DH67BL | G.Skill 8GB DDR3 1333Mhz | 500GB Segate | CM 430 | Corsair VX550 PSU| BENQ V2410 eco LED Monitor | Genuine windows 7 64-bit Ultimate | Google Galaxy Nexus, Samsung Galaxy S & boring Nokia Lumia 800 :( , iPad 4

  25. #25
    Master KOD3R nbaztec's Avatar
    Join Date
    Sep 2010
    Location
    New Delhi
    Posts
    342

    Default Re: C#: Exception handling(?)

    There is absolutely no need for checking String to be empty, the reason being there are only 2 equivalence classes - Correct Input and Incorrect Input and an empty string is the same as an incorrect numeric string.

    @ds_
    As I have earlier demonstrated the use of int.TryParse(), I suggest you instead use int.Parse() and handle the exception.

    The most crude form of it would look like:

    Code:
    public void buttonOk_Click()
    {
         try {
              this.itemPrice1.Text = int.Parse(this.itemQty1.Text) * itemRate1;
              this.itemPrice2.Text = int.Parse(this.itemQty2.Text) * itemRate2;
              this.itemPrice3.Text = int.Parse(this.itemQty3.Text) * itemRate3;
              ....
              CalculateTotal();
         } catch(FormatException) {
            MessageBox.Show("Only numbers are allowed")
         }
    }
    This way the calculation will cease once it detects one of the inputs as Invalid, I'd show you a much, much better way of handling things like these (using foreach and Controls property) but it'd be an overkill for now.

    P.S. There is no need for Trim() here since TryParse()/Parse() trims it anyway.
    AMD Phenom II X6 1055T|MSI 880GMA-E45|MSI 7770|2x2 Corsair DDR3 1333MHz|CM Elite 310|Corsair CX400W|DELL ST2320L
    Myself @ nbaztec.co.in
    Build Your Rig! (XBlade) @ nbaztec.co.in - Build Your Rig!
    My Inner Artist @ nbaztec.co.in - Designs

  26. #26
    Rusted... dashing.sujay's Avatar
    Join Date
    Nov 2009
    Location
    Bhopal
    Posts
    4,113

    Default Re: C#: Exception handling(?)

    Quote Originally Posted by gopi_vbboy
    So here are few code suggestions-
    1.Always have some good naming conventions.This helps
    to improve code readability
    Eg-chkFruits,nMangoes,etc

    2.You can use String.Empty instead of "" for readability
    Thanks for your inputs but what's your take on nbaztec's opposition for 2nd point.

    PS: Your 3rd and 5th point bounced my head

    @nbaztec: Working on it buddy

    Any views for this: C# int.Parse Optimization

    Ok, am almost done, one query.

    When I write else like
    Code:
    else;
    it gives Possibly mistaken empty statement warning. (runs fine though)

    But when I write like:

    Code:
    else {}
    It says fine.

    Everything fine now. Final queries:

    Code of OK (submit) button:

    Spoiler:
    Code:
    private void button1_Click(object sender, EventArgs e)
            {
                if (checkBox1.Checked)
                {
                    if (textBox1.Text == "")
                    {
                        MessageBox.Show("Please enter a quantity", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        qua1 = int.Parse(textBox1.Text);
                    }
                }
                else
                {
                    if (textBox1.Text == "")
                    {
                        
                    }
                    else
                    {
                        if (int.Parse(textBox1.Text) > 0)
                            MessageBox.Show("Please check the respective boxes after entering the values");
                        else { }
                    }
                    
                }
                
                
                textBox5.Text = Convert.ToString(rate_mango * qua1);
    
                if (checkBox2.Checked)
                {
                    if (textBox2.Text == "")
                    {
                        MessageBox.Show("Please enter a quantity", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        qua2 = int.Parse(textBox2.Text);
                    }
                }
                else
                {
                    if (textBox2.Text == "")
                    {
                        
                    }
                    else
                    {
                        if (int.Parse(textBox2.Text) > 0)
                            MessageBox.Show("Please check the respective boxes after entering the values");
                        else { }
                    }
                    
                }
    
                textBox6.Text = Convert.ToString(rate_pineapple * qua2);
    
                if (checkBox3.Checked)
                {
                    if (textBox3.Text == "")
                    {
                        MessageBox.Show("Please enter a quantity", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        qua3 = int.Parse(textBox3.Text);
                    }
                }
                else
                {
                    if (textBox3.Text == "")
                    {
                        
                    }
                    else
                    {
                        if (int.Parse(textBox3.Text) > 0)
                            MessageBox.Show("Please check the respective boxes after entering the values");
                        else { }
                    }
                    
                }
                textBox7.Text = Convert.ToString(rate_apple * qua3);
    
                if (checkBox4.Checked)
                {
                    if (textBox4.Text == "")
                    {
                        MessageBox.Show("Please enter a quantity", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        qua4 = int.Parse(textBox4.Text);
                    }
                }
                else
                {
                    if (textBox4.Text == "")
                    {
                        
                    }
                    else
                    {
                        if (int.Parse(textBox4.Text) > 0)
                            MessageBox.Show("Please check the respective boxes after entering the values");
                        else { }
                    }
                    
                }
                textBox8.Text = Convert.ToString(rate_banana * qua4);
                textBox9.Text = Convert.ToString(int.Parse(textBox5.Text) + int.Parse(textBox6.Text) + int.Parse(textBox7.Text) + int.Parse(textBox8.Text));
            }


    Code of "Reset" button:

    Spoiler:
    Code:
    private void button2_Click(object sender, EventArgs e)
            {
                checkBox1.Checked = false;
                checkBox2.Checked = false;
                checkBox3.Checked = false;
                checkBox4.Checked = false;
                textBox1.Text = "0";
                textBox2.Text = "0";
                textBox3.Text = "0";
                textBox4.Text = "0";
                textBox5.Text = "0";
                textBox6.Text = "0";
                textBox7.Text = "0";
                textBox8.Text = "0";
                textBox9.Text = "0";
                int qua1 = 0;
                int qua2 = 0;
                int qua3 = 0;
                int qua4 = 0;
            }


    1) The warning messages are coming as many times as error is occurred. Like if the user enters the value for all 4 items but forgets to check the respective boxes, it gives error 4 times. How do I make it once?

    2) I do a sample calculation for the first time, then press "Reset" button. Then I press "OK" button without entering any values. This should give grand total = 0 but its giving last grand total. I'm not able to catch what's wrong. It was not happening earlier, but in the modification process something went wrong.

    This screenie of my app may help you overcoming my bad naming convention.
    Spoiler:


    One more question:

    I applied E.Handled restriction only to textBox1 but its working on all quantity textboxes (1-4). I can see it activated in properties, KeyPress event of all quantity textBoxes? How is it possible?
    FAQ + answers for new members (Read before asking / messaging any moderator for any query)

    Drop Box: Get 500MB free


    Spoiler:

    Quote Originally Posted by axes2t2 View Post
    Before working on a master piece you have to first master the pieces.
    Sony Vaio CB35 Asus U32U ATH M20 Fiio E6

    Sony Vaio CB35 UnBoxing & Review

    How fast can you type?

  27. #27
    Master KOD3R nbaztec's Avatar
    Join Date
    Sep 2010
    Location
    New Delhi
    Posts
    342

    Default Re: C#: Exception handling(?)

    Quote Originally Posted by dashing.sujay View Post
    Any views for this: C# int.Parse Optimization
    It's optimization at the cost of error checking. It won't throw errors on invalid inputs like "12s2". It uses the age-old technique of converting ASCII numbers to decimal.

    Quote Originally Posted by dashing.sujay View Post
    When I write else like
    Code:
    else;
    it gives Possibly mistaken empty statement warning. (runs fine though)

    But when I write like:

    Code:
    else {}
    It says fine.
    This is compiler check. It does it since programmers sometimes tend to misplace ';' like:
    Code:
    if(condition);           // Erroneous semi-colon
          doSomeWork();
    If it's bothering you, you can turn it off either by setting the compiler options via properties to /nowarn 642 or using the good old #pragma directive #pragma warning disable 642. Alternatively you can exclude that optional else clause

    1) The warning messages are coming as many times as error is occurred. Like if the user enters the value for all 4 items but forgets to check the respective boxes, it gives error 4 times. How do I make it once?
    Try the try-catch approach. If you don't want to do that, then use a boolean flag to set it as true if some error occured. Then display the error only once.

    2) I do a sample calculation for the first time, then press "Reset" button. Then I press "OK" button without entering any values. This should give grand total = 0 but its giving last grand total. I'm not able to catch what's wrong. It was not happening earlier, but in the modification process something went wrong.
    I'm guessing some errand variables you failed to reset.

    I applied E.Handled restriction only to textBox1 but its working on all quantity textboxes (1-4). I can see it activated in properties, KeyPress event of all quantity textBoxes? How is it possible?
    Possible if you copied-pasted those text-boxes from the first one.
    AMD Phenom II X6 1055T|MSI 880GMA-E45|MSI 7770|2x2 Corsair DDR3 1333MHz|CM Elite 310|Corsair CX400W|DELL ST2320L
    Myself @ nbaztec.co.in
    Build Your Rig! (XBlade) @ nbaztec.co.in - Build Your Rig!
    My Inner Artist @ nbaztec.co.in - Designs

  28. #28
    Rusted... dashing.sujay's Avatar
    Join Date
    Nov 2009
    Location
    Bhopal
    Posts
    4,113

    Default Re: C#: Exception handling(?)

    If it's bothering you, you can turn it off either by setting the compiler options via properties to /nowarn 642 or using the good old #pragma directive #pragma warning disable 642. Alternatively you can exclude that optional else clause
    Do I really need that fuss? I just included the braces.

    Try the try-catch approach. If you don't want to do that, then use a boolean flag to set it as true if some error occured. Then display the error only once.
    What is try-catch approach ? I didn't got it at all.

    I'm guessing some errand variables you failed to reset.
    There are total 8 variables. 4 for inputting quantity & 4 for rate. I already gave "rest" code in above post in which I reset all the textboxes and quantity variables. Rate is of course not required.

    Possible if you copied-pasted those text-boxes from the first one.
    No, I didn't.

    PS: thanks for all the help
    FAQ + answers for new members (Read before asking / messaging any moderator for any query)

    Drop Box: Get 500MB free


    Spoiler:

    Quote Originally Posted by axes2t2 View Post
    Before working on a master piece you have to first master the pieces.
    Sony Vaio CB35 Asus U32U ATH M20 Fiio E6

    Sony Vaio CB35 UnBoxing & Review

    How fast can you type?

  29. #29
    122.26.11.85 Zangetsu's Avatar
    Join Date
    Jan 2008
    Location
    Soul Society
    Posts
    6,702

    Default Re: C#: Exception handling(?)

    Quote Originally Posted by dashing.sujay View Post
    What is try-catch approach ? I didn't got it at all.
    to catch any errors if it occurs & handle those in structured way....
    catching error & displaying the user about the error
    HTC One V | Nokia 5233 | Nikon D3100 | Apple Ipod Touch 4G | Sound Magic PL21 | Sound Magic ES18

  30. #30
    Master KOD3R nbaztec's Avatar
    Join Date
    Sep 2010
    Location
    New Delhi
    Posts
    342

    Default Re: C#: Exception handling(?)

    Quote Originally Posted by dashing.sujay View Post
    Do I really need that fuss? I just included the braces.
    You can remove the else clause altogether, it's optional.

    What is try-catch approach ? I didn't got it at all.
    Code:
    public void buttonOk_Click()
    {
         try {
              this.itemPrice1.Text = int.Parse(this.itemQty1.Text) * itemRate1;
              this.itemPrice2.Text = int.Parse(this.itemQty2.Text) * itemRate2;
              this.itemPrice3.Text = int.Parse(this.itemQty3.Text) * itemRate3;
              ....
              CalculateTotal();
         } catch(FormatException) {
            MessageBox.Show("Only numbers are allowed")
         }
    }
    There are total 8 variables. 4 for inputting quantity & 4 for rate. I already gave "rest" code in above post in which I reset all the textboxes and quantity variables. Rate is of course not required.
    The code seems fine, but surely there's something incorrect in the code itself.

    No, I didn't.
    Or you selected all the boxes, but that's irrelevant. Just select all the textboxes and remove the definition, then put it for the correct textbox.
    AMD Phenom II X6 1055T|MSI 880GMA-E45|MSI 7770|2x2 Corsair DDR3 1333MHz|CM Elite 310|Corsair CX400W|DELL ST2320L
    Myself @ nbaztec.co.in
    Build Your Rig! (XBlade) @ nbaztec.co.in - Build Your Rig!
    My Inner Artist @ nbaztec.co.in - Designs

Page 1 of 2 1 2 LastLast

Similar Threads

  1. Exception handling - Java
    By amit dutt in forum Programming
    Replies: 1
    Last Post: 25-09-2011, 03:04 AM
  2. I want GTA SA handling.cfg file.
    By Gigacore in forum Gamerz
    Replies: 2
    Last Post: 01-07-2008, 10:25 PM
  3. File handling using GCC/G++
    By anantkhaitan in forum Programming
    Replies: 16
    Last Post: 22-05-2007, 04:19 PM
  4. File handling using GCC/G++
    By anantkhaitan in forum QnA (read only)
    Replies: 16
    Last Post: 22-05-2007, 04:19 PM
  5. Handling /dev/dsp in C
    By desertwind in forum Open Source
    Replies: 1
    Last Post: 04-01-2007, 07:32 PM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Close