sum up data from Access to DataTable - c#

I have a database that contains a Column of 3 Defined Types and a Column of that contains numbers.
The types can appear severl time in the database.
I want to create a DataTable that will show each type one time only and sum up to numbers that relate to that type.
List<String> types = typesInTable(table);
DataTable t = new DataTable();
t.Clear();
t.Columns.Add("Type");
t.Columns.Add("Total Expenses");
foreach (String type in types)
{
DataRow tmp = t.NewRow();
tmp["Type"] = type;
int total = 0;
myConnection.Open();
OleDbDataReader reader = null;
OleDbCommand cmd = new OleDbCommand("SELECT [Type] , [Expense] FROM [" + table+"]", myConnection);
reader = cmd.ExecuteReader();
while (reader.Read())
{
if(reader["Type"].ToString().Equals(type))
{
total += Convert.ToInt32(reader["Expense"].ToString());
}
}
tmp["Total Expenses"] = total;
if (!t.Rows.Contains(tmp))
{
t.Rows.Add(tmp);
}
myConnection.Close();
}
This Code makes the types appear several times.

You can use this code to create DataTable that contains every type grouped with the sum :
DataTable t = new DataTable();
myConnection.Open();
string query = string.Format("SELECT Type, Sum(Expense) AS TotalExpenses FROM [{0}] group by Type", table);
OleDbCommand cmd = new OleDbCommand(query, myConnection);
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(t);
myConnection.Close();
if You want to sum up the types from different tables all together in 1 DataTable use this:
List<String> tableList = serviceMethod.getTableList();
DataTable dtAllType = new DataTable();
foreach (string table in tableList)
{
DataTable dtTemp = new DataTable();
myConnection.Open();
string query = string.Format("SELECT Type, Sum(Expense) AS TotalExpenses FROM [{0}] group by Type", table);
OleDbCommand cmd = new OleDbCommand(query, myConnection);
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(dtTemp);
for (int i = 0; i < dtTemp.Rows.Count; i++)
{
bool isDupe = false;
for (int j = 0; j < dtAllType.Rows.Count; j++)
{
if (dtTemp.Rows[i][0].ToString() == dtAllType.Rows[j][0].ToString())
{
dtAllType.Rows[j][1] = int.Parse(dtAllType.Rows[j][1].ToString()) + int.Parse(dtTemp.Rows[i][1].ToString());
isDupe = true;
break;
}
}
if (!isDupe)
{
dtAllType.ImportRow(dtTemp.Rows[i]);
}
}
myConnection.Close();
}
the dtAllType DataTable contain Type grouped with sum of Expence

Related

Binding data from SQL Table to custom list created using user control in C#

I am working a project and i need to display on a form (frmCaterlogs) a list of items. I have successfully implimented a custom list using a user control & FlowLayOutPanel. However now i am stuck on how i can bind my caterlogs that sits on a sql database to my custom list: Here is my code. on the custome_list(CatList), i have 4 controls, Id, Titile, Description, Icon stored in database as binarydata in the sqldb. I am lost on how i can bind data to the custom list control that can look thought all the records in my database. Thanking you all in advace for your kind advices.
private void PopulateCatelog()// This code is triggered when frmcaterlogs loads.
{
int l;
string query = "SELECT * from ServicesCaterlogs";
SqlConnection con = new SqlConnection(cn);
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
ListView Items = new ListView()
sda.Fill(dt);
l = dt.Rows.Count;
foreach(DataRow dr in dt.Rows) // This is where i am stuck
{
CatList iList = new CatList(dr["Item"].ToString());
iList.Title = dr;
}
CatList[] ListItem = new CatList[l];
//Loop though to check each item
for (int i = 0; i < ListItem.Length; i++)
{
ListItem[i] = new CatList();
ListItem[i].Title = fetch data for a list;
ListItem[i].Message = "fetch data for a lis";
ListItem[i].icon = Resources.Warning;
ListItem[i].IconBackground1 = Color.DarkGoldenrod;
if (FlowLayoutPanel.Controls.Count < 0)
{
FlowLayoutPanel.Controls.Clear();
}
else
{
FlowLayoutPanel.Controls.Add(ListItem[i]);
}
}
I got the desired result after altering the code as seen below
private void FrmCatalogs_Load(object sender, EventArgs e)
{
PopulateCatelog();
}
private void PopulateCatelog()
{
//Populate your listitem here
int l;
string query = "SELECT * from ServicesCaterlogs";
SqlConnection con = new SqlConnection(cn);
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
l = dt.Rows.Count;
foreach(DataRow dr in dt.Rows)
{
ListViewItem item = new ListViewItem(dr["Item"].ToString());
ListViewItem des = new ListViewItem(dr["Item_Description"].ToString());
CatList[] ListItem = new CatList[l];
for (int i = 0; i < ListItem.Length - l +1 ; i++)
{
ListItem[i] = new CatList();
ListItem[i].Title = item.Text;
ListItem[i].Message = des.Text;
ListItem[i].icon = Resources.Warning;
ListItem[i].IconBackground1 = Color.DarkGoldenrod;
if (FlowLayoutPanel.Controls.Count < 0)
{
FlowLayoutPanel.Controls.Clear();
}
else
{
FlowLayoutPanel.Controls.Add(ListItem[i]);
}
}
}
}

Chart from SQL Datasource but DateTime in Ticks

I have a SQL database that stores some data that I would like to chart. The problem is, I inherited this database and they store the datetime values as Ticks. When I set my chart datasource to this table, it doesn't seem to understand ticks.
How do I get my chart to convert the ticks back to a DateTime format that my chart understands?
Database Table
My SQL query and code:
static public DataTable get_I1(RunningTests rt)
{
DataTable dt = new DataTable();
using (SqlConnection cs = new SqlConnection(connString))
{
string query = string.Format("SELECT Time_Stamp, I1 FROM Test WHERE Unit_ID = '{0}' AND Time_Stamp >= '{1}' AND Time_Stamp <= '{2}'", rt.Unit_ID, rt.StartTime.Ticks, rt.StopTime.Ticks);
Console.WriteLine(query);
SqlCommand cmd = new SqlCommand(query, cs);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
dt.DefaultView.Sort = "Time_Stamp DESC";
dt = dt.DefaultView.ToTable();
return dt;
}
My code to set my chart datasource:
private void do_chart_I1(RunningTests rt)
{
muCalGUI1.chartI1.Series.Clear();
DataTable dt = SQL.get_I1(rt);
muCalGUI1.chartI1.DataSource = dt;
Series s = new Series("I1");
s.XValueMember = "Time_Stamp";
s.YValueMembers = "I1";
s.ChartType = SeriesChartType.Line;
s.BorderWidth = 2;
s.MarkerSize = 5;
s.MarkerStyle = MarkerStyle.Circle;
muCalGUI1.chartI1.ChartAreas[0].AxisY.IsStartedFromZero = false;
muCalGUI1.chartI1.ChartAreas[0].AxisX.LabelStyle.Format = "yyyy-MM-dd\nHH:mm:ss";
muCalGUI1.chartI1.ChartAreas[0].AxisY.LabelStyle.Format = "0";
muCalGUI1.chartI1.ChartAreas[0].RecalculateAxesScale();
muCalGUI1.chartI1.Series.Add(s);
muCalGUI1.chartI1.Legends.Clear();
}
Results:
Desired Results:
I have a solution that works. If someone can provide a 'more clean' approach, I'll be happy to mark that as the answer. For now my work around was to create a new datatable and convert the ticks to a datetime.
SQL Code:
static public DataTable get_I1(RunningTests rt)
{
DataTable dt = new DataTable();
using (SqlConnection cs = new SqlConnection(connString))
{
//string query = string.Format("Select TOP {0} Serial AS [Serial #], Start, [Stop], N, ROUND(Mean,4) AS Mean, ROUND(StdDev,4) AS [Standard Deviation], ROUND(Minimum,4) AS Min, ROUND(Maximum,4) AS Max FROM TestTime JOIN Membrane ON TestTime.Membrane_ID = Membrane.Membrane_ID WHERE Serial LIKE '{1}' ORDER BY TestTime_ID", numRecords, serial);
string query = string.Format("SELECT Time_Stamp, I1 FROM Test WHERE Unit_ID = '{0}' AND Time_Stamp >= '{1}' AND Time_Stamp <= '{2}'", rt.Unit_ID, rt.StartTime.Ticks, rt.StopTime.Ticks);
SqlCommand cmd = new SqlCommand(query, cs);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
//Previous user stored the date time as ticks, have to convert back to DateTime
DataTable dtCloned = new DataTable();
dtCloned.Clear();
dtCloned.Columns.Add("Time_Stamp", typeof(DateTime));
dtCloned.Columns.Add("I1", typeof(int));
foreach (DataRow dr in dt.Rows)
{
DataRow r = dtCloned.NewRow();
r[0] = new DateTime((long)dr[0]);
r[1] = dr[1];
dtCloned.Rows.Add(r);
}
dtCloned.DefaultView.Sort = "Time_Stamp DESC";
dtCloned = dtCloned.DefaultView.ToTable();
return dtCloned;
}

C# Checkedlistbox data binding

I have a checkedlistBox in C# that I am filling from sql-server.
I need to insert the checkeditems when creating a new record and I need to update the previous selected items of a certain record.
First I am trying to read the selected item of a specific record so i tried the following:
I compare the value member of every item with the list I am getting from the sql query if it matches I check the item.
So I need to use something like the value option.
if(checkedListBox1.Items.IndexOf(i).**Value**
string sql = #"select cs.id from[dbo].[Channel_availableSpecs] cas inner join[dbo].[Channel_specs] cs on cas.ChennelSpec_Id = cs.id
where cas.Channel_Id =" + val + "order by cs.id";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dta = new DataTable();
da.Fill(dta);
foreach (DataRow dr in dta.Rows)
{
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
if(checkedListBox1.Items.IndexOf(i).**Value** == dr.ToString()) checkedListBox1.SetItemCheckState(i, CheckState.Checked);
}
conn.Close();
}
}
Fill Checkedlistbox
public static void FillCheckedListox(CheckedListBox checkedListBox, string query,string displayMember, string valueMember) {
using (SqlConnection con = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
((ListBox)checkedListBox).DataSource = dt;
((ListBox)checkedListBox).DisplayMember = displayMember;
((ListBox)checkedListBox).ValueMember = valueMember;
}
}
}
This is the solution
private void selectSpecs(DataTable table)
{
while (checkedListBox1.CheckedIndices.Count > 0)
{
checkedListBox1.SetItemChecked(checkedListBox1.CheckedIndices[0], false);
}
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
DataRow r;
r = ((DataRowView)this.checkedListBox1.Items[i]).Row;
string val = (r[this.checkedListBox1.ValueMember]).ToString();
channelsSpecs.Add(Convert.ToInt32(val));
r = null;
for (int j = 0; j < table.Rows.Count; j++)
foreach (DataRow dataRow in table.Rows)
foreach (var item in dataRow.ItemArray) if (val.ToString() == item.ToString()) checkedListBox1.SetItemChecked(i, true);
}
}

I need to retrieve the vaL1 in c# using ,search by red and blue value and find two values

This value (val1) I'm passing through url (I mean this operation as jobong filter option in checkbox list, filtering by selection index then passing through another page and retrieve through database):
Default Page 3: /WebSite4/Default4.aspx?vaL1=blue,red
This retrieving form page to view in page.
Default Page 2:
public void grid()
{
con.Open();
cmd = new SqlCommand("select * from lady_cloth where color in('" + Request.QueryString["vaL1"] + "')", con);
SqlDataAdapter da1 = new SqlDataAdapter(cmd);
DataSet ds3 = new DataSet();
da1.Fill(ds3);
con.Close();
if (ds3.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds3;
GridView1.DataBind();
}
else
{
}
}
SqlConnection con = new SqlConnection("Data Source=xxxx;Initial Catalog=e_commerce;User ID=sa;Password=xxx");
SqlCommand cmd = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Label1.Text = Request.QueryString["Item"];
//Label2.Text = Request.QueryString["Color"];
//grid();
var colourTable = new DataTable();
colourTable.Columns.Add("Value", typeof(string));
var colours = Request.QueryString["vaL1"].Split(',');
for (int i = 0; i < colours.Length; i++)
{
var newRow = colourTable.NewRow();
newRow[0] = colours[i];
colourTable.Rows.Add(newRow);
}
}
string sql = "SELECT * FROM lady_cloth WHERE color IN (SELECT Value FROM #Colours)";
cmd = new SqlCommand(sql, con);
DataSet ds3 = new DataSet();
using (var adapter = new SqlDataAdapter(sql, con))
{
var parameter = new SqlParameter("#Colours", SqlDbType.Structured);
//parameter.Value = colourTable;
parameter.TypeName = "dbo.StringList";
cmd.Parameters.Add(parameter);
con.Open();
adapter.Fill(ds3);
}
if (ds3.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds3;
GridView1.DataBind();
}
else
{
}
}
I think your problem is that you are not separating your items, so your SQL ends up looking like:
select *
from lady_cloth
where color in('blue,red')
Whereas what you would really want is
select *
from lady_cloth
where color in('blue','red')
If you are using SQL Server 2008 or later then I would recommend using table-valued parameters. The first step would be to create your type:
CREATE TYPE dbo.StringList TABLE (Value NVARCHAR(MAX));
I tend to just create generic types that can be easily reused, but this would be your call.
Then in your method you would need to split your values into an array and add them to a datatable:
var colourTable = new DataTable();
colourTable.Columns.Add("Value", typeof(string));
var colours = Request.QueryString["vaL1"].Split(',');
for (int i = 0; i < colours.Length; i++)
{
var newRow = colourTable.NewRow();
newRow[0] = colours[i];
colourTable.Rows.Add(newRow);
}
You can then add this table to your command as a parameter:
string sql = "SELECT * FROM lady_clock WHERE Color IN (SELECT Value FROM #Colours)"
cmd = new SqlCommand(sql, con);
var parameter = new SqlParameter("#Colours", SqlDbType.Structured);
parameter.Value = colourTable;
parameter.TypeName = "dbo.StringList";
cmd.Parameters.Add(parameter);
Finally, You can reduce your code by just initialising the SqlDataAdapter with your SQL and connection:
public void grid()
{
var colourTable = new DataTable();
colourTable.Columns.Add("Value", typeof(string));
var colours = Request.QueryString["vaL1"].Split(',');
for (int i = 0; i < colours.Length; i++)
{
var newRow = colourTable.NewRow();
newRow[0] = colours[i];
colourTable.Rows.Add(newRow);
}
string sql = "SELECT * FROM lady_clock WHERE Color IN (SELECT Value FROM #Colours)"
DataSet ds3 = new DataSet();
using (var adapter = new SqlDataAdapter(sql, con))
{
var parameter = new SqlParameter("#Colours", SqlDbType.Structured);
parameter.Value = colourTable;
parameter.TypeName = "dbo.StringList";
adapter.Parameters.Add(parameter);
con.Open();
da1.Fill(ds3);
}
if (ds3.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds3;
GridView1.DataBind();
}
else
{
}
}

Adding a column to a datatable and adding data

How can I add a column to a datatable and add data to each row based on a condition.
This is what I am trying to do
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OleDb.4.0;
Data Source =" + Server.MapPath("App_Data\\LR Product Database 2000.mdb"));
conn.Open();
Dictionary<string, string> items = new Dictionary<string, string>();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT CODE, TITLE FROM tblProducts";
OleDbDataReader dbread = cmd.ExecuteReader();
while (dbread.Read())
{
productCode = (string)dbread["ProductCode"];
productTitle = items[productCode];
items.Add(productCode, productTitle);
}
sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["LRVWebsite"].ToString());
sqlCon.Open();
dsSql = new DataSet();
SqlDataAdapter dba = new SqlDataAdapter(#"SELECT C.CustomerFirstName,C.CustomerLastName, C.CustomerCompany,C.CustomerPosition,C.CustomerCountry,C.CustomerProvince,C.CustomerContact,CP.ActionDate,CP.ProductCode,CP.CustomerEmail FROM tblCustomers C INNER JOIN tblCustomerProducts CP ON C.CustomerEmail = CP.CustomerEmail ORDER BY ActionDate DESC", connString);
dba.Fill(dsSql,"Products");
DataTable dt = dsSql.Tables["Products"];
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < items.Count; i++)
{
if (dr["ProductCode"].ToString().Equals(productCode))
{
//here I want to add a new column and add data (productTitle) to the column
}
}
}
dba.Fill(dsSql,"Products");
DataTable dt = dsSql.Tables["Products"];
dt.Columns.Add("ColumnName", typeof(DataType));
if (dr["ProductCode"].ToString().Equals(productCode))
{
dr["ColumnName"] = value;
}
Further i would extend the code to avoid NullReferenceException
if (!String.IsNullOrEmpty(dr["ProductCode"]) && dr["ProductCode"].ToString().Equals(productCode))
{
dr["ColumnName"] = value;
}
http://msdn.microsoft.com/en-us/library/hfx3s9wd.aspx

Categories