How To Get All Data[Row] from Ms Database in Dynamic TextBox - c#

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

Related

Sending order to database- Till/Kitchen View Restaurant Ordering System

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

Can't get the total row count

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

How to pass multiple selected item text from DropDownListCheckBoxes to Parameterized Sql

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?

where I am wrong? creating labels dynamically c#

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.

Use List to populate labels C#

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];
{

Categories

Resources