Building a DataTable in C# with one column at a time

Posted by Awaken on Stack Overflow See other posts from Stack Overflow or by Awaken
Published on 2010-03-24T15:10:52Z Indexed on 2010/03/24 15:13 UTC
Read the original article Hit count: 190

Filed under:
|

I am trying to build a Retirement Calculator as a chance to make something useful and learn C# better. Currently, I am trying to build a DataTable with a dynamic amount of rows/columns.

For context, I ask the user for some inputs regarding salary, % of salary being invested, and expected ROI. I have some other stuff too, but it isn't really part of the issue I am having. Because the number of columns I need for the DataTable is unknown until the formula is run (while+for loop completes), I am having trouble doing things as DataColumns. Hopefully the code below will help.

I am really trying to build the table one column at a time. I realize I could reverse it to build it one row at a time because the Years before retirement (yearsRetire) is known, but I would prefer not to and I want to learn more. Sorry for the indentation and commenting. I tried to leave some of my commented coding attempts in there. Thanks for any help.

public double calcROI()
{     
   double testROI = 0.00;
   double tempRetireAmount = 0;
   double adjustRetire = goalAmount * (1 + (Math.Pow(inflation,yearsRetire)));

// Loop through ROI values until the calculated retire amount with the test ROI
// is greater than the target amount adjusted for inflation
while (tempRetireAmount < adjustRetire)
{
    //Increment ROI by 1% per while iteration
    testROI += .01;  

    //Make a new Column to hold the values for ROI for this while iteration
    //dtMain.Columns.Add(Convert.ToString(testROI));       
    //DataColumn tempdc = new DataColumn(Convert.ToString(testROI));

    //Loop through the number of years entered by user and see the amount
    //at Retirement with current ROI
    for (int i = 0; i < yearsRetire; i++)
    {
        //Main formula to calculate amount after i years
        tempRetireAmount = (tempRetireAmount + salary*savingsPct) * (1 + testROI);

        // Add value for this year/ROI to table/column
        //DataRow dr = .NewRow();
        //dr tempRetireAmount;
        //tempdc[i] = tempRetireAmount;

    }
    //Need to add column of data to my Main DataTable
    //dtMain.Rows.Add(dr);
    //dtMain.Columns.Add(tempdc);
}
return testROI;

}

© Stack Overflow or respective owner

Related posts about c#

Related posts about datagridview