如何将数据从变量插入数据表中

时间:2015-09-18 10:05:39

标签: c# datatable

我想用DataTable填充从变量中获取的值。我在c#中编码。我有一个名为DataTable的摘要,我创建了列,我需要为变量averageremaining_sharesales_proceedcost_sale添加值,realized_profit

代码如下:

protected void Button1_Click(object sender, EventArgs e)
{
    average = 25;
    remaining_share = 30;
    sales_proceed = 125;
    cost_sale = 50;
    realized_profit = 33;
    var dataTablesummary = new DataTable();
    dataTablesummary.Columns.Add("average", typeof(decimal));
    dataTablesummary.Columns.Add("Remaining share", typeof(decimal));
    dataTablesummary.Columns.Add("sales_proceed", typeof(decimal));
    dataTablesummary.Columns.Add("cost_sale", typeof(decimal));
    dataTablesummary.Columns.Add("realized_profit", typeof(decimal));
}

我想在点击按钮时向DataTable添加值,请告诉我们如何操作。

4 个答案:

答案 0 :(得分:3)

考虑average, remaining_share, sales_proceed, cost_sale, realized_profit是要插入行的变量,以下行

dataTablesummary.Rows.Add(average, remaining_share, sales_proceed, cost_sale, realized_profit);

会这样做。

protected void Button1_Click(object sender, EventArgs e)
{
    average = 25;
    remaining_share = 30;
    sales_proceed = 125;
    cost_sale = 50;
    realized_profit = 33;
    var dataTablesummary = new DataTable();
    dataTablesummary.Columns.Add("average", typeof(decimal));
    dataTablesummary.Columns.Add("Remaining share", typeof(decimal));     dataTablesummary.Columns.Add("sales_proceed", typeof(decimal));
    dataTablesummary.Columns.Add("cost_sale", typeof(decimal));
    dataTablesummary.Columns.Add("realized_profit", typeof(decimal));
    dataTablesummary.Rows.Add(average, remaining_share, sales_proceed, cost_sale, realized_profit);
}

答案 1 :(得分:1)

您必须使用dataTablesummarydataTablesummary.NewRow();创建新行,然后为新创建的行指定值。然后将此行添加到数据表:

 var dr = dataTablesummary.NewRow();
 dr["average"] = average;
 dr["Remaining share"] = remaining_share;
 dr["cost_sale"] = sales_proceed;
 dr["realized_profit"] = realized_profit;
 dataTablesummary.Rows.Add(dr);

答案 2 :(得分:1)

//Create a datarow of type dataTablesummary
DataRow dr=dataTablesummary.NewRow();    
//can be populated by methods like:
dr["average"] = 1.2;
dr["Remaining share"] = 5.7
dr["cost_sale"] = 5.4;
dr["realized_profit"] = 1.78;    
//Now add the row to datatable
dataTablesummary.Rows.Add(dr);

您可以用变量替换数字

答案 3 :(得分:1)

你需要调用datable实例的newrow()。它返回一个数据行实例,其行具有与该表相同的单元格数。现在你可以像我这样绑定数据了。

 DataRow dr=dataTablesummary.NewRow();
 dr["average"] = average;
 dr["Remaining share"] = remaining_share;
 dr["cost_sale"] = sales_proceed;
 dr["realized_profit"] = realized_profit;
 dataTablesummary.Rows.Add(dr);

如果colomn名字你不知道你可以像

那样写
 DataRow dr=dataTablesummary.NewRow();
 dr[0] = average;
 dr[1] = remaining_share;
 dr[2] = sales_proceed;
 dr[3] = realized_profit;
 dataTablesummary.Rows.Add(dr);