2010-03-24 53 views
0

我正在尝试构建一个退休计算器,以此来提供一些有用的东西并更好地学习C#。目前,我正在尝试使用动态数量的行/列构建DataTable。用C#编写一个DataTable,每次只写一列

对于上下文,我要求用户提供一些关于工资,投资百分比和预期投资回报率的信息。我还有其他一些东西,但这不是我所遇到的问题的一部分。因为我需要的数据表的列数是未知的,直到公式运行(+ for循环完成时),我在做DataColumns时遇到问题。希望下面的代码将有所帮助。

我真的试图一次构建表一列。我意识到我可以一次一次地将它建立起来,因为退休前的年份(岁退休年龄)是已知的,但我不想和我想了解更多。对于缩进和评论感到抱歉。我试图在那里留下一些我评论的编码尝试。谢谢你的帮助。

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; 

}

更新:只是作为一个说明,我绝对不是说这是最好的办法,因为我的出路我所知默认区。我通常只是建立一个最大大小的矩阵(数组[maxrows] [maxcols])并填充它。我试图少思维C,并使用C#的一些功能。如果有更好的方法,我很乐意改变这项技术。谢谢。

回答

2

我不认为在添加行后将列添加到DataTable不是一个好主意。

在这种情况下,最好的做法是计算一切成阵列,并在年底

+0

因此,在这种情况下,我将建立双打的动态数组?或者我会构建双打的动态矩阵。这个最终目标将会进入GUI的DataGrid视图。 – Awaken 2010-03-24 15:32:36

0

那么建立DataTable。我不同意这里采用的方法,正如你在你的问题中解释的那样,但是,为了向DataTable添加列,你应该考虑到当前添加的行的值将是DBNull。

DataColumn类,有两个属性,可以对您有用:

// default value for the newly added rows 
columna.DefaultValue = 0; 

    // whether your column allows DBNull values (which is true for this case) 
columna.AllowDBNull = true; 
+0

感谢您的属性注释。 – Awaken 2010-03-24 15:34:34