There are 2 scenarios to check when executing this SQL Select Statement below..
retrieveQuery = "SELECT itemName, itemCategory, itemSubCategory, itemPrice, orders, (orders * itemPrice) as TotalPrice FROM Menu WHERE itemCategory = #selectedCat AND itemSubCategory LIKE '%#selectedSubCat%'";
The 2 fields in the parameterized query are selectedCat and selectedSubCat.
First scenario is when the user selects for only Food and as you can see the DropdownList Value selected is ALL which means to say that the query statement's Where Clause should have only selectedCat = 'Food' and selectedSubCat LIKE '%%' (ALL VALUES OF FIELD 'itemSubCategory' FOUND IN THE SQL TABLE)
Second scenario is when the user selects for only Food and selects the DropdownList Value to be Donut which means to say that the query statement's Where Clause should have only selectedCat = 'Food' and selectedSubCat LIKE '%Donut%'
Upon when the user hits the Export to PDF button, these lines of codes are executed..
I have removed the unnecessary codes
String itemCat = HF_TabListType.Value;
String itemSubCatFood = ddlFood.SelectedValue;
String itemSubCatBeverage = ddlBeverages.SelectedValue;
//Retrieving Data to Populate to Report Table
String strConnString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
SqlConnection myConn = new SqlConnection(strConnString);
myConn.Open();
SqlDataAdapter da;
DataSet dsPDF = new DataSet();
String retrieveQuery = String.Empty;
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
{
PdfPTable reportTable = new PdfPTable(1);
if (itemCat == "Food" || itemCat == "Beverages")
{
reportTable = new PdfPTable(foodGV.Columns.Count - 1);
}
else if (itemCat == "Combo")
{
reportTable = new PdfPTable(gvCombo1Total.Columns.Count);
}
reportTable.TotalWidth = 1000f;
reportTable.LockedWidth = true;
reportTable.HorizontalAlignment = Element.ALIGN_CENTER;
reportTable.SpacingAfter = 30f;
//For Food and Beverages
String[] headerForFB = { "No.", "Item Name", "Item Category", "Item Sub Category", "Item Price($)", "Orders", "Total($)" };
//Fod Combo
String[] headerForC = { "No.", "Combo", "Total Amount of Orders", "Total Discounts($)", "Total Sales($)" };
if (itemCat == "Food" || itemCat == "Beverages")
{
for (int i = 0; i < headerForFB.Length; i++)
{
PdfPCell hCell = new PdfPCell(new Phrase(headerForFB[i].ToString(), BoldFontForHeader));
hCell.FixedHeight = 25f;
reportTable.AddCell(hCell);
}
}
else if (itemCat == "Combo")
{
for (int i = 0; i < headerForC.Length; i++)
{
PdfPCell hCell = new PdfPCell(new Phrase(headerForC[i].ToString(), BoldFontForHeader));
reportTable.AddCell(hCell);
}
}
retrieveQuery = "SELECT itemName, itemCategory, itemSubCategory, itemPrice, orders, (orders * itemPrice) as TotalPrice FROM Menu WHERE itemCategory = #selectedCat AND itemSubCategory LIKE '%#selectedSubCat%'";
da = new SqlDataAdapter(retrieveQuery.ToString(), myConn);
da.SelectCommand.Parameters.AddWithValue("#selectedCat", itemCat);
//da.SelectCommand.Parameters.AddWithValue("selectedSubCat", "%" + itemSubCatFood + "%");
if (HF_TabListType.Value.ToString() == "Food")
{
if (ddlFood.SelectedIndex != 0)
{
da.SelectCommand.Parameters.AddWithValue("#selectedSubCat", itemSubCatFood);
}
else
{
da.SelectCommand.Parameters.AddWithValue("#selectedSubCat", "%%");
}
}
else if (HF_TabListType.Value.ToString() == "Beverages")
{
if (ddlBeverages.SelectedIndex != 0)
{
da.SelectCommand.Parameters.AddWithValue("#selectedSubCat", itemSubCatBeverage);
}
else
{
da.SelectCommand.Parameters.AddWithValue("#selectedSubCat", "%%");
}
}
da.Fill(dsPDF);
GridView1.DataSource = dsPDF;
GridView1.DataBind();
PdfPCell cell = null;
PdfPCell cellCount = null;
int j = 0;
//Food/Beverages
if (dsPDF != null || dsPDF.Tables.Count != 0 || dsPDF.Tables[0].Rows.Count != 0)
{
foreach (DataRow r in dsPDF.Tables[0].Rows)
{
cellCount = new PdfPCell(new Phrase((j + 1).ToString(), NormalFont));
cellCount.FixedHeight = 15f;
reportTable.AddCell(cellCount);
for (int i = 0; i < dsPDF.Tables[0].Columns.Count; i++)
{
cell = new PdfPCell(new Phrase(r[i].ToString(), NormalFont));
cell.FixedHeight = 15f;
reportTable.AddCell(cell);
}
j++;
}
}
When the PDF is generated the output of the PDF Table gives this..
Using the Second Scenario stated above,
I have tried to amend the codes and in some instances i got 2 rows with cells that are empty. Meaning the Dataset produced has the rows and columns needed to set the number of rows and columns of the PDF Table respectively.
Could there be an issue with the Retrieve Statement? Or because of adding the da.SelectCommand.Parameters line into if else statements?
I have been trying to work this out for days..
Appreciate any help please, thanks!
Related
I am currently developing a P.O.S software and i started to code the pay form. But i want when the user enters the same product to increment the quantity value and not to display it on another row, i coded it but it displays the updated row and the products on the other rows
public void dodadi() {
MySqlConnection connection = Connection.prevzemiKonekcija();
connection.Open();
try
{
if (string.IsNullOrWhiteSpace(txtBarajKod.Text))
{
return;
}
bool Found = false;
if (dataGridView1.Rows.Count > 0)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (Convert.ToString(row.Cells[0].Value) == txtBarajKod.Text)
{
row.Cells[3].Value = Convert.ToString(1 + Convert.ToInt64(row.Cells[3].Value));
Found = true;
}
}
}
if(!Found)
{
MySqlCommand command;
MySqlDataAdapter adapter;
DataTable tabela;
MySqlDataReader reader;
string query = "SELECT * FROM artikli WHERE barcode like '%" + txtBarajKod.Text + "%'";
command = new MySqlCommand(query, connection);
adapter = new MySqlDataAdapter(command);
tabela = new DataTable();
reader = command.ExecuteReader();
//dataGridView1.DataSource = tabela;
//adapter.Fill(tabela);
if (string.IsNullOrWhiteSpace(txtBarajKod.Text))
{
return;
}
if (reader.Read())
{
txtBarajKod.Text = reader.GetString("barcode");
txtNaziv.Text = reader.GetString("ProductName");
txtCena.Text = reader.GetString("SellPrice");
kolicina = 1;
txtKolicina.Text = kolicina.ToString();
}
else
{
txtBarajKod.Text = "";
txtNaziv.Text = "";
txtCena.Text = "";
txtKolicina.Text = "";
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
connection.Close();
}
}
private void dodadivotabela() {
cena = float.Parse(txtCena.Text);
kolicina = float.Parse(txtKolicina.Text);
konecnacena = cena * kolicina;
string prvred = txtBarajKod.Text;
string vtorred = txtNaziv.Text;
float tretred = cena;
float cetvrtred = kolicina;
float pettired = konecnacena;
dataGridView1.Rows.Add(prvred, vtorred, tretred, cetvrtred, pettired);
}
this is the second method that adds the data to the dgv
If I understood clearly, you don't want the value to show on the 4th cell of the 2nd and 3rd rows when you increment the value of the first row.
If I'm right, you should add a break statement in your foreach loop like so:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (Convert.ToString(row.Cells[0].Value) == txtBarajKod.Text)
{
row.Cells[3].Value = Convert.ToString(1 + Convert.ToInt64(row.Cells[3].Value));
Found = true;
break;
}
}
The break statement will allow you to exit your foreach loop once your condition is met for the first time. If you omit it it will loop over all the other rows and change the value in the 4th cell like in your screenshot because your condition is still met in the other rows.
UPDATED
Ok so you just need to clear your dataGridView1 before you add your updated row to it. I presume your dodadivotabela() method is called when you update the row with the incremented value. Add dataGridView1.Rows.Clear() to your method :
private void dodadivotabela()
{
cena = float.Parse(txtCena.Text);
kolicina = float.Parse(txtKolicina.Text);
konecnacena = cena * kolicina;
string prvred = txtBarajKod.Text;
string vtorred = txtNaziv.Text;
float tretred = cena;
float cetvrtred = kolicina;
float pettired = konecnacena;
dataGridView1.Rows.Clear();
dataGridView1.Rows.Add(prvred, vtorred, tretred, cetvrtred, pettired);
}
I have a DataGridView which is populating data from every disk of my network splitted by partition. I want to insert it into my database, but I don't know how I can validate how many rows I have into the DataGridView.
This is the code I already have:
try
{
con = new OleDbConnection(cs.DBConn);
con.Open();
string queryInsert = #"INSERT INTO tblComputers
(Partition1Disk, Type1Disk, TotalSpace1Disk,
UseSpace1Disk, FreeSpace1Disk, PercentageUse1Disk, Partition2Disk, Type2Disk, TotalSpace2Disk,
UseSpace2Disk, FreeSpace2Disk, PercentageUse2Disk, Partition3Disk, Type3Disk, TotalSpace3Disk,
UseSpace3Disk, FreeSpace3Disk, PercentageUse3Disk,Partition4Disk, Type4Disk, TotalSpace4Disk,
UseSpace4Disk, FreeSpace4Disk, PercentageUse4Disk)
VALUES
(#Partition1Disk, #Type1Disk, #TotalSpace1Disk, #UseSpace1Disk, #FreeSpace1Disk, #PercentageUse1Disk,
#Partition2Disk, #Type2Disk, #TotalSpace2Disk, #UseSpace2Disk, #FreeSpace2Disk, #PercentageUse2Disk,
#Partition3Disk, #Type3Disk, #TotalSpace3Disk, #UseSpace3Disk, #FreeSpace3Disk, #PercentageUse3Disk,
#Partition4Disk, #Type4Disk, #TotalSpace4Disk, #UseSpace4Disk, #FreeSpace4Disk, #PercentageUse4Disk)";
cmd = new OleDbCommand(queryInsert);
cmd.Connection = con;
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
cmd.Parameters["#Partition1Disk"].Value = dataGridView1.Rows[i].Cells[0].Value.ToString();
cmd.Parameters["#Type1Disk"].Value = dataGridView1.Rows[i].Cells[1].Value.ToString();
cmd.Parameters["#TotalSpace1Disk"].Value = dataGridView1.Rows[i].Cells[2].Value.ToString();
cmd.Parameters["#UseSpace1Disk"].Value = dataGridView1.Rows[i].Cells[3].Value.ToString();
cmd.Parameters["#FreeSpace1Disk"].Value = dataGridView1.Rows[i].Cells[4].Value.ToString();
cmd.Parameters["#PercentageUse1Disk"].Value = dataGridView1.Rows[i].Cells[5].Value.ToString();
cmd.Parameters["#Partition2Disk"].Value = dataGridView1.Rows[i].Cells[0].Value.ToString();
cmd.Parameters["#Type2Disk"].Value = dataGridView1.Rows[i].Cells[1].Value.ToString();
cmd.Parameters["#TotalSpace2Disk"].Value = dataGridView1.Rows[i].Cells[2].Value.ToString();
cmd.Parameters["#UseSpace2Disk"].Value = dataGridView1.Rows[i].Cells[3].Value.ToString();
cmd.Parameters["#FreeSpace2Disk"].Value = dataGridView1.Rows[i].Cells[4].Value.ToString();
cmd.Parameters["#PercentageUse2Disk"].Value = dataGridView1.Rows[i].Cells[5].Value.ToString();
cmd.Parameters["#Partition3Disk"].Value = dataGridView1.Rows[i].Cells[0].Value.ToString();
cmd.Parameters["#Type3Disk"].Value = dataGridView1.Rows[i].Cells[1].Value.ToString();
cmd.Parameters["#TotalSpace3Disk"].Value = dataGridView1.Rows[i].Cells[2].Value.ToString();
cmd.Parameters["#UseSpace3Disk"].Value = dataGridView1.Rows[i].Cells[3].Value.ToString();
cmd.Parameters["#FreeSpace3Disk"].Value = dataGridView1.Rows[i].Cells[4].Value.ToString();
cmd.Parameters["#PercentageUse3Disk"].Value = dataGridView1.Rows[i].Cells[5].Value.ToString();
cmd.Parameters["#Partition4Disk"].Value = dataGridView1.Rows[i].Cells[0].Value.ToString();
cmd.Parameters["#Type4Disk"].Value = dataGridView1.Rows[i].Cells[1].Value.ToString();
cmd.Parameters["#TotalSpace4Disk"].Value = dataGridView1.Rows[i].Cells[2].Value.ToString();
cmd.Parameters["#UseSpace4Disk"].Value = dataGridView1.Rows[i].Cells[3].Value.ToString();
cmd.Parameters["#FreeSpace4Disk"].Value = dataGridView1.Rows[i].Cells[4].Value.ToString();
cmd.Parameters["#PercentageUse4Disk"].Value = dataGridView1.Rows[i].Cells[5].Value.ToString();
}
cmd.ExecuteNonQuery();
MessageBox.Show("Successfully saved", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception)
{
throw;
}
The problem is that some of the computers from my Network only have one partition and when it happens, the application will display an error saying that index is out of bounds. There is any validation that I can do to see when there is only one or a maximum of 4 rows into the DataGridView and depending on that insert a null into that column?
I am having three Datagridviews in my windows Form. One brings the data of Villages, on clicking any cell, Second Datagridview is populated with Customer Details. On clicking the customer name, third Datagridview must populate and calculate the balance of customer, whether credit is remaining or advance is deposited, now where I am facing problem is the third datagridview.
It specifically throws exception: Object reference set to null.
private void dataGridView3_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
double loansum1 = 0;
double emisum1 = 0;
double dd1 = 0;
double ei1 = 0;
double finalsum = 0;
foreach (DataGridViewRow drr1 in dataGridView3.Rows)
{
if (drr1.Cells[1].Selected == true)
{
string customerid = drr1.Cells[0].Value.ToString();
label1.Text = customerid;
SqlConnection setcon = new SqlConnection(ConfigurationManager.ConnectionStrings["sismanager"].ConnectionString);
using (SqlCommand getsup = new SqlCommand("SELECT Ciid, Cdate, Cparticulars, Ccr, Cdr FROM Customerbills WHERE Cid = #Cid ORDER BY Cdate DESC", setcon))
{
getsup.Parameters.AddWithValue("#Cid", customerid);
SqlDataAdapter drrr = new SqlDataAdapter(getsup);
try
{
setcon.Open();
DataTable data1 = new DataTable();
drrr.Fill(data1);
if (data1.Rows.Count > 0)
{
dataGridView1.DataSource = data1;
dataGridView1.Columns[0].HeaderText = "Bill Number";
dataGridView1.Columns[1].HeaderText = "Bill Date";
dataGridView1.Columns[2].HeaderText = "Particulars";
dataGridView1.Columns[3].HeaderText = "Credit Balance";
dataGridView1.Columns[4].HeaderText = "Cash Balance";
for (int ij = 0; ij < (dataGridView1.Rows.Count); ++ij)
{
dd1 = Double.Parse(dataGridView1.Rows[ij].Cells[3].Value.ToString());
ei1 = Double.Parse(dataGridView1.Rows[ij].Cells[4].Value.ToString());
loansum1 += dd1;
emisum1 += ei1;
}
label4.Text = (Math.Round(loansum1)).ToString();
label5.Text = (Math.Round(emisum1)).ToString();
finalsum = (emisum1 - loansum1);
if (finalsum >= 0)
{
label6.Text = "Rs. " + finalsum + " (Previous Amount Clear)";
}
else
{
label6.Text = "Rs. " + finalsum + " (Previous Amount Due)";
}
}
}
catch (SqlException exx)
{
}
finally
{
setcon.Close();
}
}
}
}
}
The exception error comes at:
dd1 = Double.Parse(dataGridView1.Rows[ij].Cells[3].Value.ToString());
Error Image below; It shows in call stack that the data is coming.
My Datagridview have one name column. I am trying to add one image column with that datagridview. Once I add the image column it made that name column as null. Please refer the below code:
public void call(string usr)
{
user = usr;
queryString = "select NAME 'Name' from ADK_MY_PRODSYSSECGROUP";
try
{
specdataadapter = new SqlDataAdapter(queryString, con);
specds = new DataSet();
con.Open();
specdataadapter.Fill(specds, "REPORT_Table");
dgvdisp.DataSource = specds;
dgvdisp.DataMember = "REPORT_Table";
dgvdisp.Columns[dgvdisp.ColumnCount - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
con.Close();
if (user == "Secgrp")
{
DataGridViewImageColumn set = new DataGridViewImageColumn();
set.Name = "set";
set.HeaderText = "Settings";
dgvdisp.Columns.Insert(1, set);
for (int rows = 0; rows < dgvdisp.Rows.Count; rows++)
{
MessageBox.Show(dgvdisp.Rows[rows].Cells[0].Value.ToString());
}
}
}
catch (Exception ex)
{
DispMessageBox disp = new DispMessageBox("Fail to retrieve data. Please try again");
disp.ShowDialog();
}
}
public void calling()
{
SqlConnection con = new SqlConnection(connetionString);
for (int rows = 0; rows < dgvdisp.Rows.Count; rows++)
{
SqlCommand command = new SqlCommand("select SETTINGS from ADK_MY_PRODSYSSECGROUP where NAME='" + Convert.ToString(dgvdisp.Rows[rows].Cells[0].Value) + "'", con);
con.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
if (reader.GetInt32(0) == 1)
{
Image image = Properties.Resources.start;
//set.Image = image;
dgvdisp.Rows[rows].Cells["set"].Value = image;
}
if (reader.GetInt32(0) == 0)
{
Image image = Properties.Resources.finish;
//set.Image = image;
dgvdisp.Rows[rows].Cells["set"].Value = image;
}
}
}
reader.Close();
con.Close();
}
}
Here in the call method, dgvdisp datagridview shows the value, But when I tried to get the value from calling method, the datagridview shows null value when I retrieve name field.
Please suggest...
I have a sample database like below, and I want to display only the red colored records in the datagrid. I have a condition for how to make those two cells red.
Sample Database
For example, I want to display records whose is value less than 10 in the book number column.
I used code like below for making them red.
Code
private void UpdateDataGridViewColor()
{
if (calledMethod == 2)
{
for (int i = 0; i < dataGridView1.RowCount; i++)
{
int j = 6;
DataGridViewCellStyle CellStyle = new DataGridViewCellStyle();
CellStyle.ForeColor = Color.Red;
if (isLate(dataGridView1[j, i].Value.ToString()))
{
dataGridView1[j, i].Style = CellStyle;
}
}
}
}
I used code something like the following.
Code
private void issueDetails()
{
calledMethod = 2;
string connectionPath = #"Data Source=Data\libraryData.dat;Version=3;New=False;Compress=True";
using (SQLiteConnection connection = new SQLiteConnection(connectionPath))
{
SQLiteCommand command = connection.CreateCommand();
connection.Open();
string query = "SELECT bookno as 'Book No.',studentId as 'Student ID', title as 'Title', author as 'Author', description as 'Description', issuedDate as 'Issued Date', dueDate as 'Due Date' FROM issuedBooks";
command.CommandText = query;
command.ExecuteNonQuery();
SQLiteDataAdapter da = new SQLiteDataAdapter(command);
DataSet ds = new DataSet();
da.Fill(ds, "issuedBooks");
int c = ds.Tables["issuedBooks"].Rows.Count;
dataGridView1.DataSource = ds.Tables["issuedBooks"];
dataGridView1.Sort(dataGridView1.Columns["Student ID"], ListSortDirection.Ascending);
dataGridView1.ReadOnly = true;
connection.Close();
this.Totals.Text = "Total Issued Books : " + Convert.ToString(c);
}
}
Have you tried,
foreach(DataGridView row in dataGridView1.Rows)
{
//check whether bookno. column in 'row' is less than 10
//and do something
}
I just read your comment that you want query from the database directly before displaying in datagridview, is that what you want?
For SQLite databases, check out this link, you can use standard SQL select statements to get the records based on your condition. Example SELECT * From <table> Where bookNum > 10
That should give you all the records with bookNum greater than 10.
First create your connection,
SQLiteConnection connection = new SQLiteConnection(connectionPath)
Then the dataadapter
SQLiteDataAdapter da = new SQLiteDataAdapter(query, connection);
Do your table mappings if any.
And then call da.Fill(ds, "issuedBooks");
I also noticed you were using As in your sql query for the column names. You can actually use tablemappings to map your database column name to the datatable column name. See this link.
Answer
public void onlyDueReport()
{
List<int> array = new List<int>();
string connectionPath = #"Data Source=Data\libraryData.dat;Version=3;New=False;Compress=True";
using (SQLiteConnection connection = new SQLiteConnection(connectionPath))
{
SQLiteCommand command = connection.CreateCommand();
connection.Open();
string query = "SELECT bookno as 'Book No.',studentId as 'Student ID', title as 'Title', author as 'Author', description as 'Description', issuedDate as 'Issued Date', dueDate as 'Due Date' FROM issuedBooks";
command.CommandText = query;
command.ExecuteNonQuery();
SQLiteDataAdapter da = new SQLiteDataAdapter(command);
DataSet ds = new DataSet();
da.Fill(ds, "issuedBooks");
int c = ds.Tables["issuedBooks"].Rows.Count;
if (c > 0)
{
for (int row = c; row > 0; row--)
{
string date = (string)(ds.Tables["issuedBooks"].Rows[c - row]["Due Date"]);
if (isLate(date))
{
int a = Convert.ToInt32(ds.Tables["issuedBooks"].Rows[c - row]["Book No."]);
array.Add(a);
}
}
}
query = "SELECT bookno as 'Book No.',studentId as 'Student ID', title as 'Title', author as 'Author', description as 'Description', issuedDate as 'Issued Date', dueDate as 'Due Date' FROM issuedBooks WHERE bookno IN (";
int[] cool = array.ToArray();
int cou = 0;
foreach (int a in cool)
{
query += a;
if (cou < cool.Length - 1) { query += ','; }
cou++;
}
query += ")";
Console.WriteLine(query);
command.CommandText = query;
command.ExecuteNonQuery();
DataSet ds1 = new DataSet();
da.Fill(ds1, "issuedBooks");
dataGridView1.DataSource = ds1.Tables["issuedBooks"];
this.Totals.Text = "";
Report_Viewer.StatusPText = " Total Pending Books : " + ds1.Tables["issuedBooks"].Rows.Count;
}
}