Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to insert data into datatable from variable

Tags:

c#

datatable

I wanted to populate DataTable with the value taken from variable. I am doing coding in in c#. I have a DataTable called summary, I have created the columns and I need to add values to those from the variables average, remaining_share, sales_proceed, cost_sale, realized_profit.

The code is as below :

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

I want to add values to DataTable on the button click, please tell how to do it.


2 Answers

Considering average, remaining_share, sales_proceed, cost_sale, realized_profit are the variable you want to insert into the row, the following line

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

will do it.

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);
}
like image 99
Abhishek Avatar answered Aug 29 '26 07:08

Abhishek


you need to call newrow() of datatable instance. It return a datarow instance with row having same number of cell as the table has. Now u can bind data like this i have done.

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

if colomn name u dont know u can write like

 DataRow dr=dataTablesummary.NewRow();
 dr[0] = average;
 dr[1] = remaining_share;
 dr[2] = sales_proceed;
 dr[3] = realized_profit;
 dataTablesummary.Rows.Add(dr);
like image 35
Rajesh Avatar answered Aug 29 '26 08:08

Rajesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!