1/23/2013

How To : Calculate Median Value Using InfoPath Forms


Thanks To Entan Ming!!

I was going crazy for this untill Entan Ming provided a solution to me.

I wanted to calculate Median for values entered into my InfoPath form (as of now I have provided 10 textboxes in InfoPath but you can modify my code as per your requirement)

Though I have provided 10 textboxes, users can enter less than 10 values as well and I need to count Median for it.

Yes, I know that we can achieve this simply by creating a List with one calculated column and can use =MEDIAN() formula (as simple as that)

But when users want to see the final Median value before submitting the values (for whatsoever reason), you can't use List!!

So, Let's start!!

First of all (if you are not aware of how to do it), check out my post on How To : Code in InfoPath Forms 2010

Once you know what I am talking about (for this perticular code), create 11 textboxes and 1 button and call below method on button click:

Code:

public void sorting()
{
int[] arry = new int[11];
int counter = 0;
for (int i = 1; i <= 10; i++)
{
if (MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:field" + i + "", NamespaceManager).Value != "")
{
arry[i] = Convert.ToInt32(MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:field" + i + "", NamespaceManager).Value);
counter++;
}
else
{
break;
}
}
int[] resul = new int[counter];
for (int i = 0; i < counter; i++)
{
resul[i] = arry[i + 1];
}
bool sortnum = true;
int pos = 0;
int tot = counter;
int median = 0;
while (sortnum == true)
{
for (int j = (pos + 1); j < tot; j++)
{
int rd = resul[pos];
int fg = resul[j];
if (rd > fg)
{
resul[pos] = fg;
resul[j] = rd;
}
}
pos = pos + 1;
if (pos >= tot)
{
sortnum = false;
}
}
if (tot % 2 == 0)
{
int sdd = resul[(tot / 2) - 1] + resul[tot / 2] / 2;
median = sdd;
}
else
{
median = resul[(tot - 1) / 2];
}
string a = Convert.ToString(median);
XPathNavigator P2 = this.MainDataSource.CreateNavigator().SelectSingleNode("//my:myFields/my:field11", this.NamespaceManager);
P2.SetValue(((Convert.ToDouble(resul[(tot/2)-1]) + Convert.ToDouble(resul[(tot / 2)])) / 2).ToString());
}

You will get Median value (at run time) in your field11 textbox!! :)

0 comments: