Here I have selected rows data table through loop how can i fill matching records in Data Base to another data table
my code :
for (int i = 0; i <= selectedrows.Rows.Count - 1; i++)
{
string date1 = selectedrows.Rows[i]["Date"].ToString();
System.DateTime dateexcel = System.DateTime.ParseExact(date1, "MM/dd/yyyy", CultureInfo.InvariantCulture);
//check select rows exists or not in DB
SqlCommand cmd = new SqlCommand("select * from UploadTable where Date='" + dateexcel+"'", con);
da = new SqlDataAdapter(cmd);
DBdt = new DataTable();
da.Fill(DBdt); // Here i need to fill all the rows matching in DB not a one row
}
Thank you
You can use DataTable.Merge:
DataTable mainTable = new DataTable();
for (int i = 0; i <= selectedrows.Rows.Count - 1; i++)
{
string date1 = selectedrows.Rows[i]["Date"].ToString();
System.DateTime dateexcel = System.DateTime.ParseExact(date1, "MM/dd/yyyy", CultureInfo.InvariantCulture);
//check select rows exists or not in DB
SqlCommand cmd = new SqlCommand("select * from UploadTable where Date='" + dateexcel+"'", con);
da = new SqlDataAdapter(cmd);
var dBdt = new DataTable();
da.Fill(dBdt);
mainTable.Merge(dBdt);
}
Related
I have a datagridView which has 2 columns that will be filled by the database.
In the database I have this:
Column1 : Name Column2 : Quantity Column 3 : Date
a 1 2019
b 2 2018
c 3 2017
a 4 2015
So what I need is to show in my combobox for Name a : (1 - 2019)(4 - 2015)
Here what I did :
using (MySqlDataAdapter sda = new MySqlDataAdapter(#"SELECT DISTINCT Name ,CONCAT(Quantite ,'PCS -' ,Date) as Conc FROM articles", MyConnexion))
{
DataTable dt = new DataTable();
sda.Fill(dt);
DTG_Bordereau.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
DTG_Bordereau.Columns[0].DataPropertyName = "Name";
DTG_Bordereau.Columns[3].Width = 300;
DTG_Bordereau.DataSource = dt;
for (int i = 0; i < dt.Rows.Count; i++)
{
var val = dt.Rows[i]["Conc"].ToString();
//check if it already exists
if (!QuantiteDisponible.Items.Contains(val))
{
QuantiteDisponible.Items.Add(val);
}
}
using (MySqlDataAdapter sda = new MySqlDataAdapter(#"SELECT DISTINCT Name FROM articles", MyConnexion))
{
DataTable dt = new DataTable();
sda.Fill(dt);
DTG_Bordereau.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
DTG_Bordereau.Columns[0].DataPropertyName = "Name";
DTG_Bordereau.Columns[3].Width = 300;
DTG_Bordereau.DataSource = dt;
try
{
for (int i = 0; i < dt.Rows.Count; i++)
{
QuantiteDisponible.Items.Clear();
MySqlDataAdapter sda2 = new MySqlDataAdapter("SELECT DISTINCT CONCAT(Quantite ,'PCS -' ,Date) as Conc FROM articles where Name='" + dt.Rows[i][0].ToString() + "'", MyConnexion);
DataTable dt2 = new DataTable();
sda2.Fill(dt2);
QuantiteDisponible.DataSource = dt2;
QuantiteDisponible.DisplayMember = "Conc";
QuantiteDisponible.ValueMember = "Conc";
}
}
catch
{ }
}
So with this code, my first combobox is correct, but the other comboboxes are taking the same value of the first combobox....
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;
}
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
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
{
}
}
hi i am trying to store data from the database into a variable and then trying to process it.
but somehow the variable does not read any data from the database and gives its initial value.
heres the code
int c1=0,c2=0.c3=0,c4=0,sum;
if (rbFour.Checked == true)
{
proce = cmb1.Text + "," + cmb2.Text + "," + cmb3.Text + "," + cmb4.Text;
SqlDataAdapter d = new SqlDataAdapter("Select Amount from addpro where SSN=" + cmb1.ValueMember, Program.con);
DataTable t = new DataTable();
foreach (DataRow row in t.Rows)
{
c1 = Convert.ToInt32(row[0]);
}
SqlDataAdapter qd = new SqlDataAdapter("Select Amount from addpro where SSN=" + cmb2.ValueMember, Program.con);
DataTable qt = new DataTable();
foreach (DataRow row in qt.Rows)
{
c2 = Convert.ToInt32(row[0]);
}
SqlDataAdapter wd = new SqlDataAdapter("Select Amount from addpro where SSN=" + cmb3.ValueMember, Program.con);
DataTable wt = new DataTable();
foreach (DataRow row in wt.Rows)
{
c3 = Convert.ToInt32(row[0]);
}
SqlDataAdapter ed = new SqlDataAdapter("Select Amount from addpro where SSN=" + cmb4.ValueMember, Program.con);
DataTable et = new DataTable();
foreach (DataRow row in et.Rows)
{
c4 = Convert.ToInt32(row[0]);
}
}
else if (rbThree.Checked == true)
{
proce = cmb1.Text + "," + cmb2.Text + "," + cmb3.Text;
SqlDataAdapter d = new SqlDataAdapter("Select Amount from addpro where SSN=" + cmb1.ValueMember, Program.con);
DataTable t = new DataTable();
foreach (DataRow row in t.Rows)
{
c1 = Convert.ToInt32(row[0]);
}
SqlDataAdapter qd = new SqlDataAdapter("Select Amount from addpro where SSN=" + cmb2.ValueMember, Program.con);
DataTable qt = new DataTable();
foreach (DataRow row in qt.Rows)
{
c2 = Convert.ToInt32(row[0]);
}
SqlDataAdapter wd = new SqlDataAdapter("Select Amount from addpro where SSN=" + cmb3.ValueMember, Program.con);
DataTable wt = new DataTable();
foreach (DataRow row in wt.Rows)
{
c3 = Convert.ToInt32(row[0]);
}
}
else if (rbTwo.Checked == true)
{
proce = cmb1.Text + "," + cmb2.Text;
SqlDataAdapter d = new SqlDataAdapter("Select Amount from addpro where SSN=" + cmb1.ValueMember, Program.con);
DataTable t = new DataTable();
foreach (DataRow row in t.Rows)
{
c1 = Convert.ToInt32(row[0]);
}
SqlDataAdapter qd = new SqlDataAdapter("Select Amount from addpro where SSN=" + cmb2.ValueMember, Program.con);
DataTable qt = new DataTable();
qd.Fill(qt);
foreach (DataRow row in qt.Rows)
{
c2 = Convert.ToInt32(row[0]);
}
}
else
{
proce = cmb1.Text;
SqlDataAdapter d = new SqlDataAdapter("Select Amount from addpro where SSN=" + cmb1.ValueMember, Program.con);
DataTable t = new DataTable();
foreach (DataRow row in t.Rows)
{
c1 = Convert.ToInt32(row[0]);
}
}
can anyone help with this.i used the same code few days ago.it worked fine.but now i dont know whats wrong with it.
i need the solution asap can anyone help plz?
You need to Fill a DataTable before using it
SqlDataAdapter d = new SqlDataAdapter("...", con);
DataTable t = new DataTable();
d.Fill(t); // Here
and so on for the remaining adapters.
However, let me show a different approach:
string sqlText = "Select Amount from addpro where SSN=#ssn";
SqlCommand cmd = new SqlCommand(sqlText, Program.con);
cmd.Parameters.AddWithValue("#ssn", cmb1.ValueMember);
object result = cmd.ExecuteScalar();
if(result != null)
c1 = Convert.ToInt32(result);
You are returning a single row with a single value (if found). This is the usage scenario provided by the ExecuteScalar method of the SqlCommand. There is no need to create a SqlAdapter, a DataTable and fill it with a single row/value.
Also, I have removed your string concatenation and used Parametrized queries to avoid Sql Injection Attacks. Albeit, in your code is a bit improbable, it is a good practice to use everywhere.
With the above code in place it is really easy to build a common method that receives the combobox control, apply the logic required and return the integer value
private int GetComboValue(ComboBox cbo)
{
// all the code above replacing cmb1 with cbo and c1 with ssnNumber
.....
return ssnNumber;
}
and now you can use
if (rbFour.Checked == true)
{
c1 = GetComboValue(cmb1);
c2 = GetComboValue(cmb2);
c3 = GetComboValue(cmb3);
c4 = GetComboValue(cmb4);
}
Use the fill() method to fill the datatable first with the dataadapter and then try to access the data rows
ex: d.fill(dt);