4
Answers

Default value for Multiple TextBoxes in C#

amber

amber

11y
9.7k
1
Hi,
i wana set default value of multiple text boxes to zero in c# winform application. i have 5 text boxes n i wana show the sum in the 6th one which is dynamically entered in those 5 textboxes. i just wana put condition dt if any of the 5 textbox is empty its value should be set to zero so it cn also participate in calculation otherwis eits giving an error cz i have made a method for ds to take 5 values :
in a separate class:

public int add(int a, int b, int c, int d, int e) 
{
      total = (a + b + c + d + e);
      return total;
}

on btn event:

            sm = new fee_endow();
            sm1 = sm.add(Convert.ToInt32(sum1.Text), Convert.ToInt32(sum2.Text), Convert.ToInt32(sum3.Text), Convert.ToInt32(sum4.Text), Convert.ToInt32(sum5.Text));
            totalbox.Text = sm1.ToString();

i also tried to put boxes in array :

int[] sum = {sum1box.text, sum2box.text, sum3box.text, sum4box.text, sum5box.text}
foreach(int b in sum)
{
    if (b is TextBox)
{
if (b.Text == "")
{
      b.Text = 0;
}
}
}
bt it doesnt work plz help me wd ds anyone as am new to c# programming.
Thnx

Answers (4)
0
Vulpes

Vulpes

NA 96k 2.6m 11y
You could do it like this (if the textbox is empty, the variable will be assigned a value of 0):

 sm = new fee_endow();
 int a, b, c, d, e;
 int.TryParse(sum1.Text, out a);
 int.TryParse(sum2.Text, out b);
 int.TryParse(sum3.Text, out c);
 int.TryParse(sum4.Text, out d);
 int.TryParse(sum5.Text, out e);

 sm1 = sm.add(a, b, c, d, e);
 totalbox.Text = sm1.ToString();


Accepted
0
Vulpes

Vulpes

NA 96k 2.6m 11y
Sure, the int.TryParse returns a bool indicating whether the first parameter can be parsed to an int or not.

If it can, then the 'out' parameter contains the value of that int.

If it can't, then the 'out' parameter contains 0.

So, if the first parameter is an empty string or something like 'abc', then it can't be parsed to an int and the out parameter will contain zero, which is what you wanted.

Here, we're not interested in the bool return value and so just ignore it.

'out' parameters are a form of 'passing by reference. However, unlike 'ref', the variable does not need to be initialized first but the compiler guarantees that it will have a value by the time the method returns. 
0
amber

amber

NA 39 48.8k 11y
Thnx it's working. one more favor can u xplain how does out a, out b work??
0
krishna angirekula

krishna angirekula

NA 68 30.7k 11y
Convert.ToInt32(TextBoxToTalTickets.Text)+Convert.ToInt32(TextBox2.Text)+
Convert.ToInt32(TextBox2.Text)..................
u can use this man