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

本文关键字:变量 插入 数据表 数据 | 更新日期: 2023-09-27 18:13:22

我想用变量中的值填充DataTable。我正在用c#进行编码。我有一个名为summary的DataTable,我已经创建了列,我需要将值添加到变量averageremaining_sharesales_proceedcost_salerealized_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添加值,请告诉如何执行。

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

考虑到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);
}

您需要调用datatable实例的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);

如果名字你不知道,你可以写得像

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

您必须使用dataTablesummary.NewRow();dataTablesummary创建一个新行,然后为新创建的行赋值。然后将此行添加到数据表中:

 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);
//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);

您可以将数字替换为变量