I have a button click event in one user control that will deduct 1 from the stock of ingredients in tbl_ingredients whenever it matches the ingredient found in string array ings.
private void btn_confirm_Click(object sender, EventArgs e, string[] ings)
{
foreach (string s in ings)
{
string qry = "UPDATE tbl_ingredients SET inv_stock = inv_stock -1 WHERE inv_name = '" + s + "'";
SQLiteCommand myCommand = new SQLiteCommand(qry, myConnection);
myCommand.ExecuteNonQuery();
}
}
and a dynamically created tablelayoutpanel (to display all the ingredients and their respective total stock) in another user control
myConnection = new SQLiteConnection("Data Source=database.sqlite3");
string qry = "SELECT * FROM tbl_ingredients ORDER BY inv_name";
string qry2 = "SELECT COUNT(*) FROM tbl_ingredients";
SQLiteCommand myCommand = new SQLiteCommand(qry, myConnection);
SQLiteCommand myCommand2 = new SQLiteCommand(qry2, myConnection);
openConnection();
int row = Convert.ToInt32(myCommand2.ExecuteScalar());
SQLiteDataReader result = myCommand.ExecuteReader();
string[] itemname = new string[row];
string[] totalstock = new string[row];
int cnt = 0;
if (result.HasRows)
{
while (result.Read())
{
itemname[cnt] = result["inv_name"].ToString();
totalstock[cnt] = result["inv_stock"].ToString();
cnt++;
}
}
//tlb_inventory is the name of the tablelayoutpanel in windows form
tbl_inventory.ColumnCount = 2;
tbl_inventory.RowCount = row;
tbl_inventory.Controls.Add(new Label() { Text = "Item" }, 0, 0);
tbl_inventory.Controls.Add(new Label() { Text = "Total Stock" }, 1, 0);
for (int i = 1, j = 0; i < row + 1; i++, j++)
{
tbl_inventory.Controls.Add(new Label() { Text = itemname[j], AutoSize = true }, 0, i);
tbl_inventory.Controls.Add(new Label() { Text = totalstock[j], AutoSize = true }, 1, i);
}
closeConnection();
Whenever I click on the button, it should update the contents of the table in real-time. The issue is that I have to re-run the program in order for it to display the updated contents of the table. Is there a function or something that will make the user control and its contents refresh after button click?
First you need to set the name property to the labels control
tbl_inventory.Controls.Add(new Label() { Name = "Total_"+ itemname[j], Text = totalstock[j], AutoSize = true }, 1, i);
and then at the button_click event inside foreach loop add:
Label c = (tbl_inventory.Controls.Find("Total_" + s, true).First() as Label);
var total = Convert.ToInt32(c.Text);
c.Text = (total++).ToString();
Related
I need to create a table which will always display the last ten records of CTLog on a TableLayoutPanel. So whenever the user adds a new CTLog in Access database by clicking on a button, the table will dynamically update and display the last ten CTLogs. When adding the first ten records, I managed to get them on table but those records added after the 10th row cannot be displayed. I used the method of replacing the old labels on TableLayoutPanel by erasing the old one and then add the new ones.
private void RecentCT()
{
int j = 0;
for (j = 0; j < 10; j++)
{
tableLayoutPanel1.Controls.Remove(tableLayoutPanel1.GetControlFromPosition(j + 1, 0));
tableLayoutPanel1.Controls.Remove(tableLayoutPanel1.GetControlFromPosition(j + 1, 1));
}
string sql = "select Top 10 * from timer where ModelLog = #m and ShiftLog = #sl and ShiftStart = #ss and ShiftEnd = #se";
using (OleDbCommand cmd = new OleDbCommand(sql, connection))
{
//all cmd.Parameters.Add actions at here
try
{
connection.Open();
//List<string> results = new List<string>(); I used list and foreach previously
Label[] labels = new Label[10];
Label[] labels2 = new Label[10];
int i = 0;
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
labels[i] = new Label
{
Text = reader["CTLog"].ToString(),
Anchor = AnchorStyles.None,
Font = new Font("Microsoft Sans Serif", 10, FontStyle.Regular),
TextAlign = ContentAlignment.MiddleCenter
};
labels2[i] = new Label
{
Text = "Unit " + reader["UnitID"].ToString(),
Anchor = AnchorStyles.None,
Font = new Font("Microsoft Sans Serif", 10, FontStyle.Regular),
TextAlign = ContentAlignment.MiddleCenter
};
tableLayoutPanel1.Controls.Add(labels2[i], i + 1, 0);
tableLayoutPanel1.Controls.Add(labels[i], i + 1, 1);
i++;
}
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Recent cycle time records cannot be retrieved. Error: " + ex.Message);
connection.Close();
}
}
}
Did I miss out something or something is wrong in my method?
Problem is with the sql query I used.
This is the correct sql query:
string sql = "select top 10 * from timer where ModelLog = #m and ShiftLog = #sl and ShiftStart = #ss and ShiftEnd = #se ORDER BY ID DESC";
To get the latest 10 rows of records, I must combine top and order by in desc form in a query. Because using only top keyword will only get the first 10 row, not the last ten rows.
I have a list of combobox items generated from a database
private void Outlet1_DropDown(object sender, EventArgs e)
{
SqlDataReader dr7;
SqlConnection Conadd1 = new SqlConnection("Data Source=PC-PC\\MIKO;Initial Catalog=Caproj;Integrated Security=True;");
Conadd1.Open();
SqlCommand cmd6 = new SqlCommand("select Address from [Outlet Table] where ClientID='" + clientid + "'", Conadd1);
cmd6.Connection = Conadd1;
dr7 = cmd6.ExecuteReader();
DataTable dt8 = new DataTable();
dt8.Columns.Add("Address", typeof(string));
dt8.Load(dr7);
Outlet1.DisplayMember = "Address";
Outlet1.DataSource = dt8;
Conadd1.Close();
colorcombo();
}
A user can select a certain item in the said combobox and it will be inserted in a listbox. Once the listbox contains the said address, I want the item color to be made red, so it will remind the user that it's already selected
my attempt to code, I have no idea on how to use the drawmode event:
private void colorcombo()
{
if (outletlist.Items.Contains(Outlet1.Items.ToString()))
{
Con.Open();
for (int i = Outlet.Items.Count - 1; i >= 0; --i)
{
using (var cmd = new SqlCommand("UPDATE [Outlet Table] SET [Address] = Address WHERE [Address] = #address", Con))
{
cmd.Parameters.AddWithValue("#address", (Outlet.Items[i].Text));
if (cmd.ExecuteNonQuery() > 0)
{
//Outlet.Items[i].BackColor = Color.Red;
}
else
{
//Outlet.Items[i].BackColor = Color.Black;
}
}
}
}
}
Some details:
Outlet1 = name of my combobox
outletlist = name of my listbox
I have a table which has 3 columns and each column has 5 rows.Now I wanna get those total numbers of rows in c# to create that number of labels dynamically as well as get the rows value for labels name.Similarly, creates same numbers of the textbox as well.Then in the runtime, i wanted to submit the value to the database by this textbox.
Note: here, if I increase the rows of the table,then the label and textbox will be increased automatically/dynamically as well as submitting value through textbox will perfectly work.
But , all I have done is only getting count value 1 , I just tried a lot but not getting the total count value which is actually 5 .
here, is my code...
private void Form1_Load(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
//string cmText = "select ProductId,ProductName,UnitPrice from tblProductInventory";
string cmText = "Select Count(ProductId) from tblProductInventory";
SqlCommand cmd = new SqlCommand(cmText, con);
con.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
int count = rdr.FieldCount;
while (rdr.Read())
{
//System.Windows.Forms.Label MyLabel;
{
int y = 50;
Label myLabel = new Label();
for (int i = 0; i < count; i++)
{
myLabel = new Label();
myLabel.Location = new Point(88, y);
myLabel.Name = "txtVWReadings" + i.ToString();
myLabel.Size = new Size(173, 20);
myLabel.TabIndex = i;
myLabel.Visible = true;
myLabel.Text = rdr[i].ToString();
y += 25;
this.Controls.Add(myLabel);
}
}
}
}
}
}
And I got this output.
The issue seems that you are using query as count but you want the values of the field. So you can probably change it to
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
//string cmText = "select ProductId,ProductName,UnitPrice from tblProductInventory";
string cmText = "Select Count(ProductId) from tblProductInventory";
SqlCommand cmd = new SqlCommand(cmText, con);
con.Open();
Int32 count = (Int32) cmd.ExecuteScalar();
int i = 1;
cmText = "select ProductId,ProductName,UnitPrice from tblProductInventory";
SqlCommand cmd1 = new SqlCommand(cmText, con);
using (SqlDataReader rdr = cmd1.ExecuteReader())
{
int y = 50;
Label myLabel = new Label();
TextBox MyTxt = New TextBox();
while (rdr.Read())
{
myLabel = new Label();
myLabel.Location = new Point(88, y);
myLabel.Name = "txtVWReadings" + i.ToString();
myLabel.Size = new Size(173, 20);
myLabel.TabIndex = i;
myLabel.Visible = true;
myLabel.Text = rdr[1].ToString(); //Since you want ProductName here
y += 25;
this.Controls.Add(myLabel);
//Same Way Just include the TextBox
//After all Position of TextBox
MyTxt.Text = rdr[2].ToString(); // I believe you need UnitPrice of the ProductName
i++;
}
}
}
Count(columname) :
Will count only the NOT NULL values in that column.
Count(*) :
Will count the number of records in that table.
So I guess you have some NULL values in ProductId column. Change it to
Select Count(*) from tblProductInventory
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 created labels and textboxes dynamically . everything goes fine,but the second label doesn't want to appear at all. where i am wrong? this is my code in C#:
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
OracleDataReader reader;
int x = 434;
int y = 84;
int i = 0;
try
{
conn.Open();
foreach (var itemChecked in checkedListBox1.CheckedItems)
{
Label NewLabel = new Label();
NewLabel.Location = new Point(x + 100, y);
NewLabel.Name = "Label" + i.ToString();
Controls.Add(NewLabel);
TextBox tb = new TextBox();
tb.Location = new Point(x, y);
tb.Name = "txtBox" + i.ToString();
Controls.Add(tb);
y += 30;
OracleCommand cmd = new OracleCommand("SELECT distinct data_type from all_arguments where owner='HR' and argument_name='" + itemChecked.ToString() + "'", conn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
label[0].Text = reader["data_type"].ToString();
}
i++;
}
}
finally
{
if (conn != null)
conn.Close();
}
}
private void Procedure()
{
string proc = "";
try
{
conn.Open();
if (this.listView1.SelectedItems.Count > 0)
proc = listView1.SelectedItems[0].Text;
OracleCommand cmd = new OracleCommand("" + proc + "", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 600;
int i = 0;
foreach (var itemChecked1 in checkedListBox1.Items)
{
Control[] txt = Controls.Find("txtBox" + i.ToString(), false);
Control[] label = Controls.Find("Label" + i.ToString(), false);
cmd.Parameters.Add(new OracleParameter("select distinct data_type from all_arguments where owner='HR' and argument_name=toupper("+itemChecked1.ToString()+")",conn));
cmd.Parameters[":"+itemChecked1.ToString()+""].Value=label[0].Text;
cmd.Parameters.Add(new OracleParameter(":" + itemChecked1.ToString() + "", OracleDbType.Varchar2));
cmd.Parameters[":" + itemChecked1.ToString() + ""].Value = txt[0].Text;
i++;
I think the second Label has appeared. But its text is an empty string! So you will never see it.
Check the "data_type" returned by DB reader.