Use List to populate labels C# - 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];
{

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

If else statement between two combobox using c#

I implemented two Combobox in my coding. 1st combobox contain the city name and the 2nd combobox contain the POI of that city. Now I want to implement if else statement between this two combobox. Suppose if I select 1st combobox, Button will enable only for 1st one, then if I select 2nd Combobox then Button will work for 2nd one. I do not know how to do it. My code is like this
public void Download_Click(object sender, EventArgs e)
{
// if combox1 select
// all function will work for combobox 1
//else if combobox2 select
//combobbox1 disabled and all function will work for combobx2
}
Initially I created class to set the value of combobox1 like this
class PlaceList
{
public static ComboBox Combo_list = new ComboBox();
public static DataGridView dataTable = new DataGridView();
public static void List()
{
var startPath = Application.StartupPath;
string folderName = Path.Combine(startPath, "POI_List");
System.IO.Directory.CreateDirectory(folderName);
string SavedfileName = "POI_list.json";
var Saving_path = Path.Combine(folderName, SavedfileName);
string fileName = "Zensus_Gemeinden_org.xlsx";
var path = Path.Combine(startPath, fileName);
String name = "Gemeinden_31.12.2011_Vergleich";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
path + ";Extended Properties='Excel 12.0 XML;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select [3] as City,[4] as Population, * From [" + name + "$D7:E11300] Where [4] > 10000", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
dataTable.DataSource = data;
for (int i = 0; i < data.Rows.Count; i++)
{
Combo_list.Items.Add(data.Rows[i]["City"]);
}
string Place_Json = "Place_List:" + JsonConvert.SerializeObject(data, Formatting.Indented);
File.WriteAllText(Saving_path, Place_Json);
}
}
}
Then in Form1.cs I created
Dictionary<string, List<string>> poi = new Dictionary<string, List<string>>();
private void LoadKeys()
{
foreach (string line in File.ReadLines("TextFile1.txt"))
{
string[] parts = line.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
poi.Add(parts[0], new List<string>());
poi[parts[0]] = new List<string>(parts.Skip(1));
}
}
void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedItem != null)
{
string txt = comboBox1.SelectedItem.ToString();
if (poi.ContainsKey(txt))
{
List<string> points = poi[txt];
comboBox2.Items.Clear();
comboBox2.Items.AddRange(points.ToArray());
}
}
}
That means combobox2 is dependent of combobox1. It will give the places name accoerding to the combobox1
then finally in form1.cs button 1 I am trying to do this somethis like this
public Form1()
{
InitializeComponent();
PlaceList.Combo_list = comboBox1;
PlaceList.List();
LoadKeys();
}
private void button1_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex != 0)
{
ShortText.txt1 = richTextBox1;
ShortText.shortText(comboBox1.Text);
}
else if (comboBox2.SelectedIndex != 0)
{
ShortText.txt1 = richTextBox1;
ShortText.shortText(comboBox2.Text);
}
else
{
MessageBox.Show("Error");
}
Check the selected index of each combobox for the default value. The one that isn't the default value is the one you use. For example, if the default is index 0:
if(combo1.SelectedIndex != 0){
//do something
}
else if(combo2.SelectedIndex != 0) {
//do something else
}
else {
// Error: You need to select something!
}

Search page with empty TextBox returns - Null or empty full-text predicate

I work on a search page. I am using 2 repeaters. First to display the results of the search and second to display paging.
The query works just fine if I exclude postback. I can type something in the search box and it appears on the screen. Without the postback, the problem is when I click to go to the second page, I lose the paging repeater. That means I cannot go back to the first page.
So I need this postback to work.
The problem is when the page first loads the text box is empty, therefore I get the following error: "Null or empty full-text predicate."
How to get around it?
Here my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindRpt();
}
}
private void BindRpt()
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["blabla"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
cmd.CommandText = "select Distinct Rank, columnA, columnB, columnC from FREETEXTTABLE (TABLE, columnA , '" + Search.Text + "' ) S, TABLE C WHERE c.columnID = S.[KEY] order by Rank Desc";
DataTable dt = new DataTable();
adapter.SelectCommand = cmd;
adapter.Fill(dt);
PagedDataSource pgitems = new PagedDataSource();
pgitems.DataSource = dt.DefaultView;
pgitems.AllowPaging = true;
pgitems.PageSize = 2;
pgitems.CurrentPageIndex = PageNumber;
if (pgitems.Count > 1)
{
rptPaging.Visible = true;
ArrayList pages = new ArrayList();
for (int i = 0; i <= pgitems.PageCount - 1; i++)
{
pages.Add((i + 1).ToString());
}
rptPaging.DataSource = pages;
rptPaging.DataBind();
}
else
{
rptPaging.Visible = false;
}
rptResults.DataSource = pgitems;
rptResults.DataBind();
}
public int PageNumber
{
get
{
if(ViewState["PageNumber"] != null)
{
return Convert.ToInt32(ViewState["PageNumber"]);
}
else
{
return 0;
}
}
set
{ ViewState["PageNumber"] = value; }
}
protected void rptPaging_ItemCommand(object source, System.Web.UI.WebControls.RepeaterCommandEventArgs e)
{
PageNumber = Convert.ToInt32(e.CommandArgument) - 1;
BindRpt();
}
protected void btnGo_Click(object sender, EventArgs e)
{
BindRpt();
}
Try adding the following as the first line of BindRpt()
if (string.IsNullOrEmpty(Search.Text)) return;
Update following condition:
if (pgitems.Count > 1)
to
if (pgitems.Count > 0)

How to delete a row from gridview on button click after the row's checkbox is selected

I have a DataGridView created in C# windows forms and checkboxColumn added to it. The DataGridView is populated with other columns like Sno, AccountNo, Name, Salary (Sno is identitycolumn and primarykey).
I want to delete a row (using stored procedure) by selecting the checkbox and on button click which is out side DataGridView. Error at "FindControl".
Stored Procedure:
Create Procedure uspDeleteSelectedRow
As
Delete from EmpDetails where Sno=Sno
Go
private void btnDelete_Click(object sender, EventArgs e)
{
//Create String Collection to store IDs of
//records to be deleted
StringCollection idCollection = new StringCollection();
string strID = string.Empty;
//Loop through GridView rows to find checked rows
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
CheckBox chkDelete = (CheckBox)dataGridView1.Rows[i].
Cells[0].FindControl("chkSelect");
if (chkDelete != null)
{
if (chkDelete.Checked)
{
strID = dataGridView1.Rows[i].Cells[1].ToString();
idCollection.Add(strID);
}
}
}
if (idCollection.Count > 0)
{
//Call the method to Delete records
DeleteMultipleRecords(idCollection);
// rebind the GridView
dataGridView1.DataBind();
}
else
{
lblMessage.Text = "Please select any row to delete";
}
}
private void DeleteMultipleRecords(StringCollection idCollection)
{
//Create sql Connection and Sql Command
SqlConnection con = new SqlConnection(Helper.ConnectionString);
SqlCommand cmd = new SqlCommand();
string IDs = "";
foreach (string id in idCollection)
{
IDs += id.ToString() + ",";
}
try
{
string test = IDs.Substring
(0, IDs.LastIndexOf(","));
string sql = "Delete from EmpDetails" + " WHERE ID in (" + test + ")";
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
string errorMsg = "Error in Deletion";
errorMsg += ex.Message;
throw new Exception(errorMsg);
}
finally
{
con.Close();
}
}
Let say this is your stored procedure:
ALTER PROCEDURE [dbo].[sp_ToDeleteEmpDetails] #Sno int
/*
(
#parameter1 int = 5,
#parameter2 datatype OUTPUT
)
*/
AS
DELETE FROM EmpDetails
WHERE Sno = Sno
RETURN
You don't need a StringCollection to delete or call the stored procedure.
private void btnDelete_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow item in dataGridView1.Rows)
{
bool IsBool = false;
if (bool.TryParse(item.Cells[1].EditedFormattedValue.ToString(), out IsBool)) //<--Where: The ColumnIndex of the DataGridViewCheckBoxCell
{
using (SqlConnection con = new SqlConnection(Helper.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("sp_ToDeleteEmpDetails", con))
{
try {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#sno", SqlDbType.Int).Value = item.Cells[0].EditedFormattedValue.ToString(); //<--Where: The ColumnIndex of the Primary key from your DataGridView
dataGridView1.Rows.RemoveAt(item.Cells[0].RowIndex);
con.Open();
cmd.ExecuteNonQuery();
} catch (Exception) {
throw;
}
finally
{
con.Close();
}
}
}
}
}
}
Please let me know if you have some encountered problem from my given answer.
Try this solution. In my code I have class and pass a list of it to gridview as my datasource.
//Class
public class User
{
public bool Selected { get; set; }
public string UserName { get; set; }
}
//Create a list and bind to the data grid view
private void Form1_Load(object sender, EventArgs e)
{
var users = new List<User> { new User { UserName = "Jobert", Selected = false }, new User { UserName = "John", Selected = true }, new User { UserName = "Leah", Selected = true }, new User { UserName = "Anna", Selected = false } };
dataGridView1.DataSource = users;
}
//On delete
private void btnDelete_Click(object sender, EventArgs e)
{
//get data back from the source
var source = dataGridView1.DataSource as List<User>;
var selectedItems = source.Where(x => x.Selected).ToList();
foreach (var item in selectedItems)
{
//perform the delete
}
}

WPF TreeView (hierarchicaldatatemplate ) with 2 tables

I have 2 db tables:
ProductGroup(GroupID, GroupName, ...)
Product(ProductID, ProductName, GroupID, ...)
Now I want to display the ProductGroup and the Product Table in a TreeView.
I am using an Entity Model and I dont now how to bind 2 Tables to 1 TreeView.
I am looking forward to some answers! THX
public partial class Form1 : Form
{
private string TextFields=string.Empty;
private string TagFields=string.Empty;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
FillTree();
}
void FillTree()
{
DataSet mds = new DataSet();
DataSet dds = new DataSet();
string ssql;
TextFields = "GroupName";
TagFields = "GroupID";
this.treeView1.Nodes.Clear();
ssql = "select GroupID, GroupName from productgroups ";
mds = DB.GetInstance.GetDataSet( ssql);
if(mds!=null)
insert1LevelNodes(null,mds.Tables[0]);
ssql="select ProductID, ProductName, GroupID from products";
dds = GetDataSet(ssql);
if(dds!=null)
{
for(short i = 0;i<this.treeView1.Nodes.Count;i++)
{
TextFields = "ProductName";
TagFields = "ProductID";
insert1LevelNodes(this.treeView1.Nodes[i],dds.Tables[0] );
}
}
dds.Clear();
dds.Dispose();
}
void insert1LevelNodes(TreeNode parentNode, DataTable dt)
{
string sNodeText = "";
string sNodeTag = "";
string[] aTexts = this.TextFields.Split(',');
string[] aTags = this.TagFields.Split(',');
for(int i=0; i< dt.Rows.Count; i++ )
{
sNodeText = "";
sNodeTag = "";
for(int k=0;k<dt.Columns.Count;k++)
{
for(short j=0;j<aTexts.Length;j++)
if(aTexts[j].Equals(dt.Columns[k].ColumnName))
sNodeText+=dt.Rows[i][k].ToString() + ":";
for(short j=0;j<aTags.Length;j++)
if(aTags[j].Equals(dt.Columns[k].ColumnName))
sNodeTag+=dt.Rows[i][k].ToString() + ",";
}
if(sNodeText.Length>0) sNodeText = sNodeText.TrimEnd(':');
if(sNodeTag.Length>0) sNodeTag = sNodeTag.TrimEnd(',');
if(sNodeText==string.Empty) return;
TreeNode newNode=new TreeNode(sNodeText);
newNode.Tag = sNodeTag;
if(parentNode==null)
treeView1.Nodes.Add(newNode);
else
parentNode.Nodes.Add(newNode);
}
}
DataSet GetDataSet(string ssql)
{
/// Your function to get Dataset from your Database
}
}

Categories

Resources