Click here to Skip to main content
15,886,806 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I have five textboxes and I want to add the values typed into them calculating the sum of all five values. I'm using ASP.net.

Please guide me in this!
Posted
Updated 14-Nov-11 5:17am
v2
Comments
[no name] 14-Nov-11 10:59am    
What have you tried?
Member 8388026 14-Nov-11 11:02am    
i want to add five integer values which will be entered in 5 text boxes and when i click button result should be displayed in another textbox
Manfred Rudolf Bihy 14-Nov-11 11:14am    
Errmmhh, Mark asked of you what you had tried and not what you wanted. Did you actually try anything sofar? Please do so and come back if run into any trouble.

1 solution

Here to get you started:

C#
public Object Parse(String stringValue, Type typ)
{
    Type[] parseParams = new Type[] { typeof(String) };
    Object retVal = null;
    // This method should also check that the Parse method matches the type, but I'll leave that as an excercise
    MethodInfo mi = typ.GetMethod("Parse", parseParams);
    if (mi != null)
    {
        retVal = mi.Invoke(this, new Object[] { stringValue });
    }
    return retVal;
}

private D GetValue<D>(Textbox tb)
{
    D result = default(D);
    try
    {
        result = (D)Parse(tb.Text, typeof(D));
    }
    catch
    {
    }
    return result;
}

private T DoSum<T>(Textbox[] textboxes)
{
    T result = default(T);
    foreach(Textbox tb in textboxes)
    {
        result = Add<T>(result, GetValue<T>(tb));
    }
}

private L Add<L>(L result, L addend)
{
    L result = default(L);
    ...
    ...
    ...
    return result;
}


Cheers!

—MRB
 
Share this answer
 
v4
Comments
Sergey Alexandrovich Kryukov 14-Nov-11 11:45am    
Manfred, sorry, I just had to vote 2. This code will not compile, because D does now know Parse/TryParse operation, and generic constraints for primitive types are not possible. This is one of the fundamental problems of .NET generics, a curse of numeric programming, which practically cannot be generic, unlike regular (non-CLI) C++.

I would gladly change my vote if you fix it.

There is another problem: you should have explained the result of TryParse when a text is not recognized: your function would return default value. Another choice would be using Parse instead and deal with its exceptions on top of stack relative to this call.

--SA
Manfred Rudolf Bihy 14-Nov-11 12:13pm    
I did something analogus a while back. I'll have to check the code I wrote bak then. It is really to bad there is no INumber or INumeric interface, then one could just add a generic constraint and be done with it.

Thanks for bringing the issue to my attention!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900