2
Reply

How Create a new Column in a Datable and assign value to the newly created column row

Biswarup Saha

Biswarup Saha

May 28 2012 11:50 PM
1.9k
i have generated a datatable from database like this
 
source destination vehicle Rate
---------------------------------------------------
   a         b          XXX    500 
   a           c          xxx     400
 

After add a column (New_Rate) in the datatable and assign value.
 
source destination vehicle Rate New_Rate 
--------------------------------------------------------------------------------
a b     XXX 500 1000
a c xxx 400 800
 
Here is my code snippet:
SqlDataAdapter adp2 = new SqlDataAdapter("select source, destination, vehicle, rate from pickupdroptariff order by source", conn);
        DataTable dt2 = new DataTable();
        adp2.Fill(dt2);
        dt2.Columns.Add("Rate_New");
        int veh_rate=0;
        if (dt2.Rows.Count > 0)
        {
            for (int j = 0; j < dt2.Rows.Count; j++)
            {
                if(dt2.Rows[j][2].ToString()=="Small Car")
                {
                    veh_rate = Convert.ToInt32(dt2.Rows[j][3].ToString());
                    veh_rate = veh_rate + small;
                    //DataRow row = null;
                    //row[4] = veh_rate.ToString();
                    //dt2.Rows.Add(row);
 
                    dt2.Rows.Add("small",veh_rate.ToString());
                }
                if(dt2.Rows[j][2].ToString()=="Regular Car")
                {
                    veh_rate = Convert.ToInt32(dt2.Rows[j][3].ToString());
                    veh_rate = veh_rate + regular;
                    dt2.Rows.Add("Regular", veh_rate.ToString());
                }
                if(dt2.Rows[j][2].ToString()=="Luxury Car")
                {
                    veh_rate = Convert.ToInt32(dt2.Rows[j][3].ToString());
                    veh_rate = veh_rate + luxury;
                    dt2.Rows.Add("Luxury", veh_rate.ToString());
                }
            }
        }
        GridView1.DataSource = dt2;
        GridView1.DataBind();
Where:
dt2 is the datatable,
veh_rate stores vehicle rate
 
But new records are added below of the previous records.
 
Please help me, thank you very much.

Answers (2)