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);
Related
My chart doesn't seem to display the right values when it's a really small number (less than one). When I have big values (greater than one) it seems to chart and scale everything just fine. Any idea what I'm doing wrong?
My Charting Code:
private void do_chart_Conc(RunningTests rt, Chart c)
{
c.Series.Clear();
set_chart_alignment(c);
DataTable dt = SQL.get_Conc(rt);
c.DataSource = dt;
Series s = new Series("Conc");
s.XValueMember = "Time_Stamp";
s.YValueMembers = "Conc";
s.ChartType = SeriesChartType.Line;
s.BorderWidth = 2;
s.MarkerSize = 5;
s.MarkerStyle = MarkerStyle.Circle;
s.IsValueShownAsLabel = true;
s.Label = "#VALY{0.0000}";
c.ChartAreas[0].AxisY.IsStartedFromZero = false;
c.ChartAreas[0].AxisX.LabelStyle.Format = "yyyy-MM-dd\nHH:mm:ss";
c.ChartAreas[0].AxisY.LabelStyle.Format = "0.0000";
c.ChartAreas[0].RecalculateAxesScale();
c.Series.Add(s);
c.Legends.Clear();
}
My SQL Code:
static public DataTable get_Conc(RunningTests rt)
{
DataTable dt = new DataTable();
using (SqlConnection cs = new SqlConnection(connString))
{
string query = string.Empty;
if (rt.StopTime.Ticks > 0)
{
query = string.Format("SELECT Time_Stamp, RawConc FROM Test WHERE Unit_ID = '{0}' AND Time_Stamp > '{1}' AND Time_Stamp < '{2}'", rt.Unit_ID, rt.StartTime.Ticks, rt.StopTime.Ticks);
}
else
{
query = string.Format("SELECT Time_Stamp, RawConc FROM Test WHERE Unit_ID = '{0}' AND Time_Stamp > '{1}'", rt.Unit_ID, rt.StartTime.Ticks);
}
SqlCommand cmd = new SqlCommand(query, cs);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
//Person stored the date time to ticks, have to convert back to DateTime
DataTable dtCloned = new DataTable();
dtCloned.Clear();
dtCloned.Columns.Add("Time_Stamp", typeof(DateTime));
dtCloned.Columns.Add("Conc", 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;
}
Example Chart I'm getting:
Zoomed:
The example Data:
I would like it to chart the actual values and display them (instead of zero). IE: -0.0021
You are losing precision because you are feeding in a table with y-values as int.
Change
dtCloned.Columns.Add("Conc", typeof(int));
to
dtCloned.Columns.Add("Conc", typeof(double));
and all should be well..
Good afternoon, dear developers.
Faced such a problem:
there is DataGridVev, I have data lines in it. Depending on the toss-up, I need to sort the order of the rows in the display.
How can I do that?
As I understand the lines do not have an index, and the columns have.
Here is my code for sorting
for(int i = 0; i < 9; i++)
{
int tmp = i;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if ((string)row.Cells[2].Value == position[i])
{
Console.WriteLine(position[i] + "Место: " + tmp);
tmp += 9;
}
}
}
copied from the comment of the OP:
con = new SqlConnection();
con.ConnectionString = getConn;
con.Open();
adap = new SqlDataAdapter("SELECT * FROM " + table_name + " WHERE Groupe_year = #year ", con);
string year = comboBox1.Text;
adap.SelectCommand.Parameters.AddWithValue("#year", year);
ds = new System.Data.DataSet();
adap.Fill(ds, "Fighters_Details");
dataGridView1.DataSource = ds.Tables[0];
Assign the Data Source to a Data View instead.
dataGridView1.DataSource = ds.Tables[0].DefaultView;
For Sorting on the Groupe_year column as an example:
((System.Data.DataView)dataGridView1.DataSource).Sort = "Groupe_year";
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);
}
DataTable dt = db.getProductIdFromCategoriesId(categories_id);
foreach (DataRow row in dt.Rows)
{
string products_id = row["products_id"].ToString();
DataTable dt5 = db.FillDataGridfromTree(int.Parse(products_id));
show_products.ItemsSource = dt5.DefaultView;
}
this code show one by one rows in datagridview
but i want to show all the product rows having categories_id in datagridview in one go
this is the function FillDataGridfromTree in databasecore class and its object is db
public DataTable FillDataGridfromTree(int product_Id)
{
string CmdString = string.Empty;
using (SqlCeConnection con = new SqlCeConnection(ConString))
{
CmdString = "SELECT products.product_id as ID, products.remote_products_id as Remote_ID, products_description.products_name as name,products.products_model as model,products.manufacturers_id as manufacturersId,products.products_image as Image,products.products_price as Price,products.products_weight as Weight,products.products_date_added as dateAdded,products.products_last_modified as lastModified,products.products_date_available as dateAvailable,products.products_status as status,products.products_tax_class_id as taxClass FROM products INNER JOIN products_description ON products.product_id=products_description.products_id where products_description.language_id=1 and products_description.products_id=" + product_Id;
SqlCeCommand cmd = new SqlCeCommand(CmdString, con);
SqlCeDataAdapter adapter = new SqlCeDataAdapter(cmd);
DataTable dt = new DataTable("products");
adapter.Fill(dt);
//show_products.ItemsSource = dt.DefaultView;
return dt;
}
}
this is the function through which i get product_id
public DataTable getProductIdFromCategoriesId(int categories_id)
{
string CmdString = string.Empty;
using (SqlCeConnection con = new SqlCeConnection(ConString))
{
CmdString = "SELECT products_id FROM products_to_categories where categories_id=" + categories_id;
SqlCeCommand cmd = new SqlCeCommand(CmdString, con);
DataTable dt = new DataTable();
SqlCeDataAdapter adapter = new SqlCeDataAdapter(cmd);
adapter.Fill(dt);
return dt;
}
}
how to show all the rows instead of one row in datagridview
CHANGED Try changing your foreach loop to:
DataTable dt = db.getProductIdFromCategoriesId(categories_id);
DataTable dt5 = new Datatable();
foreach (DataRow row in dt.Rows)
{
string products_id = row["products_id"].ToString();
dt5.Merge(db.FillDataGridfromTree(int.Parse(products_id)));
}
show_products.ItemsSource = dt5.DefaultView;
You code is always going to display the last row for a category_id, this is because you're assigning an ItemsSource inside a loop. I've changed the top part to do what you looking for:
DataTable dt = db.getProductIdFromCategoriesId(categories_id);
List<DataRow> ProductList = new List<DataRow>();
foreach (DataRow row in dt.Rows)
{
string products_id = row["products_id"].ToString();
DataTable dt5 = db.FillDataGridfromTree(int.Parse(products_id));
if(dt5.Rows.Count > 0)
{
ProductList.AddRange(dt5.Select().ToList());
}
}
show_products.ItemsSource = ProductList.CopyToDataTable().DefaultView;
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