WPF TreeView (hierarchicaldatatemplate ) with 2 tables - c#

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

Related

How do I create a dataset in C# with local database

I am a beginner in C# and created a database in a Windows Forms App for a customer data, the function of it is to take the user's phone number and then search the table and then if it is found then populate the data fields with the information; otherwise it needs to add the new customer to the table.
When I run the code I get an error
System.ArgumentException: 'Keyword not supported: 'data source(localdb)\mssqlocaldb;attachdbfilename'.'
This is my code:
DataTable TableCust;
SqlConnection cnCust;
SqlDataAdapter dataCust;
DataGrid dtGridCust;
public bool buttonClicked = false;
private static int CurrentOrder = 1000;
private int i = 0;
Validation v = new Validation();
public frmPizzaPetes()
{
InitializeComponent();
}
string dataSource;
string SqlParms;
private void Form1_Load(object sender, EventArgs e)
{
btnAccept.Enabled = false;
lblOrderNo.Text = CurrentOrder.ToString();
Price();
//
dataSource = #"Data Source(LocalDB)\MSSQLocalDB;AttachDbFilename=|C:\Users\tyada\DATABASE\Pizza.mdf;";
SqlParms = "Integrated Securtiy=True; Connect Timeout==30";
string SqlCust = "select * from Customers";
string strConn = dataSource + SqlParms;
cnCust = new SqlConnection(strConn);
cnCust.Open();
TableCust = new DataTable();
dtGridCust.DataSource = TableCust;
}
public bool ifCustIsFound()
{
bool tester=false;
string SqlCustomer = "SELECT*FROM Customers WHERE CustPhone= '" + mtbPhone.Text + "';";
dataCust = new SqlDataAdapter(SqlCustomer, cnCust);
dataCust.Fill(TableCust);
if (TableCust.Rows.Count > 0)
{
txtName.Text = TableCust.Rows[0]["CustName"].ToString();
txtAddress.Text = TableCust.Rows[0]["CustAddress"].ToString();
txtApt.Text = TableCust.Rows[0]["CustSuite"].ToString();
txtCity.Text = TableCust.Rows[0]["CustCity"].ToString();
mtbZip.Text = TableCust.Rows[0]["CustZip"].ToString();
cboState.Text = TableCust.Rows[0]["CustState"].ToString();
// dtGridCust.DataSource = TableCust;
}
else
{
DialogResult dlg=MessageBox.Show("Add Customer?","Customer not found", MessageBoxButtons.YesNo);
if (dlg == DialogResult.Yes)
{
string strConn = dataSource + SqlParms;
SqlDataAdapter adaptSQL = new SqlDataAdapter(strSQL, strConn);
SqlCommand cmdCust = new SqlCommand();
SqlCommandBuilder cmdBld = new SqlCommandBuilder(adaptSQL);
DataRow newCust;
newCust = TableCust.NewRow();
newCust["CustPhone"] = mtbPhone.Text;
newCust["CustName"] = txtName.Text;
newCust["CustAddress1"] = txtAddress.Text;
newCust["CustAddress2"] = txtApt.Text;
newCust["CustCity"] = txtCity.Text;
newCust["CustState"] = cboState.Text;
newCust["CustZip"] = mtbZip.Text;
try
{
TableCust.Rows.Add(newCust);
cmdBld.GetUpdateCommand();
adaptSQL.Update(TableCust);
MessageBox.Show("Customer Added!");
}
catch (SqlException)
{
MessageBox.Show("Customer Add Failed!");
}
}
txtName.Focus();
}
return tester;
}
it seems "=" is missing in data source. Try this.
private void Form1_Load(object sender, EventArgs e)
{
btnAccept.Enabled = false;
lblOrderNo.Text = CurrentOrder.ToString();
Price();
//
dataSource = #"Data Source =(LocalDB)\MSSQLocalDB;AttachDbFilename=|C:\Users\tyada\DATABASE\Pizza.mdf;";
SqlParms = "Integrated Securtiy=True; Connect Timeout==30";
string SqlCust = "select * from Customers";
string strConn = dataSource + SqlParms;
cnCust = new SqlConnection(strConn);
cnCust.Open();
TableCust = new DataTable();
dtGridCust.DataSource = TableCust;
}

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!
}

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

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

Different select command in a single button click

I am trying to give multiple select commands in single button.
Example:
Datewise search,name wise,Product wise search in a single show Button.
But this search can be random like either name wise search alone can be done
or name and product wise search can be done.
But this should done in a single show button only..
Plz help me with a example code..
This is not a coding doubt,this is more likely a logic doubt,For this you have lot of options here you can perform some SQL Query concatenations Or some If..else...elseIf statements,something like this :
protected void btnSave_Click(object sender, EventArgs e)
{
if (ddpcustomer.SelectedIndex == 0 && ddpproperty.SelectedIndex == 0)
{
DataSet ds1 = Tbl_MasterBooking.getDetailsforBookingSummaryWithoutStatusCheckinDate(inputField.Text, inputField1.Text, userId, Cid);
GVBookingSummary.DataSource = ds1;
GVBookingSummary.DataBind();
GridView1.DataSource = ds1;
GridView1.DataBind();
}
else if (ddpcustomer.SelectedIndex != 0 && ddpproperty.SelectedIndex == 0)
{
DataSet ds1 = Tbl_MasterBooking.getDetailsforBookingSummaryWithoutStatusWithCustNameCheckinDate(inputField.Text, inputField1.Text, userId, Cid,ddpcustomer.SelectedItem.Text);
GVBookingSummary.DataSource = ds1;
GVBookingSummary.DataBind();
GridView1.DataSource = ds1;
GridView1.DataBind();
}
else if (ddpcustomer.SelectedIndex != 0 )
{
DataSet ds1 = Tbl_MasterBooking.getDetailsforBookingSummaryWithoutStatusWithPnameCheckinDate(inputField.Text, inputField1.Text, userId, Cid, ddpproperty.SelectedItem.Text);
GVBookingSummary.DataSource = ds1;
GVBookingSummary.DataBind();
GridView1.DataSource = ds1;
GridView1.DataBind();
}
else if (ddpcustomer.SelectedIndex != 0 && ddpproperty.SelectedIndex != 0)
{
DataSet ds1 = Tbl_MasterBooking.getDetailsforBookingSummaryWithoutStatusWithPnameandCustNameCheckinDate(inputField.Text, inputField1.Text, userId, Cid, ddpproperty.SelectedItem.Text, ddpcustomer.SelectedItem.Text);
GVBookingSummary.DataSource = ds1;
GVBookingSummary.DataBind();
GridView1.DataSource = ds1;
GridView1.DataBind();
}
}
If you want to do search based on One filter you'd better use a DropDownList and search based on the selected value or ... but if searching in multiple data collections is your doubt I'll provide you a code snippet below :
private class Product
{
public string Name;
public double Price;
public string ToString()
{
return Name + " : " + Price.ToString() + "$";
}
}
private void button1_Click(object sender, EventArgs e)
{
List<string> names = new List<string>();
names.Add("Jack");
names.Add("John");
names.Add("Nick");
names.Add("Rock");
List<Product> products = new List<Product>();
products.Add(new Product { Name = "Laptop", Price = 1000 });
products.Add(new Product { Name = "Tablet", Price = 750 });
products.Add(new Product { Name = "Rock", Price = 1 });
List<DateTime> dates = new List<DateTime>();
dates.Add(DateTime.Now.AddDays(-1));
dates.Add(DateTime.Now);
dates.Add(DateTime.Now.AddDays(1));
lblOutput.Text = "";
foreach (string name in names)
{
if (name == txtSearch.Text)
lblOutput.Text += name + "[Name] ";
}
foreach (Product product in products)
{
if (product.Name == txtSearch.Text)
lblOutput.Text += product.ToString();
}
foreach (DateTime date in dates)
{
DateTime dt;
if (DateTime.TryParse(txtSearch.Text, out dt))
if (date == dt)
lblOutput.Text = date.Date.ToShortDateString();
}
}
Also if you want to stop searching as soon as you've found a match, you can put a return after each match-found code block, for example:
if (name == txtSearch.Text)
{ lblOutput.Text += name + "[Name] "; return;}
I hope it helps.
I hope this would do.You may setup the options you like.
public class Parameters
{
//Properties.
public string CompanyName
{
get;set;
}
public string ProductName
{
get;set;
}
public string Design
{
get;set;
}
public string Size
{
get;set;
}
}
private void button1_Click(object sender, EventArgs e)
{
Parameters para = new Parameters();
if (cbxCompanyName.Text.Trim().Length != 0)
{
para.CompanyName = "'" + this.cbxCompanyName.Text + "'";
}
if (cbxProductName.Text.Trim().Length != 0)
{
para.ProductName = "'" + this.cbxProductName.Text + "'";
}
if (cbxDesign.Text.Trim().Length != 0)
{
para.Design = "'" + this.cbxDesign.Text + "'";
}
}
public void test(Parameters paras)
{
try
{
con = new SqlConnection(source);
con.Open();
string select;
select = "SPGetSaleRegCulture ";
DataSet ds = new DataSet();
cmd = new SqlCommand(select, con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Company", paras.CompanyName);
cmd.Parameters.AddWithValue("#Product", paras.ProductName);
cmd.Parameters.AddWithValue("#Design", paras.Design);
cmd.Parameters.AddWithValue("#Size", paras.Size);
da.SelectCommand = cmd;
da.Fill(ds, "SaleRegister");
}
catch (Exception ex)
{
throw ex;
}
}

Categories

Resources