SqlConnection con = new SqlConnection(connectionString: ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
String cquery = "SELECT cart.ProductID, ProName, Size, Colour, Price FROM cart, Products WHERE Custid=" + Session[custid] + "AND Products.ProductID = cart.ProductID";
SqlCommand ccmd = new SqlCommand(cquery, con);
DataTable dataTable = new DataTable();
CRepeater.DataSource = ccmd.ExecuteReader();
CRepeater.DataBind();
con.Close();
DataRow[] dr = dataTable.Select("SUM(Price)");
Label3.Text = Convert.ToString(dr[0]); ;
I am using a repeater to display data from database and i cant seem to figure out how to get the sum using repeater
Best approach to calculate the sum of a column in a DataTable use the DataTable.Compute method.
// Declare an object variable.
object sumObject;
sumObject = table.Compute("Sum(Price)", "");
Display the result in your Total Amount Label like so:
Label3.Text = sumObject.ToString();
Update
your missing to load the DataTable,try this
var dataReader = ccmd.ExecuteReader();
var dataTable = new DataTable();
dataTable.Load(dataReader);
CRepeater.DataSource = dataTable;
CRepeater.DataBind();
Related
I have 2 different databases - SQLite and PostgreSQL and i trying to make tiny math on table from this databases.
Both tables contains columns nr_serii and ilosc, SQLite:
And Postgres:
I established a connection to both databases and populate dataset. Maybe i should use different place to store the data?
I need to substraction column ilosc: (sqlite-postgres), but not know how to do that.
For example, for each nr_serii make substraction column ilosc:
nr_serii:222222
ilosc:15-7=8
Finally i want to show output data to datagridview.
When i use messagebox i can see the data in dataset. Here is my part of code:
string cs = #"URI = file:" + Sdatabase;
string csP = conParam;
string sqlP = "select nr_serii, ilosc from stany";
string sql = "select nr_serii, ilosc from przychod";
using var con = new SQLiteConnection(cs);
con.Open();
using var cmd = new SQLiteCommand(sql, con);
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
using var conP = new NpgsqlConnection(csP);
conP.Open();
NpgsqlCommand cmdP = new NpgsqlCommand(sqlP, conP);
NpgsqlDataAdapter DA = new NpgsqlDataAdapter(cmdP);
DataSet dsP = new DataSet();
DA.Fill(dsP);
//----------test-----------
foreach (DataRow row in dsP.Tables[0].Rows)
{
var nr_serii = row["nr_serii"];
var ilosc = row["ilosc"];
MessageBox.Show(nr_serii +","+ ilosc);
}
//--------------------------
For example, you can browse data table from first datasource ds and search for a matching row by value of nr_serii column for each row in the datatable in second datasource dsP, and if found, add a new row with the calculation result to the new third result table.
Then you don't forget to solve the problem of what to do with records that are only in the first ds or only in the second dsP datasource, depending on the value of the nr_serii column.
Program code example:
//prepare result third DataTable
DataTable resultDt = new DataTable();
resultDt.Columns.Add("nr_serii");
resultDt.Columns.Add("ilosc");
//add content to result DataTable
foreach (DataRow row in ds.Tables[0].Rows)
{
var nr_serii = row["nr_serii"];
var ilosc = row["ilosc"];
DataRow drP = null;
foreach (DataRow dataRow in dsP.Tables[0].Rows)
{
if (nr_serii.ToString() == (string)dataRow["nr_serii"])
{
drP = dataRow;
break;
}
}
if (drP != null)
{
var dr = resultDt.NewRow();
dr["nr_serii"] = nr_serii;
dr["ilosc"] = (int)ilosc - (int)drP["ilosc"];
resultDt.Rows.Add(dr);
}
}
GridView1 does not display the data that the SQL statement brings
as :
.....{statements to select attributes and conditions to putting SQL statement}
(Example on SQL :SELECT [patient].name_patient FROM patient, visitFACTABLE, datetime, disease WHERE [patient].Id_patient = [visitFACTABLE].Id AND [visitFACTABLE].Id = [datetime].Id_datetime AND [patient].gender_patient = 'Male')
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
con.Open();
string q_sql = "SELECT " + slct + " FROM patient, visitFACTABLE, datetime, disease WHERE [patient].Id_patient = [visitFACTABLE].Id AND [visitFACTABLE].Id = [datetime].Id_datetime " + w;SqlDataAdapter da = new SqlDataAdapter(q_sql, con);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
trigger debugger break point # GridView1.DataSource = dt;
then hover visualize 🔎 and check did your dt ( data table) contain at least 1 row . if got row , by right your Gridview shall show data
I am working on a Tool Crib system. I need to have a way to fill my dataGridView with past Purchase Orders.PO List on the left side to fill DataGridView. I have used this before to fill gridViews:
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
string orderNumber = lbOrders.SelectedItem.ToString();
string query = "SELECT PartNumber from PurchaseOrders WHERE PONumber LIKE '%" + orderNumber + "%' ";
cmd.CommandText = query;
//OleDbDataReader reader = cmd.ExecuteReader();
cmd.ExecuteNonQuery();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
However I don't know how to fill an existing dataGridView table. As in I don't know how to use the columns that I already have to create Purchase Orders. The da.Fill(dt) just adds all new columns and I end up with and extra column and a lot of empty cells.
Extra Column for PartNumber
I tried to just fill the Item column with this code:
string query = "SELECT PartNumber from PurchaseOrders WHERE PONumber LIKE '%" + orderNumber + "%' ";
cmd.CommandText = query;
OleDbDataReader reader = cmd.ExecuteReader();
//cmd.ExecuteNonQuery(); //not using this code
//OleDbDataAdapter da = new OleDbDataAdapter(cmd); //not using this code
//DataTable dt = new DataTable(); //not using this code
//da.Fill(dt); //not using this code
//dataGridView1.DataSource = dt; //not using this code
List<string> result = new List<string>();
for (int i = 0; i < result.Count - 1; i++)
while (reader.Read())
{
result.Add(reader.GetString(0));
//dataGridView1.Rows[0].Cells["Item"].Value = (reader["PartNumber"]).ToString(); //not using this code
}
for (int i = 0; i < result.Count-1; i++)
{
foreach (var item in result)
{
dataGridView1.Rows[i].Cells["Item"].Value = result[i];
}
}
con.Close();
This code sort of worked for me. However, it kept saying that my index was out of range and would never fill the "Item" column correctly/completely. The other downside to this is that I still needed to bring in the Quantity. I have the grid bring in the other information when there is a change to a cell value. It looks at the database of items to get description and price, so all I need to do is to be able to fill the Item and quantity columns.
I've been at this for a few hours now and I need help.
Summary: I need a way to fill my Item, and Quantity columns with part numbers and quantities stored in an Access DataBase - DB Columns are [PO#, PartNumber, Quantity]
Sorry if this seems like a lot / not enough information. I just need help.
I had done till one last part. Unsure how or what should I do to add into code.
public String DisplaySheetList()
{
DataTable dt = new DataTable();
GridView gv = new GridView();
string sqlStatement1 = "SELECT cs.SheetId AS sheet_id, ltm.LocationType AS location_type, cs.PalletNo AS palletNo, cs.period AS period,cs.syncDate AS syncDate,cs.syncStatus AS syncStatus "
+ "FROM CountSheet cs JOIN LocationTypeMaster ltm ON ltm.LocationId = cs.LocationId " +
" ORDER BY 1 DESC";
SqlCommand sqlCmd1 = new SqlCommand(sqlStatement1, conn);
SqlDataAdapter sqlDa1 = new SqlDataAdapter(sqlCmd1);
sqlDa1.Fill(dt);
//What should i put here
gv.DataBind();
}
I created the table and the view, got the query and fill it in to the table (if I am not wrong). Is it completed or is thing else I should do to ensure it is in the gridview so I can display them out.
Any help will be good, thank you guys
Just Put :
gv.DataSource=dt;
in place of What should i put here to bind datatable data to gridview
So after you fill the result in your data table
Make dt the gridview datasource.
//put it in the gridview datasource.
gv.DataSource = dt;
You can refer to this MSDN page for setting gridview datasource
To complete your code:
public String DisplaySheetList()
{
DataTable dt = new DataTable();
GridView gv = new GridView();
string sqlStatement1 = "SELECT cs.SheetId AS sheet_id, ltm.LocationType AS location_type, cs.PalletNo AS palletNo, cs.period AS period,cs.syncDate AS syncDate,cs.syncStatus AS syncStatus "
+ "FROM CountSheet cs JOIN LocationTypeMaster ltm ON ltm.LocationId = cs.LocationId " +
" ORDER BY 1 DESC";
SqlCommand sqlCmd1 = new SqlCommand(sqlStatement1, conn);
SqlDataAdapter sqlDa1 = new SqlDataAdapter(sqlCmd1);
sqlDa1.Fill(dt);
//put it in the gridview datasource.
gv.DataSource = dt;
gv.DataBind();
}
I am doing a project for my school, where I have to make a C# Windows Forms application that lets me interact with my PostgreSQL database. I have made a listbox, which is supposed to get the names of the tables from my database, and when I select these names, data from that table is show in the datagridview object in the form. The problem is, however, all my listbox values are System.Data.DataRowView, and datagridview only displays values from the first table in the list.
The code:
DataTable tabulusaraksts = new DataTable();
DataTable tabula = new DataTable();
NpgsqlDataAdapter adapter = new NpgsqlDataAdapter();
NpgsqlDataAdapter adapter2 = new NpgsqlDataAdapter();
string tab;
public datubaze()
{
InitializeComponent();
string connectionstring = "Server=localhost;Port=5432;UserId=postgres;Password=students;Database=retrospeles;";
//string connectionstring = String.Format("Server={0};Port={1};" +
// "User Id={2};Password={3};Database={4};",
// serveris.ToString(), port.ToString(), user.ToString(),
// password.ToString(), database.ToString());
NpgsqlConnection ncon = new NpgsqlConnection(connectionstring);
NpgsqlCommand listfill = new NpgsqlCommand("select table_name from INFORMATION_SCHEMA.tables WHERE table_schema = ANY (current_schemas(false));", ncon);
adapter.SelectCommand = listfill;
adapter.Fill(tabulusaraksts);
listBox1.DataSource = tabulusaraksts;
listBox1.DisplayMember = "table_name";
NpgsqlCommand showtable = new NpgsqlCommand("select * from " + tab +";" , ncon);
adapter2.SelectCommand = showtable;
}
public void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
tab = listBox1.GetItemText(listBox1.SelectedItem);
adapter2.Fill(tabula);
dataGridView1.DataSource = tabula;
}
That code should work. I tried it with some test data and ListBox was filled with correct values.
To be sure, try to also set ValueMember like
listBox1.DisplayMember = "table_name";
I think the best approach is to add DataTable rows to your ListBox using loop or Linq list. After filling tabulusaraksts iterate through DataRows and add them as items to ListBox, without setting DataSource Something like this (Linq):
adapter.SelectCommand = listfill;
adapter.Fill(tabulusaraksts);
listBox1.Items.AddRange(tabulusaraksts.AsEnumerable().Select(row => row[0].ToString()).ToArray());
NpgsqlCommand showtable = new NpgsqlCommand("select * from " + tab +";" , ncon);
adapter2.SelectCommand = showtable;
or, using foreach loop
adapter.SelectCommand = listfill;
adapter.Fill(tabulusaraksts);
listBox1.Items.Clear();
foreach (DataRow row in tabulusaraksts.Rows)
{
listBox1.Items.add(tabulusaraksts[0].ToString());
}
NpgsqlCommand showtable = new NpgsqlCommand("select * from " + tab +";" , ncon);
adapter2.SelectCommand = showtable;