How to list Row Headers from SQL in C# - c#

I've been trying to find a way to create Row Headers (DataGridView) from Tables.
My Table consists name of days e.g. Mon, Tue, Wed, ... so on.
How can I achieve this?
Sorry, I'm very new to C# and I need a huge help.
Here's my code:
string queryString2 = "select * from DayType";
using (SqlCommand command = conn.CreateCommand())
{
command.CommandText = queryString2;
conn.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
dataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
dataGridView1.Rows[0].HeaderCell.Value = (reader["WhichDay"].ToString());
}
}
conn.Close();
//UPDATE:
//This is what i'm trying to achieve:
//-------------------------------------------
// | 12:00 | 13:00 | 14:00 | 15:00 ---> Read from SQL Table 2
//-------------------------------------------
// Mon | 0 | 0 | 0 | 0
//-------------------------------------------
// Tue | 0 | 0 | 0 | 0
//-------------------------------------------
// Wed | 0 | 0 | 0 | 0
//-------------------------------------------
// Thu | 0 | 0 | 0 | 0
//-------------------------------------------
// |
// V
//Read from SQL Table 1

use the below code
dataGridView1.HeaderRow.Cells[0].Text = (reader["WhichDay"].ToString());

Related

Unpivot data excel with merged column using SSIS

I'm using SSIS to export from Excel to text and in my case, I need to export where the file contains merged columns anyone can help or have suggest for my case?
Input Excel
A B C D E
+-------------+-----------------+-----------------+
| Shop Name | Monday | Tuesday |
| +---------+-------+---------+-------+
| | Jackson | Steve | Jackson | Steve |
+-------------+---------+-------+---------+-------+
| 7Eleven | 11 | 30 | 23 | 21 |
+-------------+---------+-------+---------+-------+
| Delta Shop | 43 | 12 | 33 | 2 |
+-------------+---------+-------+---------+-------+
Output Expected
+-------------+---------+-------------+-------+
| Shop_Name | Day | Member_Name | Point |
+-------------+---------+-------------+-------+
| 7Eleven | Monday | Jackson | 11 |
+-------------+---------+-------------+-------+
| 7Eleven | Monday | Steve | 30 |
+-------------+---------+-------------+-------+
| Delta Shop | Monday | Jackson | 43 |
+-------------+---------+-------------+-------+
| Delta Shop | Monday | Steve | 12 |
+-------------+---------+-------------+-------+
| 7Eleven | Tuesday | Jackson | 23 |
+-------------+---------+-------------+-------+
| 7Eleven | Tuesday | Steve | 21 |
+-------------+---------+-------------+-------+
| Delta Shop | Tuesday | Jackson | 33 |
+-------------+---------+-------------+-------+
| Delta Shop | Tuesday | Steve | 2 |
+-------------+---------+-------------+-------+
Using oledb and ACE driver (Microsoft Office) to read excel file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
namespace ConsoleApplication124
{
class Program
{
static void Main(string[] args)
{
string connStr = "Provider=Microsoft.ACE.OLEDB.15.0;Data Source=c:\\temp\\test.xlsx;Extended Properties=\"Excel 12.0;HDR=NO;IMEX=1\"";
string query = "Select * From [Sheet1$]";
OleDbDataAdapter adapter = new OleDbDataAdapter(query, connStr);
DataTable dt = new DataTable();
adapter.Fill(dt);
string[] days = dt.Rows[0].ItemArray.Skip(1).Select(x => (x == DBNull.Value) ? string.Empty : ((string)x).Trim()).ToArray();
string[] people = dt.Rows[1].ItemArray.Skip(1).Select(x => (x == DBNull.Value) ? string.Empty : ((string)x).Trim()).ToArray();
int numberDays = days.Where(x => x != string.Empty).Count();
int numberPeople = people.Where(x => x != string.Empty).Distinct().Count();
string[] columnNames = { "Shop_Name", "Day", "Member_Name", "Point" };
Console.WriteLine(string.Join(",", columnNames));
for (int row = 2; row < dt.Rows.Count; row++)
{
string[] columns = dt.Rows[row].ItemArray.Select(x => (x == DBNull.Value) ? string.Empty : ((string)x).Trim()).ToArray();
string shop = columns[0];
for (int col = 1; col < dt.Rows[row].ItemArray.Count(); col++)
{
object point = dt.Rows[row].Field<string>(col);
if (point != null)
{
string pointStr = ((string)point).Trim();
int dayIndex = numberPeople * ((col - 1) / numberPeople);
string day = days[dayIndex];
string person = people[col - 1];
string[] outputData = { shop, day, person, pointStr };
Console.WriteLine(string.Join(",", outputData));
}
}
}
Console.ReadLine();
}
}
}

How to get group of records with latest date using Linq to Entities

I have a table with the following fields:
ID | MarketID | CommodityID | CurrencyID | PriceValue | Year | Month
With the following data:
1 | 100 | 30 | 15 | 3.465 | 2018 | 03
2 | 100 | 30 | 15 | 2.372 | 2018 | 04
3 | 100 | 32 | 15 | 1.431 | 2018 | 02
4 | 100 | 32 | 15 | 1.855 | 2018 | 03
5 | 100 | 32 | 15 | 2.065 | 2018 | 04
6 | 101 | 30 | 15 | 7.732 | 2018 | 03
7 | 101 | 30 | 15 | 8.978 | 2018 | 04
8 | 101 | 32 | 15 | 4.601 | 2018 | 02
9 | 101 | 32 | 18 | 0.138 | 2017 | 12
10 | 101 | 32 | 18 | 0.165 | 2018 | 03
11 | 101 | 32 | 18 | 0.202 | 2018 | 04
As you can see the date is (unfortunately) saved as an integer in the Year and Month fields.
I want to get from the above data, using LINQ to Entities (EF6), the latest PriceValue for each Market-Commodity-Currency record.
So the expected result should be:
2 | 100 | 30 | 15 | 2.372 | 2018 | 04
5 | 100 | 32 | 15 | 2.065 | 2018 | 04
7 | 101 | 30 | 15 | 8.978 | 2018 | 04
8 | 101 | 32 | 15 | 4.601 | 2018 | 02
11 | 101 | 32 | 18 | 0.202 | 2018 | 04
I've tried with the following queries but none of them can give me the expected results:
var lastValues = (from a in Analysis
group a by a.ID into g
select g.OrderByDescending(t => ((t.Year* 100) + t.Month)));
and the following that has more sense of the previous one, but I loose the PriceValue field:
var lastValues = (from a in Analysis
group a by new {a.MarketID, a.CommodityID, a.CurrencyID } into g
select new
{
g.Key.MarketID,
g.Key.CommodityID,
g.Key.CurrencyID,
date = g.Max(t => ((t.Year* 100) + t.Month))
});
Is there a way to have a single LINQ query to get only the records with the latest date as I've described above?
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ConsoleApplication45
{
class Program
{
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("MARKETID", typeof(int));
dt.Columns.Add("CommodityID", typeof(int));
dt.Columns.Add("CurrencyID", typeof(int));
dt.Columns.Add("PriceValue", typeof(decimal));
dt.Columns.Add("Year", typeof(int));
dt.Columns.Add("Month", typeof(int));
//ID | MarketID | CommodityID | CurrencyID | PriceValue | Year | Month
dt.Rows.Add(new object[] {1 , 100 , 30 , 15 , 3.465 , 2018 , 03});
dt.Rows.Add(new object[] {2 , 100 , 30 , 15 , 2.372 , 2018 , 04});
dt.Rows.Add(new object[] {3 , 100 , 32 , 15 , 1.431 , 2018 , 02});
dt.Rows.Add(new object[] {4 , 100 , 32 , 15 , 1.855 , 2018 , 03});
dt.Rows.Add(new object[] {5 , 100 , 32 , 15 , 2.065 , 2018 , 04});
dt.Rows.Add(new object[] {6 , 101 , 30 , 15 , 7.732 , 2018 , 03});
dt.Rows.Add(new object[] {7 , 101 , 30 , 15 , 8.978 , 2018 , 04});
dt.Rows.Add(new object[] {8 , 101 , 32 , 15 , 4.601 , 2018 , 02});
dt.Rows.Add(new object[] {9 , 101 , 32 , 18 , 0.138 , 2017 , 12});
dt.Rows.Add(new object[] {10 , 101 , 32 , 18 , 0.165 , 2018 , 03});
dt.Rows.Add(new object[] { 11, 101, 32, 18, 0.202, 2018, 04 });
List<DataRow> results = dt.AsEnumerable()
.OrderByDescending(x => new DateTime(x.Field<int>("Year"), x.Field<int>("Month"), 1))
.GroupBy(x => new { market = x.Field<int>("MarketID"), commodity = x.Field<int>("CommodityID"), currency = x.Field<int>("CurrencyID") })
.Select(x => x.First())
.ToList();
}
}
}
I've finally found the way to include also the PriceValue in the results.
Starting from the last query I've posted, I've to simply add the
g.OrderByDescending(t => ((t.Year* 100) + t.Month)).FirstOrDefault().PriceValue
So it will be:
var lastValues = (from a in Analysis
group a by new {a.MarketID, a.CommodityID, a.CurrencyID } into g
select new
{
g.Key.MarketID,
g.Key.CommodityID,
g.Key.CurrencyID,
date = g.Max(t => ((t.Year* 100) + t.Month)),
g.OrderByDescending(t => ((t.Year* 100) + t.Month)).FirstOrDefault().PriceValue
});
I prefer this solution as it's based on the current query I've developed.
Try This Linq Query
var lastValues = (from ak in Analysis
group ak by new { ak.MarketID, ak.CommodityID, ak.CurrencyID } into g
select new
{
g.Key.MarketID,
g.Key.CommodityID,
g.Key.CurrencyID,
pricevalue = g.OrderByDescending(c=>c.Year).ThenByDescending(c=>c.Month).FirstOrDefault().PriceValue,
year = g.OrderByDescending(c => c.Year).ThenByDescending(c => c.Month).FirstOrDefault().Year,
month = g.OrderByDescending(c => c.Year).ThenByDescending(c => c.Month).FirstOrDefault().Month
});
Using Orderby and ThenBy

Color the datagridview there where it found a difference with SQL

I got some code which makes an SQL query and pastes the result into a datagridview. This works perfectly. The code be seen below:
private void FillInDataGrid()
{
string cn = ConfigurationManager.ConnectionStrings["Scratchpad"].ConnectionString;
SqlConnection myConnection = new SqlConnection(cn);
string sql =
"SELECT " +
" dbo.new.[column1], dbo.new.[column2], dbo.new.[column3], dbo.new.[column4] from dbo.new" +
"except " +
"select dbo.old.[column1], dbo.old.[column2], dbo.old.[column3], dbo.old.[column4] from dbo.old"
;
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, myConnection);
DataSet ds = new DataSet();
myConnection.Open();
dataadapter.Fill(ds, "Authors_table");
myConnection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Authors_table";
}
This code displays the values of the row from the new table if it doenst exists in the old table. Now I want to color the cells where they differ. So for example if you have those two tables:
new table:
--------------------------------------
| column1 | column2| column3| column4|
--------------------------------------
| 1 | 1 | 1 | 2 |
--------------------------------------
| 2 | 2 | 3 | 2 |
--------------------------------------
| 6 | 7 | 9 | 8 |
--------------------------------------
| 7 | 5 | 34 | 22 |
--------------------------------------
| 3 | 4 | 3 | 3 |
--------------------------------------
old table:
--------------------------------------
| column1 | column2| column3| column4|
--------------------------------------
| 6 | 7 | 9 | 8 |
--------------------------------------
| 7 | 5 | 34 | 22 |
--------------------------------------
| 1 | 1 | 1 | 1 |
--------------------------------------
| 2 | 2 | 2 | 2 |
--------------------------------------
| 3 | 3 | 3 | 3 |
--------------------------------------
So this example would show:
--------------------------------------
| column1 | column2| column3| column4|
--------------------------------------
| 1 | 1 | 1 | *2* |
--------------------------------------
| 2 | 2 | *3* | *2* |
--------------------------------------
| 3 | *4* | *3* | *3* |
--------------------------------------
Where the * 2 *, * 3 * and * 4 * would show a color in the datagridview.
Thanks in advance for your help.

dynamic menustrip

I m trying to create dynamic menu using C# WinForm Project. My database structure is mentioned below. I can create the top menu ie "FILE", "EDIT", "SEARCH". But I cannot run the recursive function for the Child menu.
mysql> select * from dynamicmenu;
+------+-----------------+--------+-------+-----------+
| SLN | Child | Parent | Level | Reference |
+------+-----------------+--------+-------+-----------+
| 1 | FILE | NULL | 0 | NULL |
| 2 | EDIT | NULL | 0 | NULL |
| 3 | SEARCH | NULL | 0 | NULL |
| 4 | Session Manager | FILE | 1 | 1 |
| 5 | Connect To | FILE | 1 | 1 |
| 6 | DO | FILE | 2 | 5 |
| 7 | Copy | EDIT | 1 | 2 |
| 8 | Paste | EDIT | 1 | 2 |
| 9 | Find Text | SEARCH | 1 | 3 |
| 10 | Cut | EDIT | 2 | 7 |
| 11 | VMS | FILE | 3 | 6 |
+------+-----------------+--------+-------+-----------+
11 rows in set (0.00 sec)
The c# code is as follows.
mysqlConn conn;
private void Form1_Load(object sender, EventArgs e)
{
conn = new mysqlConn();
conn.OpenConnection();
MySqlCommand cmd = new MySqlCommand("Select * from dynamicmenu", conn.connection);
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr["Parent"].ToString() == "")
{
menuStrip1.Items.Add(dr["Child"].ToString());
}
else if (dr["Parent"].ToString() != "")
{
AddSubMenu(new ToolStripMenuItem(dr["Child"].ToString()), dr["Parent"].ToString());
}
}
dr.Close();
conn.CloseConnection();
}
private void AddSubMenu(ToolStripMenuItem ChildItem, string ParentItem)
{
foreach (ToolStripMenuItem item in menuStrip1.Items)
{
if (ParentItem == item.Name)
{
item.DropDownItems.Add(ChildItem);
}
}
}
Please advise.
Use toString() instead of name.
private void AddSubMenu(ToolStripMenuItem ChildItem, string ParentItem)
{
foreach (ToolStripMenuItem item in menuStrip1.Items)
{
if (ParentItem == item.ToString())
{
item.DropDownItems.Add(ChildItem);
}
}
}

How to take the difference of two sums in two tables in mysql

I have two tables to treat in a query for getting the product in hand.
ProdBiscuit
+----+-----+-------+---------------+
| ID | QTY |StockID| Name |
+----+-----+-------+---------------+
| 1 | 100 | 1 | Bis Chocolat |
+----+-----+-------+---------------+
| 2 | 120 | 2 | Bis Moutarde |
+----+-----+-------+---------------+
| 3 | 100 | 3 | Bis Epice |
+----+-----+-------+---------------+
StockData
+----+-----+-------+------+----+
| ID | QTY |ProdID |Status|Type|
+----+-----+-------+------+----+
| 1 | 100 | 1 | 0 | 3 |
+----+-----+-------+------+----+
| 2 | 120 | 2 | 0 | 3 |
+----+-----+-------+------+----+
| 3 | 100 | 3 | 0 | 3 |
+----+-----+-------+------+----
| 4 | 200 | 1 | 0 | 4 |
+----+-----+-------+------+----+
| 5 | 200 | 2 | 0 | 4 |
+----+-----+-------+------+----+
| 6 | 48 | 1 | 0 | 2 |
+----+-----+-------+------+----+
| 7 | 96 | 2 | 4 | 3 |
+----+-----+-------+------+----+
| 8 | 200 | 1 | 4 | 4
+----+-----+-------+------+----+
ProdBiscuit ID is relational with StockData.ProdID
ProdBiscuit.StockId is relational with StockData.ID
StockData.Status = 0 => Entry in stock, > 0 =>Left the stock
Type means 2=>Macaron, 3=>Biscuit, 4=>Ganache
ProdID => ID of ProdBiscuit
StockID-> ID of StockData
With the method below I get this
+--------------+--------+---------+
|Name |QTY PROD|QTY REST |
+--------------+--------+---------+
|Bis Chocolat | 100 | 100 |
+--------------+--------+---------+
|Bis Moutarde | 120 | 24 |
+--------------+--------+---------+
|Bis Epice | 100 | 100 |
+--------------+--------+---------+
Result is correct but the query seems to me to be incorrect.
Because in WHERE clause query search the rows where status > 0
However I get the correct result??
Here is my code :
private void RefreshProd()
{
Int16 ProdQty;
Int16 UsedQty;
DateLst.Items.Clear();
ProdLst.Items.Clear();
QtyLst.Items.Clear();
NomLst.Items.Clear();
prodidLst.Items.Clear();
using (MySqlConnection conn = new MySqlConnection(PublicVariables.cs))
{
using (MySqlCommand cmd = new MySqlCommand("SELECT tb.id, tb.qty,tb.nom, tb.proddate, IF(status > 0 AND tb.id = sd.prodid, sd.quantite, 0) AS rq FROM StockData AS sd, " + TableName + " AS tb WHERE sd.matcuisine = 3 AND sd.status > 0", conn))
{
conn.Open();
try
{
MySqlDataReader r = cmd.ExecuteReader();
while (r.Read())
{
DateLst.Items.Add(Convert.ToDateTime(r["proddate"]).ToString("d"));
ProdQty = Convert.ToInt16(r["qty"]);
UsedQty = Convert.ToInt16(r["rq"]);
ProdLst.Items.Add(r["qty"]).ToString();
NomLst.Items.Add(r["nom"]);
prodidLst.Items.Add(r["id"]).ToString();
QtyLst.Items.Add((ProdQty-UsedQty).ToString());
}
}
catch (MySqlException e)
{
MessageBox.Show("MYSQL ERROR--> " + e.ToString());
}
}
}
}
I could not find the rub.
The thing that's astonishing me that the query seems to me to be faulty but gives a correct result.
In where clause I put a condition that the search must be "sd.status>0" but it seems to me it's fetching the status = ZERO conditions too.(Perhaps I am missing something technical in MYSQL WHERE clause)
How ever bu doing my premenade overthestackflow I learnt that UNION and JOIN is more powerfull then the method that I use.
Is there a more efficient way to write my query by JOIN oro UNION? I will appreciate your help. Because I couldn't find way to resolve it by this way.
this query?
SELECT
tb.id
, tb.qty
, tb.nom
, tb.proddate
, sd.quantity as rq
FROM
StockData AS sd
INNER JOIN " + TableName + " AS tb
On tb.id = sd.prodid
WHERE
sd.matcuisine = 3
AND sd.status > 0

Categories