Reputation: 4334
i have managed to connect to an interbase database and get data from the database and store it in a dataset, i need to manipulate some of the data in the dataset and do something like the following,
add a new column in the dataset called total, for each row i need to add the 2nd and 3rd column and place the result into the total column.
can some one shed some light on how i may do this, im using the following code to get the data into a data set.
OdbcConnection conn = new OdbcConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString2"].ConnectionString;
DataSet ds = new DataSet();
OdbcDataAdapter da = new OdbcDataAdapter("SELECT * FROM MTD_FIGURE_VIEW1", conn);
da.Fill(ds);
Upvotes: 1
Views: 5096
Reputation: 8920
Have you considered letting the database do the work
OdbcDataAdapter da = new OdbcDataAdapter("SELECT *, (col1+col2) as sum FROM MTD_FIGURE_VIEW1", conn);
PS: you might want to get rid of your select * and use columnames
Upvotes: 1
Reputation: 1205
IF you are sure that your column values would never be null or empty then the best way is
ds.Tables[0].Columns.Add("Sum", typeof(double), "Col1 + Col2");
In case if your any column's value will be null then it wont give any exception but the total value would also be empty ...
If there can be any null value then try this
dt.Columns.Add("Total", typeof(double));
foreach (DataRow dr in dt.Rows)
{
if (String.IsNullOrEmpty(dr["col1"].ToString()))
dr["col1"] = 0.0;
if (String.IsNullOrEmpty(dr["col2"].ToString()))
dr["col2"] = 0.0;
dr["Total"] = Convert.ToDouble(dr["col1"]) + Convert.ToDouble(dr["col2"]);
}
In this case if you never check for null or empty value then this will give you a run time exception...
Upvotes: 1
Reputation: 9986
Following is how to >manipulate some of the data in the dataset
ds.Tables[0].Columns.Add("Sum", typeof(string));
foreach (DataRow drRow in ds.Tables[0].Rows)
{
drRow["Sum"] = (Convert.ToInt32(drRow["Col1"].ToString()) + Convert.ToInt32(drRow["Col2"].ToString())).ToString();
}
--UPDATE--
Something like following, using ternary operator:
drRow["Sum"] =
(string.IsNullOrEmpty(drRow["Col1"].ToString()) ? 0.00 : Convert.ToDouble(drRow["Col1"].ToString())) +
(string.IsNullOrEmpty(drRow["Col2"].ToString()) ? 0.00 : Convert.ToDouble(drRow["Col2"].ToString()));
Upvotes: 1
Reputation: 2458
This is the simplest way to do it
ds.Tables[0].Columns.Add("Sum", typeof(double), "Col1 + Col2");
Upvotes: 2