C#: How to detect which textbox value is equal to, or the closest to zero of a group of textboxes/values?

StackOverflow https://stackoverflow.com/questions/3623066

  •  26-09-2019
  •  | 
  •  

Question

I have a great excel formula I have been using but I want to distribute something a little more substantial and durable and also user friendly to my group of designers at work. I am also dealing with negative numbers unfortunately so going by the minimum value would not work.

So if textbox1 said 13, textbox2 said 4, and textbox3 said -1, text box 3 would light up or whatever action I chose be performed since -1 is the closest to zero.

Not that it really helps, but the excel formula goes like this: =INDEX(A61:A78,MATCH(MIN(INDEX(ABS(A61:A78),0,1)),INDEX(ABS(A61:A78),0,1),0))

Thanks for any help!

Was it helpful?

Solution

Here is a "fun with LINQ" method

Func<string, bool> isDecimal = s => { decimal temp; return decimal.TryParse(s, out temp);};
TextBox closestToZero =
    (from tb in this.Controls.OfType<TextBox>()
        where isDecimal(tb.Text)
        orderby Math.Abs(decimal.Parse(tb.Text))
        select tb)
        .FirstOrDefault();

if (closestToZero != null)
    MessageBox.Show(closestToZero.Text);

OTHER TIPS

Iterate over the text boxes, calculate the absolute value of each number in each box, and keep track of the lowest number seen as well as the index of the text box it was seen in. Try looking into Math.Abs() for absolute value.

You could simply iterate over the textboxes, storing the minimum value found so far and its associated textbox as you go.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top