Display the data on GridView by built SQL from multi tables - c#

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

Related

C# - How to fill an existing DataGridView with data from an Access Database

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.

How to calculate sum if using repeater

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();

Web Forms - Multiple Select Query Results in a GridView?

I'm an extreme newbie. Please bear with me.
I'm trying to populate a GridView with multiple resultsets. I'm using a DataSet with mulitple DataTables. This code has only 2 DataTables, but I will need to use more than 5 or maybe 10.
ASP.NET 4.5.1 Web Forms w/ MSSQL
Method
public DataSet GvTest()
{
using (SqlConnection conn = new SqlConnection(strConn))
{
conn.Open();
SqlCommand cmd = new SqlCommand
(
"SELECT s.StudioName, i.Studio, i.UPC, i.Title, i.Price, i.Availability, i.Location, i.Qty " +
"FROM tbl_Item i JOIN tbl_studio s ON i.Studio = s.StudioID WHERE i.Availability = 'T' and i.Qty > 0 ORDER BY i.Location; " +
"SELECT d.UPC, SUM(d.Qty) FROM tbl_PROrderDetail d JOIN tbl_PROrder p ON d.OrderNo = p.OrderNo " +
"WHERE p.Status = 'P' and p.Type = 'P' GROUP BY d.UPC;"
, conn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
conn.Close();
DataTable dtTest = new DataTable();
ds.Tables[0].Merge(ds.Tables[1]);
dtTest = ds.Tables[0];
return ds;
}
}
Code behind
protected void Page_Load(object sender, EventArgs e)
{
DataModel dm = new DataModel();
DataSet ds = dm.GvTest();
GridBind(ds);
}
private void GridBind(DataSet ds)
{
gvItemList.DataSource = ds.Tables[0];
gvItemList.DataBind();
}
This code just generates the first SELECT result and then the second SELECT result right after.
What I need to do is add a new column to Tables[0], and the result set of Tables[1] fills the new column.
Row count of Tables[0] = 94
Row count of Tables[1] = 6800
I need 94 rows on my GridView, not 6800. UPC is the connection.
Thanks in advance!

SQL query to datatable

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();
}

Data grid view not showing data from mysql table

Im trying to get data in data grid view . this code works fine if i use this query :- "Select * from employee.transaction"
But when im trying to put the conditions it does not give any output (just shows a blank table)
My table has month,year column of type Int.Im using mysql server 5.6.25
I cant find the problem with my code.Please help.Thx in advance.
private void load_data_Click(object sender, EventArgs e)
{
string constring = "datasource = localhost;port = 3306;username = ****;password = ****";
MySqlConnection conDataBase = new MySqlConnection(constring);
var cmdDataBase = conDataBase.CreateCommand();
cmdDataBase.CommandText = #"select * from employee.transaction where department = #department AND month = #month AND year = #year";
cmdDataBase.Parameters.AddWithValue("#department", this.department.Text);
cmdDataBase.Parameters.AddWithValue("#month", this.dateTimePicker1.Value.Month);
cmdDataBase.Parameters.AddWithValue("#year", this.dateTimePicker1.Value.Year);
try
{
// here im trying to show table in datagrid view
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmdDataBase;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
dataGridView1.DataSource = bSource;
sda.Update(dbdataset);
//here im trying to make a excel file which would contain what is currently being displayed in the datagrid view
DataSet ds = new DataSet("New_DataSet");
DataTable dt = new DataTable("New_DataTable");
dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
ds.Tables.Add(dbdataset);
ExcelLibrary.DataSetHelper.CreateWorkbook("MyExcelFile.xls", ds);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The problem could be, as mentioned by #Bjorn-Roger in the comments, that both 'month' and 'year' are keywords in SQL.
I would suggest you try :
select * from employee.transaction where department = #department AND [month] = #month AND [year] = #year
P.S: Notice the use of [] with the fields 'month' and 'year'.
Edit 1
Also, you might want to check if the date format of the input fields 'month' and 'year' is same as that of database table fields.

Categories

Resources