I'm creating a restaurant ordering system and cant figure out how to send the completed order back into the access database and across to the kitchen view form. It creates buttons for the user to choose which items they want from the database. I need it to get the highest orderID from the listview where the order is and loop through each item getting the MenuID, time and tableno from the till view. Can answer any questions as may not have explained it clearly. Here is some of the code for the till view form. Any help would be appreciated.
public TillView()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
int i = 0;
clsDBConnector dbConnector = new clsDBConnector();
OleDbDataReader dr;
string sqlStr;
dbConnector.Connect();
sqlStr = "SELECT description, CatID FROM tblCategory";
dr = dbConnector.DoSQL(sqlStr);
while (dr.Read())
{
Button btn = new Button();
btn.BackColor = Color.Lime;
btn.ForeColor = Color.Black;
btn.Font = new Font(btn.Font.Name, 12, FontStyle.Bold);
btn.Size = new Size(110, 100);
btn.Visible = true;
btn.Tag = dr[1].ToString();
btn.Text = dr[0].ToString();
btn.Name = "btn_ " + i;
i++;
btn.Click += Btn_Click;
flpCategory.Controls.Add(btn);
}
dbConnector.Close();
string time = DateTime.Now.ToString("t");
lblTime.Text = ($"{""}" + time);
lblDate.Text = (DateTime.Now.ToString("dd/MM/yyyy"));
lblServer.Text = Login.server;
}
private void Btn_Click(object sender, EventArgs e)
{
flpItem.Controls.Clear();
int i = 0;
int catID = Convert.ToInt32((sender as Button).Tag.ToString());
clsDBConnector dbConnector = new clsDBConnector();
OleDbDataReader dr;
string sqlStr;
dbConnector.Connect();
sqlStr = "SELECT description, CatID, menuID, cost FROM tblMenu where catid = " + catID;
dr = dbConnector.DoSQL(sqlStr);
while (dr.Read())
{
string Description = Convert.ToString((sender as Button).Tag);
int MenuID = Convert.ToInt32((sender as Button).Tag.ToString());
int Cost = Convert.ToInt32((sender as Button).Tag.ToString());
Button bttn = new Button();
bttn.BackColor = Color.LightSkyBlue;
bttn.ForeColor = Color.Black;
bttn.Size = new Size(105, 95);
bttn.Visible = true;
bttn.Tag = dr[2].ToString() + "-" + dr[3].ToString() ;
bttn.Text = dr[0].ToString();
bttn.Name = "bttn_ " + i;
i++;
bttn.Click += bttn_Click;
flpItem.Controls.Add(bttn);
}
dbConnector.Close();
}
private void bttn_Click(object sender, EventArgs e)
{
string theTag = (sender as Button).Tag.ToString() ;
string[] theTagArray = theTag.Split('-');
int MenuID = Convert.ToInt32(theTagArray[0]);
double cost = Convert.ToDouble(theTagArray[1]);
//lstVOrder.Items.Add(MenuID.ToString());
string Description = Convert.ToString(((sender as Button).Text));
lstVOrder.Font = new Font(Font.Name, 12);
lstVOrder.Items.Add(Description.ToString());
lstVOrder.Items[lstVOrder.Items.Count - 1].SubItems.Add(cost.ToString("N2"));
lstVOrder.Items[lstVOrder.Items.Count - 1].SubItems.Add("");
lstVOrder.Items[lstVOrder.Items.Count - 1].SubItems.Add(MenuID.ToString());
}
Related
I have code like this
int cLeft=0;
public System.Windows.Forms.TextBox AddNewTextBox()
{
System.Windows.Forms.TextBox txt = new System.Windows.Forms.TextBox();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = " select * FROM DotMatrix;
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
this.Controls.Add(txt);
txt.Top = (cLeft*25) + 124;
txt.Left = 50;
txt.Height = 20;
txt.Width = 259;
while (reader.Read())
{
txt.Text=reader["Pertanyaan"].ToString();
}
if (txt.Text=="")
{
MessageBox.Show("Pertanyaan Habis , Akan Redirect Ke Hasil");
}
cLeft = cLeft + 1;
return txt;
}
private void textBox1_TextChanged_1(object sender, EventArgs e)
{
AddNewTextBox();
}
My Question is, why textBox just Show 1 Line from Database???
i Want to Show Data[Row] in Pertanyaan Row
Thanks For Answer
This line is looping through every row and constantly overwriting the textbox value:
while (reader.Read())
{
txt.Text=reader["Pertanyaan"].ToString();
}
So the same textbox is being assigned to over and over.
Your textbox creation code wants to be moved to inside the loop, something like this:
while (reader.Read())
{
System.Windows.Forms.TextBox txt = new System.Windows.Forms.TextBox();
txt.Top = (cLeft*25) + 124;
txt.Left = 50;
txt.Height = 20;
txt.Width = 259;
txt.Text=reader["Pertanyaan"].ToString();
if (txt.Text=="")
{
MessageBox.Show("Pertanyaan Habis , Akan Redirect Ke Hasil");
}
this.Controls.Add(txt);
}
I am able to retain the DropDownListCheckbox multi-selected items text inside a label with a button click. I need to search from the database based on the DropDownListCheckBox multi selected items and its related data from a SQL-Server database.
How to achieve the search option using a button click by passing the input from DDL_CB list items or label text to parameterized SQL query?
My requirement: the search feature must display the data in JQgrid based on the text contained in the Label or DDL_CheckBox multi-selected items.
My C# code:
static string value1;
static string value2;
static string value3;
protected void createmaincontrols()
{
//Create a Dynamic Panel
DynamicPanel = new Panel();
DynamicPanel.ID = "DynamicPanel";
DynamicPanel.Width = 1600;
//Create Main Table
var dynamic_filter_table = new WebForms.Table();
dynamic_filter_table.ID = "dynamic_filter_table_id";
TableRow campaign_table_row = new TableRow();
campaign_table_row.ID = "country_table_row";
TableRow campaign_label_row = new TableRow();
campaign_label_row.ID = "country_label_row";
TableCell campaignnamecell = new TableCell();
campaignnamecell.ID = "countrynamecell";
TableCell btncell = new TableCell();
btncell.ID = "btncell";
TableCell labelcell = new TableCell();
labelcell.ID = "labelcell";
//Create Campaigns DDL
DropDownCheckBoxes DDL_checkbox = new DropDownCheckBoxes();
DDL_checkbox.ID = "MainDDL_Countries";
DDL_checkbox.AutoPostBack = true;
DDL_checkbox.ForeColor = System.Drawing.Color.MidnightBlue;
DDL_checkbox.Font.Size = FontUnit.Point(8);
DDL_checkbox.Font.Bold = true;
DDL_checkbox.Font.Name = "Arial";
DDL_checkbox.AddJQueryReference = true;
DDL_checkbox.UseButtons = true;
DDL_checkbox.UseSelectAllNode = true;
DDL_checkbox.Style.SelectBoxWidth = 200;
DDL_checkbox.Style.DropDownBoxBoxWidth = 200;
DDL_checkbox.Style.DropDownBoxBoxHeight = 130;
DDL_checkbox.Texts.SelectBoxCaption = "Select Countries";
DDL_checkbox.Items.Add(new ListItem("SINGAPORE"));
DDL_checkbox.Items.Add(new ListItem("UNITED KINGDOM"));
DDL_checkbox.Items.Add(new ListItem("MALAYSIA"));
DDL_checkbox.Items.Add(new ListItem("INDIA"));
DDL_checkbox.Items.Add(new ListItem("FRANCE"));
DDL_checkbox.Items.Add(new ListItem("GERMANY"));
DDL_checkbox.Items.Add(new ListItem("NORWAY"));
DDL_checkbox.DataTextField = "Country Name";
DDL_checkbox.DataBind();
DDL_checkbox.AutoPostBack = true;
DDL_checkbox.EnableViewState = false;
Button submitbutton = new Button();
submitbutton.ID = "mybutton";
submitbutton.Text = "SubmitSelectedCountries";
submitbutton.Click += new EventHandler(Buttonnew_Click);
submitbutton.Font.Name = "Arial";
submitbutton.Font.Bold = true;
submitbutton.Font.Size = FontUnit.Point(8);
submitbutton.ForeColor = System.Drawing.Color.MidnightBlue;
submitbutton.BackColor = System.Drawing.Color.LightGray;
submitbutton.UseSubmitBehavior = false;
Label lblCampaignName = new Label();
lblCampaignName.ID = "Countries";
lblCampaignName.Font.Bold = true;
lblCampaignName.Font.Size = FontUnit.Point(8);
lblCampaignName.ForeColor = System.Drawing.Color.MidnightBlue;
lblCampaignName.BackColor = System.Drawing.Color.LightGray;
campaignnamecell.Controls.Add(DDL_checkbox);
campaignnamecell.Controls.Add(submitbutton);
campaignnamecell.Controls.Add(lblcountryname);
campaign_table_row.Controls.Add(countrycell);
dynamic_filter_table.Controls.Add(country_table_row);
DynamicPanel.Controls.Add(dynamic_filter_table);
SelectPanel.Controls.Add(DynamicPanel);
}
C# code to retrieve the dropdown checked items in a label using a button click
protected void Buttonnew_Click(object sender, EventArgs e)
{
Table maintable = Select.FindControl("dynamic_filter_table_id") as Table;
DropDownCheckBoxes DDL_checkbox = maintable.FindControl("MainDDL_Contries") as DropDownCheckBoxes;
Label lblcountryname = maintable.FindControl("Country") as Label;
List<String> Country_List = new List<string>();
foreach (System.Web.UI.WebControls.ListItem item in DDL_checkbox.Items)
{
if (item.Selected)
{
Country_List.Add(item.Text);
}
lblcountryname .Text = String.Join(",", Country_List.ToArray());
}
}
How to search the country details based on a parameterized SQL query input from label or dropdowncheckbox selected items?
protected void Button4_Click(object sender, EventArgs e)
{
Table maintable = Select.FindControl("dynamic_filter_table_id") as Table;
int rc = maintable.Rows.Count;
if (rc == 2)
{
//Three country selected in DDL_checkbox
DropDownCheckBoxes d4 = maintable.FindControl("MainDDL_Countries") as DropDownCheckBoxes;
Label lblcountryname = maintable.FindControl("Countries") as Label;
var countryname= test.ToString().Split(new[] { ',', '\n' }).ToArray();
if(countryname.Count() >=1 && countryname.Count() <=3)
{
value1 = countryname.ElementAt(0).ToString();
value2 = countryname.ElementAt(1).ToString();
value3 = countryname.ElementAt(2).ToString();
}
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT C.Country_Name,C.Address FROM COUNTRYTABLE as C WHERE C.Country_Name in(#t4,#t5,#t6)";
cmd.Parameters.Add("#t4", SqlDbType.VarChar).Value = value1;
cmd.Parameters.Add("#t5", SqlDbType.VarChar).Value = value2;
cmd.Parameters.Add("#t6", SqlDbType.VarChar).Value = value3;
con.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter sql = new SqlDataAdapter(cmd);
DataSet data = new DataSet();
sql.Fill(data);
con.Close();
Session["DataforSearch_DDL"] = data.Tables[0];
}
}
This is admittedly a partial answer. It will get you started.
When you submit a form with multi-selected items, the selected items are passed as comma separated values. Something like this:
value1,value2,etc
You want your query to have a where clause like this:
where someTextfield in ('value1','value2','etc')
or without the quotes for numeric fields. However, you wisely said that you wanted to use parameters.
Here endeth the partial answer.
long-long time ago, I used to do it this way:
for (int i = 0; i < param.Length; i++)
if (param[i] != "" && param[i] != null)
s_comm.Parameters.AddWithValue(tParam + i.ToString(), param[i]);
where:
private string tParam = "#Param";
string[] paramName // Name of the parameters
string[] param // Values for those parameters.
and I was building a statement like this:
string where = "";
if (paramName != null)
for (int i = 0; i < paramName.Length; i++)
if (paramName[i] != "" && paramName[i] != null)
if (i == 0)
where = " WHERE " + paramName[i] + " = " + tParam + i.ToString();
else
where += ", " + paramName[i] + " = " + tParam + i.ToString();
else throw new Exception(noColumnName + " at position #:" + i.ToString());
else where = "";
if (table != "") return "SELECT * FROM " + table + where;
I am sure there are more elegant solutions, but this is a start, right?
I would like to minus the data from the database with the value that I give when I run the program. Everything works, but I keep stuck at the newVal. I already did it like this, but the newVal keep appear 0 (because I declared decimal newVal = 0, but on this question, I just used decimal newVal;). Two more problems: if I move the newVal = ... to the top, it is useless, because one of the calculations in the newVal is reading data from the database (since I want database minus with the new value given when i run the program, required dReader = cmd.ExecuteReader();), but if I put the newVal at the bottom after reading data, it is useless as well, because I set the Quantity = ? and the value of ? is newVal.. Well, here is the code:
private void AddObjects(object sender, EventArgs e, Form theForm)
{
button1.Visible = true;
textBoxQuantityContainer = new List<NumericUpDown>();
textBoxCodeContainer = new List<NumericTextBox>();
textBoxDescContainer = new List<TextBox>();
textBoxSubTotalContainer = new List<TextBox>();
textBoxTotalContainer = new List<TextBox>();
textBoxAllTotalContainer = new TextBox();
OleDbDataReader dReader;
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT [Code] FROM [Seranne]", conn);
dReader = cmd.ExecuteReader();
AutoCompleteStringCollection codesCollection = new AutoCompleteStringCollection();
while (dReader.Read())
{
string numString = dReader[0].ToString().PadLeft(4, '0');
codesCollection.Add(numString);
}
dReader.Close();
conn.Close();
if (firstForm.comboBox1.SelectedIndex == 0)
{
label1.Text = "Code:";
label1.Location = new Point(60, 125);
label2.Text = "Welcome to the Selling System.";
label2.Location = new Point(600, 30);
label3.Text = "Quantity:";
label3.Location = new Point(155, 125);
label4.Text = "Description:";
label4.Location = new Point(580, 125);
label5.Text = "Sub Total on Rp:";
label5.Location = new Point(1020, 125);
label6.Text = "Total on Rp:";
label6.Location = new Point(1210, 125);
label7.Text = "Total on Rp:";
label7.Location = new Point(1080, 580);
}
else if (firstForm.comboBox1.SelectedIndex == 1)
{
label1.Text = "Kode:";
label1.Location = new Point(60, 125);
label2.Text = "Selamat datang di Selling System.";
label2.Location = new Point(600, 30);
label3.Text = "Banyaknya:";
label3.Location = new Point(145, 125);
label4.Text = "Keterangan:";
label4.Location = new Point(580, 125);
label5.Text = "Sub Total di Rp:";
label5.Location = new Point(1020, 125);
label6.Text = "Total di Rp:";
label6.Location = new Point(1210, 125);
label7.Text = "Total di Rp:";
label7.Location = new Point(1080, 580);
}
//****TextBox for Code****
for (int y = 0; y <= 16; y++)
{
textBoxCodeContainer.Add(new NumericTextBox());
textBoxCodeContainer[y].Size = new Size(100, 50);
textBoxCodeContainer[y].Location = new Point(25, 150 + (y * 25));
textBoxCodeContainer[y].TextChanged += new System.EventHandler(this.textBox_TextChanged);
textBoxCodeContainer[y].AutoCompleteMode = AutoCompleteMode.Suggest;
textBoxCodeContainer[y].AutoCompleteSource = AutoCompleteSource.CustomSource;
textBoxCodeContainer[y].AutoCompleteCustomSource = codesCollection;
theForm.Controls.Add(textBoxCodeContainer[y]);
}
//****TextBox for Quantity****
for (int y = 0; y <= 16; y++)
{
textBoxQuantityContainer.Add(new NumericUpDown());
textBoxQuantityContainer[y].Size = new Size(100, 50);
textBoxQuantityContainer[y].Location = new Point(125, 150 + (y * 25));
textBoxQuantityContainer[y].TextChanged += new System.EventHandler(this.textBox_TextChanged);
textBoxQuantityContainer[y].Maximum = 1000;
theForm.Controls.Add(textBoxQuantityContainer[y]);
}
//****TextBox for Description****
for (int y = 0; y <= 16; y++)
{
textBoxDescContainer.Add(new TextBox());
textBoxDescContainer[y].Size = new Size(750, 50);
textBoxDescContainer[y].Location = new Point(225, 150 + (y * 25));
theForm.Controls.Add(textBoxDescContainer[y]);
}
//****TextBox for Sub Total****
for (int y = 0; y <= 16; y++)
{
textBoxSubTotalContainer.Add(new TextBox());
textBoxSubTotalContainer[y].Size = new Size(175, 50);
textBoxSubTotalContainer[y].Location = new Point(975, 150 + (y * 25));
theForm.Controls.Add(textBoxSubTotalContainer[y]);
}
//****TextBox for Total****
for (int y = 0; y <= 16; y++)
{
textBoxTotalContainer.Add(new TextBox());
textBoxTotalContainer[y].Size = new Size(175, 50);
textBoxTotalContainer[y].Location = new Point(1150, 150 + (y * 25));
textBoxTotalContainer[y].TextChanged += new System.EventHandler(this.textBox_TextChanged);
theForm.Controls.Add(textBoxTotalContainer[y]);
}
//****TextBox for Total All****
textBoxAllTotalContainer.Size = new Size(175, 50);
textBoxAllTotalContainer.Location = new Point(1150, 575);
textBoxAllTotalContainer.TextChanged += new System.EventHandler(this.textBox_TextChanged);
theForm.Controls.Add(textBoxAllTotalContainer);
}
private void UpdateDatas()
{
int codeValue = 0;
int index = 0;
string query = "SELECT [Quantity], [Description], [Price] FROM [Seranne] WHERE [Code] IN (";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
if (int.TryParse(this.textBoxCodeContainer[0].Text, out codeValue))
{
query = query + codeValue.ToString();
}
for (int i = 1; i < 17; i++)
{
if (int.TryParse(this.textBoxCodeContainer[i].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
}
query = query + ")";
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
while (dReader.Read())
{
if (textBoxCodeContainer[index].TextLength != 0)
{
this.textBoxQuantityContainer[index].Maximum = Convert.ToInt32(dReader["Quantity"].ToString());
this.textBoxDescContainer[index].Text = dReader["Description"].ToString();
this.textBoxSubTotalContainer[index].Text = dReader["Price"].ToString();
}
index += 1;
}
dReader.Close();
conn.Close();
}
private void UpdatePrice()
{
int totalPrice = 0;
int quantity = 0;
int price = 0;
for (int i = 0; i < 17; i++)
{
if (textBoxQuantityContainer[i].Value > 0)
{
quantity = (int)textBoxQuantityContainer[i].Value;
price = Convert.ToInt32(textBoxSubTotalContainer[i].Text);
textBoxTotalContainer[i].Text = (quantity * price).ToString();
}
else
{
textBoxSubTotalContainer[i].Text = "";
textBoxTotalContainer[i].Text = "";
}
}
for (int i = 0; i < 17; i++)
{
if (textBoxTotalContainer[i].TextLength != 0)
{
totalPrice += Convert.ToInt32(textBoxTotalContainer[i].Text);
}
}
textBoxAllTotalContainer.Text = totalPrice.ToString("n2");
}
private void UpdateQuantity()
{
int index = 0;
int codeValue = 0;
decimal newVal;
List<int> integers = new List<int>();
foreach (var tb in textBoxCodeContainer)
{
if (int.TryParse(tb.Text, out codeValue))
{
integers.Add(codeValue);
}
}
string command = "UPDATE [Seranne] SET [Quantity]=? WHERE [Code] IN(" + string.Join(", ", integers) + ")";
OleDbConnection conn = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand(command, conn);
cmd.Parameters.Add("Quantity", System.Data.OleDb.OleDbType.Integer);
cmd.Parameters["Quantity"].Value = this.newVal.ToString();
OleDbDataReader dReader;
conn.Open();
dReader = cmd.ExecuteReader();
while (dReader.Read())
{
if (textBoxQuantityContainer[index].Value != 0)
{
newVal = (Convert.ToInt32(dReader["Quantity"].ToString()) -
textBoxQuantityContainer[index].Value);
int numberOfRows = cmd.ExecuteNonQuery();
}
index += 1;
}
if (newVal == 0)
{
System.Media.SoundPlayer sounds = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Notify.wav");
sounds.Play();
MessageBox.Show("Cannot Update", "Error");
}
else
{
System.Media.SoundPlayer sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Notify.wav");
sound.Play();
MessageBox.Show("Was Updated Successfully", "Success");
}
dReader.Close();
conn.Close();
}
private void textBox_TextChanged(object sender, EventArgs e)
{
UpdateDatas();
UpdatePrice();
}
private void button1_Click(object sender, EventArgs e)
{
UpdateQuantity();
}
Thanks a bunch
Good day, i got several things here:
1) cmd.Parameters["Quantity"].Value = this.newVal.ToString(); conversion to string is not needed here, because the Value is an object. You already defined that it should be handled as integer.
2) Replace the ? within you query to #Quantity, so it will be filled by the query execution.
3) When updating you don't need to execute it as a reader. use the int numberOfRows = cmd.ExecuteNonQuery(); without the loop. It will update all items.
4) You should execute the if (textBoxQuantityContainer[index].Value != 0 && textBoxQuantityContainer[index].Value >=
Convert.ToInt32(dReader["Quantity"].ToString()))
{ when building the integers list, this way you are only updating the right quantities.
If you only want to update certain rows, you'll have to expand your where clause:
cmd.Parameters.Add("MinimumQuantity", System.Data.OleDb.OleDbType.Integer).Value = minimumQuantity;
string command = "UPDATE [Seranne]
SET [Quantity]=#Quantity
WHERE [Code] IN(" + string.Join(", ", integers) + ")
AND [Quantity] > #MinimumQuantity
The higest risk is: You assume that the order and count of the records are the same between your textBoxCodeContainer and the database.
What is the relation between a textbox and a row. How do you know what textbox links to which row?
I could give you a push in the right direction, if you show me some more code (like where/how is textBoxCodeContainer defined)
UPDATE:
I made some code the read and manipulate your database, this is not tested since i don't have any database here.
I would create these classes, 1 is a data class Product and one is a Handler class ProductHandler.
The data class only contains the data (not in presentation format) The data handler knows how to read and write them.
public class Product
{
public int Code { get; set; }
public string Description { get; set; }
public int Quantity { get; set; }
}
public class ProductHandler
{
public ProductHandler(string connectionString)
{
ConnectionString = connectionString;
}
public bool AddProduct(Product product)
{
return AddProducts(new Product[] { product }) > 0;
}
public int AddProducts(IEnumerable<Product> products)
{
int rowsInserted = 0;
using (OleDbConnection conn = new OleDbConnection(ConnectionString))
{
conn.Open();
string query = "INSERT INTO [Seranne] (Code, Description, Quantity) VALUES(#Code, #Description, #Quantity)";
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.Add("Code", OleDbType.Integer);
cmd.Parameters.Add("Description", OleDbType.VarChar);
cmd.Parameters.Add("Quantity", OleDbType.Integer);
foreach (var product in products)
{
cmd.Parameters["Code"].Value = product.Code;
cmd.Parameters["Description"].Value = product.Description;
cmd.Parameters["Quantity"].Value = product.Quantity;
rowsInserted += cmd.ExecuteNonQuery();
}
}
}
return rowsInserted;
}
public bool UpdateProduct(Product product)
{
return UpdateProducts(new Product[] { product }) > 0;
}
public int UpdateProducts(IEnumerable<Product> products)
{
int rowsUpdated = 0;
using (OleDbConnection conn = new OleDbConnection(ConnectionString))
{
conn.Open();
string query = "UPDATE [Seranne] SET Description = #Description, Quantity = #Quantity WHERE [Code] == #Code)";
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.Add("Code", OleDbType.Integer);
cmd.Parameters.Add("Description", OleDbType.VarChar);
cmd.Parameters.Add("Quantity", OleDbType.Integer);
foreach (var product in products)
{
cmd.Parameters["Code"].Value = product.Code;
cmd.Parameters["Description"].Value = product.Description;
cmd.Parameters["Quantity"].Value = product.Quantity;
rowsUpdated += cmd.ExecuteNonQuery();
}
}
}
return rowsUpdated;
}
public bool DeleteProduct(Product product)
{
return DeleteProducts(new int[] { productCode }) > 0;
}
public int DeleteProducts(IEnumerable<Product> products)
{
using (OleDbConnection conn = new OleDbConnection(ConnectionString))
{
conn.Open();
string productCodeStr = string.Join(", ", products.Select(item => item.Code));
string query = string.Format("DELETE FROM [Seranne] WHERE [Code] in ({0})", productCodeStr);
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
int rowsDeleted = cmd.ExecuteNonQuery();
return rowsDeleted;
}
}
}
public IEnumerable<Product> ReadAllProducts()
{
List<Product> result = new List<Product>();
using (OleDbConnection conn = new OleDbConnection(ConnectionString))
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand("SELECT [Code], [Description], [Quantity] FROM [Seranne]", conn))
using (OleDbDataReader dReader = cmd.ExecuteReader())
while (dReader.Read())
{
Product product = new Product();
product.Code = Convert.ToInt32(dReader["Code"]);
product.Description = Convert.ToString(dReader["Description"]);
product.Quantity = Convert.ToInt32(dReader["Quantity"]);
result.Add(product);
}
}
return result;
}
public string ConnectionString { get; private set; }
}
Some example code:
ProductHandler _productHandler = new ProductHandler("connectionstring here or from config");
public void Example()
{
_productList.Clear();
_productList.AddRange(_productHandler.ReadAllProducts());
// displaying
foreach (var product in _productList)
Trace.WriteLine(string.Format("code: {0}, description: {1}, quantity: {2}", product.Code, product.Description, product.Quantity);
// updating
var selectedProduct = _productList.FirstOrDefault(item => item.Code == 15);
if(selectedProduct!= null)
{
selectedProduct.Quantity = 50;
_productHandler.UpdateProduct(selectedProduct);
}
// deleting
_productHandler.DeleteProducts(_productList.Where(item => item.Quantity < 5));
}
How to link the textboxes to the right product:
I would create a UserControl that contains a Product property and the TextBoxes and handles when textbox_changed events occurs. Those event handlers manipulate the Product instance.
You only generate 16 controls and bind a product to it. When you press a button, you only need to save the changed products.
I'm creating a device application in VS 2005.
I created a List called "info" and want to populate labels on my form with the values from the List. This is my code:
public List<String> info = new List<String>();
int i = 0;
private void populateinfo()
{
conn.Open();
string query;
query = "select distinct dp.current_location_code,dci.dest_location_code,dps.order_no,dps.company_id_no,dps.no_of_full_cartons,dps.dc_grv_id_no,s.sku_code from dc_pallet_stock dps, dc_pallet dp,sku s , purch_order_carton_sku pocs , dc_crane_instruc dci where dp.pallet_id_no = dps.pallet_id_no and dps.order_no = pocs.order_no and dps.company_id_no = pocs.company_id_no and dps.carton_code = pocs.carton_code and s.sku_id_no = pocs.sku_id_no and s.company_id_no = dps.company_id_no and dp.pallet_id_no = '" + palletId + "' and dci.pallet_id_no(+) = dps.pallet_id_no";
OracleCommand cmd = new OracleCommand(query, conn);
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
this.info.Add(dr["order_no"].ToString());
}
dr.Close();
conn.Close();
}
private void frmInfo_Load(object sender, EventArgs e)
{
populateinfo();
lbl3.Text = this.info[++i];
{
Im getting error at lbl3.Text = this.info[++i];
Specified argument was out of the range of valid values. Parameter name: index.
This is how I'm testing it at the moment, but at the end I want all the columns in my query to be shown in separate labels, how would I do this. Or is there a better way of doing it? Gridview is no option.
Thanks in advance.
What I probably would do would to create either an Array of your labels or a List of your labels iterate through it. Here is an example dynamically creating your labels and adding them to your form.
public List<String> info = new List<String>();
public List<Label> labels = new List<Label>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
populateinfo();
for (int i = 0; i < info.Count; i++)
{
labels.Add ( new Label(){Name="lbl"+i+1, Text=info[i],
Font = new Font("Arial",8),
ForeColor= Color.Blue});
}
placelabels();
}
private void placelabels()
{
int topvalue = 0;
foreach (Label item in labels)
{
item.Left = 0;
item.Top = topvalue;
this.Controls.Add(item);
topvalue += 20;
}
}
And a method adding your existing labels to a List
public List<String> info = new List<String>();
public List<Label> labels = new List<Label>();
public Form1()
{
InitializeComponent();
labels.Add(label1);
labels.Add(label2);
labels.Add(label3);
labels.Add(label4);
labels.Add(label5);
}
private void Form1_Load(object sender, EventArgs e)
{
populateinfo();
if (labels.Count > info.Count)
{
for (int i = 0; i < info.Count; i++)
{
labels[i].Text = info[i];
}
}
else
{
for (int i = 0; i < labels.Count; i++)
{
labels[i].Text = info[i];
}
}
}
try to use like this.
...
while (dr.Read())
{
lbl3.Text += dr["order_no"].ToString() + "\n";
}
...
palletId in my select query was incorrect. Please see constructor:
public List<String> info = new List<String>();
int i = 0;
public frmInfo(string palletId)
{
InitializeComponent();
this.palletId = palletId;
}
private void populateinfo()
{
conn.Open();
string query;
query = "select distinct dp.current_location_code,dci.dest_location_code,dps.order_no,dps.company_id_no,dps.no_of_full_cartons,dps.dc_grv_id_no,s.sku_code from dc_pallet_stock dps, dc_pallet dp,sku s , purch_order_carton_sku pocs , dc_crane_instruc dci where dp.pallet_id_no = dps.pallet_id_no and dps.order_no = pocs.order_no and dps.company_id_no = pocs.company_id_no and dps.carton_code = pocs.carton_code and s.sku_id_no = pocs.sku_id_no and s.company_id_no = dps.company_id_no and dp.pallet_id_no = '" + palletId + "' and dci.pallet_id_no(+) = dps.pallet_id_no";
OracleCommand cmd = new OracleCommand(query, conn);
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
this.info.Add(dr["order_no"].ToString());
}
dr.Close();
conn.Close();
}
private void frmInfo_Load(object sender, EventArgs e)
{
populateinfo();
lbl3.Text = this.info[++i];
{
I am having an issue with some of my dynamic checkboxes on a project I am working on.
I have a tables, and in one cell per row, I have a checkbox. This checkbox is checked to "flag" that record. The records in the table are populated on a button click, after the user has set a series of filters. Therefore, the table contents completely change on each postback.
I use a list to preserve which records were already flagged, so that if a record appears that was previously checked, it will be checked on that retrieval too.
I am performing this check against my list in my page_load function and I can see through debugging that it is getting set correctly. However, when the page is done loading, the checked status is often wrong.
Do I need to move my checkbox state verification step to another part of the page lifecycle?
Any tips would be great. I found some questions on asp.net issues with checkboxes, but I they did not seem to be relevant to my issue.
Here is the code, feel free to critique any/all of it :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ScienceAssessmentToolASP
{
public partial class createnewtest : System.Web.UI.Page
{
private int n;
private SqlConnection conn = null;
private List<int> flaggedQuestions = new List<int>();
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
var temp = (List<int>)Session["flaggedQuestions"];
if (temp != null)
flaggedQuestions = temp; ;//retrieve flags from session
try
{
GetConn();
ExecuteRetrieval();
n = 1;
}
catch (Exception ex) { n = 0; Response.Write("for debugging: " + ex); }
finally { if (conn != null) conn.Close(); }
if (n < 0)
//Label1.Text = "Connection Successful";
Label3.Text = "Failed to Connect to Database, please contact the administrator.";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
}
private void GetConn()
{
string connString = #"laalalala";
conn = new SqlConnection(connString);
conn.Open();
}
private void ExecuteRetrieval()
{
SqlDataReader reader = null;
string query;
if (!IsPostBack)
{
query = "select * from [ScienceQA]";
flaggedQuestions = (List<int>)Session["flaggedQuestions"];//retrieve flags from session
}
else query = "select * from [ScienceQA] where [GradeLevel] = " + DropDownList1.Text +
" and [Topic] = '" + DropDownList2.Text + "';";
SqlCommand cmd = new SqlCommand(query, conn);
reader = cmd.ExecuteReader();
TableHeaderRow headerRow = new TableHeaderRow();
TableHeaderCell idH = new TableHeaderCell();
TableHeaderCell questionH = new TableHeaderCell();
TableHeaderCell answerH = new TableHeaderCell();
TableHeaderCell flagH = new TableHeaderCell();
idH.Text = "ID";
questionH.Text = "Question";
answerH.Text = "Answer";
flagH.Text = "Flag";
headerRow.Cells.Add(idH);
headerRow.Cells.Add(questionH);
headerRow.Cells.Add(answerH);
headerRow.Cells.Add(flagH);
resultTable.Controls.Add(headerRow);
while (reader.Read())
{
TableRow row = new TableRow();
TableCell idCell = new TableCell();
TableCell qCell = new TableCell();
TableCell aCell = new TableCell();
TableCell flag = new TableCell();
idCell.Text = reader[0].ToString();
qCell.Text = reader[1].ToString();
aCell.Text = reader[2].ToString();
CheckBox flagBox = new CheckBox();
int id = Convert.ToInt32(idCell.Text);
flagBox.AutoPostBack = true;
flagBox.CheckedChanged += new System.EventHandler(flagButton_Click);
flagBox.EnableViewState = true;
flagBox.ViewStateMode = ViewStateMode.Enabled;
if (flaggedQuestions.Contains(id) && flagBox.ID == "flag" + id)
flagBox.Checked = true;
else flagBox.Checked = false;
flagBox.Text = id.ToString();
flag.Controls.Add(flagBox);
row.Cells.Add(idCell);
row.Cells.Add(qCell);
row.Cells.Add(aCell);
row.Cells.Add(flag);
resultTable.Controls.Add(row);
}
Label4.Visible = true;
flagCounter.Visible = true;
resultTable.Visible = true;
}
protected void flagButton_Click(object sender, EventArgs e)
{
CheckBox lb = (CheckBox)sender;
int questionID = Convert.ToInt32(lb.ID.Substring(4));
if (lb.Checked && !flaggedQuestions.Contains(questionID))
{
//lb.Checked = false;
flaggedQuestions.Add(questionID);
flagCounter.Text = Convert.ToString(flaggedQuestions.Count);
}
else
{
//lb.Checked = true;
flaggedQuestions.Remove(questionID);
flagCounter.Text = Convert.ToString(flaggedQuestions.Count);
}
Session["flaggedQuestions"] = flaggedQuestions;//store questions to session
}
protected void createTestButton_Click(object sender, EventArgs e)
{
//create a test
bool sendQuery = true;
string author = Session["user"].ToString();
string accessLevel = accessDropdown.Text;
int gradeLevel = Convert.ToInt32(DropDownList1.Text);
int questionCount = flaggedQuestions.Count();
string testType = testTypeDropDown.Text;
string description = descriptionBox.Text;
string questionString = "";
for (int i = 0; i < flaggedQuestions.Count(); i++)
questionString += flaggedQuestions[i] + ",";
string query = #"Insert into Tests Values ('" + author + "','" + questionString
+ "','" + accessLevel + "','" + gradeLevel + "','" + questionCount + "','"
+ testType + "','" + description +"');";
//check parameters
if (accessLevel == "")
{
errorLabel.Text = "Please choose an access level.";
sendQuery = false;
}
if (questionCount == 0)
{
errorLabel.Text = "Please flag a set of questions before creating a test.";
sendQuery = false;
}
if (testType == "")
{
errorLabel.Text = "Please choose a test type";
sendQuery = false;
}
if (description == "")
{
errorLabel.Text = "Please describe your test";
sendQuery = false;
}
if (sendQuery)
{
try
{
GetConn();
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Prepare();
int n;
n = cmd.ExecuteNonQuery();
}
catch (Exception e2) { n = 0; }
if (n == 1)
errorLabel.Text = "Test Created Successfully";
else errorLabel.Text = "Test Creation Failed, please check your parameters.";
}
}
}
}
Here was the solution that worked for me, moving the checkbox state check to the onprerender function.
protected override void OnPreRender(EventArgs e)
{
foreach (TableRow row in resultTable.Rows)
{
var cell = row.Cells[3];
foreach (Control control in cell.Controls)
{
var flagBox = control as CheckBox;
if (flagBox != null)
{
int id = Convert.ToInt32(flagBox.ID.Substring(4));
if (flaggedQuestions.Contains(id) && flagBox.ID == "flag" + id)
flagBox.Checked = true;
else flagBox.Checked = false;
}
}
}
}
You probably need to update the checked state of the checkboxes in PreRender as that occurs after the button click event has fired.