I have use the code below. And this tables in my database. I have textbox and button and i want on button click to be possible to add new child on Proba1,Proba2...What change i need to make and write in my code:
Output display:
protected void Page_Load(object sender, EventArgs e)
{
fill_Tree2();
}
void fill_Tree2()
{
DataSet PrSet = PDataset("Select * from ParentTable");
TreeView1.Nodes.Clear();
foreach (DataRow dr in PrSet.Tables[0].Rows)
{
TreeNode tnParent = new TreeNode();
tnParent.Text = dr["ParentName"].ToString();
tnParent.Value = dr["ParentID"].ToString();
tnParent.PopulateOnDemand = true;
tnParent.ToolTip = "Click to get Child";
tnParent.SelectAction = TreeNodeSelectAction.SelectExpand;
tnParent.Expand();
tnParent.Selected = true;
TreeView1.Nodes.Add(tnParent);
FillChild(tnParent, tnParent.Value);
}
}
public void FillChild(TreeNode parent, string ParentId)
{
DataSet ds = PDataset("Select * from ChildTable where ParentId =" + ParentId);
parent.ChildNodes.Clear();
foreach (DataRow dr in ds.Tables[0].Rows)
{
TreeNode child = new TreeNode();
child.Text = dr["ChildName"].ToString().Trim();
child.Value = dr["ChildId"].ToString().Trim();
if (child.ChildNodes.Count == 0)
{
child.PopulateOnDemand = true;
}
child.ToolTip = "Click to get Child";
child.SelectAction = TreeNodeSelectAction.SelectExpand;
child.CollapseAll();
parent.ChildNodes.Add(child);
}
}
protected DataSet PDataset(string Select_Statement)
{
SqlConnection SqlCon = new SqlConnection(#"Data Source=.\SQLEXPRESS;Initial Catalog=cms;Integrated Security=True");
SqlDataAdapter ad = new SqlDataAdapter(Select_Statement, SqlCon);
DataSet ds = new DataSet();
ad.Fill(ds);
return ds;
}
Related
I am new to c# and trying to search a listbox as following :
First i have this :
public partial class FrmCodes : Form
{
...
SqlConnection Cn = new SqlConnection(#"Server = AMR-PC\SQLEXPRESS ; Database=PlanningDB ; Integrated Security = True");
SqlCommand cmd;
SqlDataReader DataRead;
...
public FrmCodes()
{
InitializeComponent();
cmd = new SqlCommand("Select Item from Items", Cn);
Cn.Open();
DataRead = cmd.ExecuteReader();
while (DataRead.Read())
{
ListItems.Items.Add(DataRead["Item"].ToString());
}
DataRead.Close();
Cn.Close();
}
And tried to do this :
private void txtSrch_TextChanged(object sender, EventArgs e)
{
ListItems.Items.Clear();
while (DataRead.Read())
{
string str = DataRead["Item"].ToString();
string srch = txtSrch.Text;
if (str.Contains(srch))
{
ListItems.Items.Add(str);
}
}
}
It did not work , I tried to make a new sql select query that get data depending on txtSrch.Text but got nothing either .
Thanks in advance.
Edit#1
This is the query i mentioned before :
private void txtSrch_TextChanged(object sender, EventArgs e)
{
ListItems.Items.Clear();
SqlConnection Cn2 = new SqlConnection(#"Server = AMR-PC\SQLEXPRESS ; Database=PlanningDB ; Integrated Security = True");
Cn2.Open();
string srch = txtSrch.Text;
using (SqlDataAdapter a2 = new SqlDataAdapter("Select Item from Items WHERE Item LIKE '%" + srch + "%'", Cn2))
{
var t2 = new DataTable();
a2.Fill(t2);
ListItems.DisplayMember = "Item";
ListItems.ValueMember = "Code";
ListItems.DataSource = t2;
}
}
This did not affect the items in the listbox nothing happens on txtSrch Change .
Another solution using Dataview thanks to #Trevor
public partial class FrmCodes : Form
{
...
SqlConnection Cn = new SqlConnection(#"Server = AMR-PC\SQLEXPRESS ; Database=PlanningDB ; Integrated Security = True");
SqlDataAdapter da;
DataTable dt = new DataTable();
...
public FrmCodes()
{
InitializeComponent();
da = new SqlDataAdapter("Select Item from Items", Cn);
da.Fill(dt);
DataView dv = new DataView(dt);
ListItems.DataSource = dv;
ListItems.DisplayMember = "Item";
}
Textbox change :
private void txtSrch_TextChanged(object sender, EventArgs e)
{
ListItems.DataSource = null;
DataView dv = new DataView(dt);
string srch = txtSrch.Text;
dv.RowFilter = string.Format("Item Like '%{0}%'", srch);
ListItems.DataSource = dv;
ListItems.DisplayMember = "Item";
}
Thanks.
Basedon #Olivier Jacot-Descombes’ comments, this worked for me:
private void txtSrch_TextChanged(object sender, EventArgs e)
{
ListItems.DataSource = null;
SqlConnection Cn2 = new SqlConnection(#"Server = AMR-PC\SQLEXPRESS ; Database=PlanningDB ; Integrated Security = True");
Cn2.Open();
string srch = txtSrch.Text;
using (SqlDataAdapter a2 = new SqlDataAdapter("Select Item from Items WHERE Item LIKE '%" + srch + "%'", Cn2))
{
var t2 = new DataTable();
a2.Fill(t2);
ListItems.DisplayMember = "Item";
ListItems.ValueMember = "Code";
ListItems.DataSource = t2;
}
}
When I use the scanner to scan the barcode,
the item will be add in the first row and when I scan the second barcode,
the item will no add in the datagridview but it just adds a row only.
My column in datagridview is productid, ProductName, Description, Stock, UOM, Price
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
DataGridViewRow newRow = new DataGridViewRow();
if (textBox1.Text.Length != 0)
{
conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=F:\Database\book1.mdf;Integrated Security=True;Connect Timeout=30");
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter("SELECT productid,ProductName,Description,Stock,UOM,Price from ProductTable where productId='" + textBox1.Text + "'", conn);
DataTable dt = new DataTable();
adp.Fill(dt);
foreach (DataRow item in dt.Rows)
{
int i = dataGridView1.RowCount -1;
dataGridView1.Rows.Insert(i);
dataGridView1.Rows.Add();
dataGridView1.Rows[i].Cells[0].Value = item[0].ToString();
dataGridView1.Rows[i].Cells[1].Value = item[1].ToString();
dataGridView1.Rows[i].Cells[2].Value = item[2].ToString();
dataGridView1.Rows[i].Cells[3].Value = item[3].ToString();
dataGridView1.Rows[i].Cells[4].Value = item[4].ToString();
dataGridView1.Rows[i].Cells[5].Value = item[5].ToString();
}
}
}
}
Page Screenshots:
https://ibb.co/pJ0fnx7
Your approach if your productid is a unique key as it should be, will always be returning only one result, I really dont see the need of the foreach statement here. Moreover every time you open a conn to the database you should be closing it.
My approach with this in mind would be a little different this would be
Public Class clsConn
{
Public List<Data> getSomething()
var SqlConn = new SqlConnection("your connection");
try
{
SqlConn.Open();
string sqlstring = "your sql sentence";
SqlCommand SqlCmd = new SqlCommand(sqlstring, SqlConn);
SqlDataReader reader = SqlCmd.ExecuteReader();
List<Data> dataList = new List<Data>();
if (reader.Read())
{
Data data = new Data();
data.productid = reader[0].ToString(); // this is just an example
dataList.Add(data);
}
return dataList;
}
catch (Exception ex)
{
MessageBox.Show("conexion to DB failed: " + ex.Message);
throw;
}
finally
{
SqlConn.Close();
}
}
}
}
And you should have a public data class that has all the properties you need like this for example
public class Data
{
public string productid { get; set; }
}
To use it, you have to work like this
List<Data> dbData = new List<Data>();
clsConn db = new clsConn();
dbData = db.getSomething();
//I ll leave the foreach but as I said this should be only one result
foreach (var item in DBData)
{
dataGridView1.Rows.Add(item.productid);
}
Your .Insert()-call does not provide the row to insert, and you do not handle the index returned from the Rows.Add()-call.
I have edited your code a bit so that it should work now.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode != Keys.Enter) || (textBox1.Text.Length == 0))
{
return;
}
conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=F:\Database\book1.mdf;Integrated Security=True;Connect Timeout=30");
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter("SELECT productid,ProductName,Description,Stock,UOM,Price from ProductTable where productId='" + textBox1.Text + "'", conn);
DataTable dt = new DataTable();
adp.Fill(dt);
foreach (DataRow item in dt.Rows)
{
int i = dataGridView1.Rows.Add();
DataGridViewRow row = dataGridView1.Rows[i];
row.Cells[0].Value = item[0].ToString();
row.Cells[1].Value = item[1].ToString();
row.Cells[2].Value = item[2].ToString();
row.Cells[3].Value = item[3].ToString();
row.Cells[4].Value = item[4].ToString();
row.Cells[5].Value = item[5].ToString();
}
}
And do not forget to close your database connection. Consider using the using-statement for this.
You should also check this: How to add a new row to datagridview programmatically
I am building nodes dynamically from a DB table. When I run the code the node root node also appears which wont go away. I have tried everything. Looked up on the internet but haven't find a specific solution for this problem.
My ProductCategory table looks like this
Here's the code in .cs file
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetTreeViewItems();
}
}
private void GetTreeViewItems()
{
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlDataAdapter da = new SqlDataAdapter("select * from ProductCategories where ParentId in (0,1,2)", con);
DataSet ds = new DataSet();
da.Fill(ds);
ds.Relations.Add("ChildRows", ds.Tables[0].Columns["ProductCategoryId"],
ds.Tables[0].Columns["ParentId"]);
foreach (DataRow level1DataRow in ds.Tables[0].Rows)
{
if (string.IsNullOrEmpty(level1DataRow["ParentId"].ToString()))
{
TreeNode parentTreeNode = new TreeNode();
parentTreeNode.Text = level1DataRow["ProductCategoryName"].ToString();
parentTreeNode.Value = level1DataRow["ProductCategoryId"].ToString();
parentTreeNode.NavigateUrl = "?catid=" + level1DataRow["ProductCategoryId"].ToString();
int i = (int)level1DataRow["ProductCategoryId"];
GetChildRows(level1DataRow, parentTreeNode);
TreeView1.Nodes.Add(parentTreeNode);
}
}
}
private void GetChildRows(DataRow dataRow, TreeNode treeNode)
{
DataRow[] childRows = dataRow.GetChildRows("ChildRows");
foreach (DataRow row in childRows)
{
TreeNode childTreeNode = new TreeNode();
childTreeNode.Text = row["ProductCategoryName"].ToString();
childTreeNode.Value = row["ProductCategoryId"].ToString();
childTreeNode.NavigateUrl = "?catid=" + row["ProductCategoryId"].ToString();
treeNode.ChildNodes.Add(childTreeNode);
if (row.GetChildRows("ChildRows").Length > 0)
{
GetChildRows(row, childTreeNode);
}
}
}
}
You can't do this. I you want a node to be invisible, but it's children to show, then the only way is not to add the root node, and add the children as root nodes.
Either that, or write your own TreeView control.
for example: I generate two combo-boxes box1 and box2 dynamically(on run time with a add button click) and on the selected index change of box1, items in box2 should be changed ;data in both boxes is fetched from database.
int cnt = 0;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["WindowsFormsApplication1.Properties.Settings.BusinessUltra1_2ConnectionString"].ConnectionString);
SqlConnection conb = new SqlConnection(ConfigurationManager.ConnectionStrings["WindowsFormsApplication1.Properties.Settings.BusinessUltra1_2ConnectionString"].ConnectionString);
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WindowsFormsApplication1.Properties.Settings.BusinessUltra1_2ConnectionString"].ConnectionString);
SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["WindowsFormsApplication1.Properties.Settings.BusinessUltra1_2ConnectionString"].ConnectionString);
SqlConnection con3 = new SqlConnection(ConfigurationManager.ConnectionStrings["WindowsFormsApplication1.Properties.Settings.BusinessUltra1_2ConnectionString"].ConnectionString);
public Form2()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
cnt++;
AddNewComboBox();
AddNewComboBox1();
}
private void AddNewComboBox()
{
ComboBox myNewComboBox = new ComboBox();
myNewComboBox.Name = "ComboBox1" + cnt.ToString();
con.Open();
SqlDataAdapter adp = new SqlDataAdapter("select * from company", con);
DataSet ds = new DataSet();
adp.Fill(ds, "company");
myNewComboBox.DataSource = ds.Tables["company"];
myNewComboBox.DisplayMember = ds.Tables["company"].Columns[0].ToString();
myNewComboBox.ValueMember = ds.Tables["company"].Columns[0].ToString();
//Program.counteritems = myNewComboBox.SelectedValue.ToString();
myNewComboBox.SelectedIndexChanged += new EventHandler(myNewComboBox_SelectedIndexChanged);
flowLayoutPanel1.Controls.Add(myNewComboBox);
con.Close();
}
private void AddNewComboBox1()
{
//string xyz = Program.counteritems;
ComboBox myNewComboBox1 = new ComboBox();
myNewComboBox1.Name = "ComboBox2" + cnt.ToString();
conb.Open();
SqlDataAdapter adp1 = new SqlDataAdapter("select * from company", con);
DataSet ds1 = new DataSet();
adp1.Fill(ds1, "company");
myNewComboBox1.DataSource = ds1.Tables["company"];
myNewComboBox1.DisplayMember = ds1.Tables["company"].Columns[1].ToString();
myNewComboBox1.ValueMember = ds1.Tables["company"].Columns[1].ToString();
//myNewComboBox_SelectedIndexChanged(sender);
myNewComboBox1.SelectedIndexChanged += new EventHandler(myNewComboBox1_SelectedIndexChanged);
flowLayoutPanel2.Controls.Add(myNewComboBox1);
//changefunction();
conb.Close();
}
void myNewComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
var cbox1 = sender as ComboBox;
if (cbox1 != null)
{
if (cbox1.Name == "ComboBox1" + cnt.ToString())
{
var cbox2 = flowLayoutPanel2.Controls.OfType<ComboBox>().Where(c => c.Name == "ComboBox2" + cnt.ToString()).FirstOrDefault();
cbox2.SelectedValue = cbox1.SelectedValue.ToString();
con2.Open();
SqlDataAdapter adfgtyu = new SqlDataAdapter("select * from Cat_Comp_Item where (Category_Name='" + cbox1.SelectedText + "') ", con2);
DataSet dsft = new DataSet();
adfgtyu.Fill(dsft, "Cat_Comp_Item");
cbox2.DataSource = dsft.Tables["Cat_Comp_Item"];
cbox2.DisplayMember = dsft.Tables["Cat_Comp_Item"].Columns[1].ToString();
con2.Close();
}
}
//string combochange1 = ((ComboBox)sender).Text;
//if (!string.IsNullOrEmpty(myNewComboBox.SelectedValue.ToString()))
//{
// myNewComboBox1.SelectedValue = myNewComboBox.SelectedValue.ToString();
//}
}
private void Form2_Load(object sender, EventArgs e)
{
AddNewComboBox();
AddNewComboBox1();
}
void myNewComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show("Press OK to select this ");
}
I think you should bind first combobox value and second combobox add just text(---select---) on add button and letter on first combobox index change bind second combobox
You can do as below
private void myNewComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
var cbox1 = sender as ComboBox;
if (cbox1 != null)
{
if (cbox1.Name == "ComboBox1")
{
var cbox2 = flowLayoutPanel2.Controls.OfType<ComboBox>().Where(c => c.Name == "ComboBox2").FirstOrDefault();
cbox2.SelectedValue = cbox1.SelectedValue.ToString();
}
}
}
To Do that you need to set comboBox2.ValueMember and comboBox1.ValueMember as same column in your company Table. select ID column or primary key column for that.
And also name your comboboxes as ComboBox1 and ComboBox2 when you create it like below
ComboBox myNewComboBox = new ComboBox();
myNewComboBox.Name = "ComboBox1";
And do the same for ComboBox2
I have a database table (named Topics) which includes these fields :
topicId
name
parentId
and by using them I wanna populate a TreeView in c#. How can I do that ?
Thanks in advance...
It will probably be something like this. Give some more detail as to what exactly you want to do if you need more.
//In Page load
foreach (DataRow row in topics.Rows)
{
TreeNode node = new TreeNode(dr["name"], dr["topicId"])
node.PopulateOnDemand = true;
TreeView1.Nodes.Add(node);
}
///
protected void PopulateNode(Object sender, TreeNodeEventArgs e)
{
string topicId = e.Node.Value;
//select from topic where parentId = topicId.
foreach (DataRow row in topics.Rows)
{
TreeNode node = new TreeNode(dr["name"], dr["topicId"])
node.PopulateOnDemand = true;
e.Node.ChildNodes.Add(node);
}
}
Not quite.
Trees are usually handled best by not loading everything you can at once. So you need to get the root node (or topic) which has no parentIDs. Then add them to the trees root node and then for each node you add you need to get its children.
foreach (DataRow row in topicsWithOutParents.Rows)
{
TreeNode node = New TreeNode(... whatever);
DataSet childNodes = GetRowsWhereParentIDEquals(row["topicId"]);
foreach (DataRow child in childNodes.Rows)
{
Treenode childNode = new TreeNode(..Whatever);
node.Nodes.add(childNode);
}
Tree.Nodes.Add(node);
}
this code runs perfectly for me, check it out i think it will help you :)
;
protected void Page_Load(object sender, EventArgs e)
{
DataSet ds = RunQuery("Select topicid,name from Topics where Parent_ID IS NULL");
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
TreeNode root = new TreeNode(ds.Tables[0].Rows[i][1].ToString(),ds.Tables[0].Rows[i][0].ToString());
root.SelectAction = TreeNodeSelectAction.Expand;
CreateNode(root);
TreeView1.Nodes.Add(root);
}
}
void CreateNode(TreeNode node)
{
DataSet ds = RunQuery("Select topicid, name from Category where Parent_ID =" + node.Value);
if (ds.Tables[0].Rows.Count == 0)
{
return;
}
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
TreeNode tnode = new TreeNode(ds.Tables[0].Rows[i][1].ToString(), ds.Tables[0].Rows[i][0].ToString());
tnode.SelectAction = TreeNodeSelectAction.Expand;
node.ChildNodes.Add(tnode);
CreateNode(tnode);
}
}
DataSet RunQuery(String Query)
{
DataSet ds = new DataSet();
String connStr = "???";//write your connection string here;
using (SqlConnection conn = new SqlConnection(connStr))
{
SqlCommand objCommand = new SqlCommand(Query, conn);
SqlDataAdapter da = new SqlDataAdapter(objCommand);
da.Fill(ds);
da.Dispose();
}
return ds;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
PopulateRootLevel();
}
private void PopulateRootLevel()
{
SqlConnection objConn = new SqlConnection(connStr);
SqlCommand objCommand = new SqlCommand(#"select FoodCategoryID,FoodCategoryName,(select count(*) FROM FoodCategories WHERE ParentID=c.FoodCategoryID) childnodecount FROM FoodCategories c where ParentID IS NULL", objConn);
SqlDataAdapter da = new SqlDataAdapter(objCommand);
DataTable dt = new DataTable();
da.Fill(dt);
PopulateNodes(dt, TreeView2.Nodes);
}
private void PopulateSubLevel(int parentid, TreeNode parentNode)
{
SqlConnection objConn = new SqlConnection(connStr);
SqlCommand objCommand = new SqlCommand(#"select FoodCategoryID,FoodCategoryName,(select count(*) FROM FoodCategories WHERE ParentID=sc.FoodCategoryID) childnodecount FROM FoodCategories sc where ParentID=#parentID", objConn);
objCommand.Parameters.Add("#parentID", SqlDbType.Int).Value = parentid;
SqlDataAdapter da = new SqlDataAdapter(objCommand);
DataTable dt = new DataTable();
da.Fill(dt);
PopulateNodes(dt, parentNode.ChildNodes);
}
protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e)
{
PopulateSubLevel(Int32.Parse(e.Node.Value), e.Node);
}
private void PopulateNodes(DataTable dt, TreeNodeCollection nodes)
{
foreach (DataRow dr in dt.Rows)
{
TreeNode tn = new TreeNode();
tn.Text = dr["FoodCategoryName"].ToString();
tn.Value = dr["FoodCategoryID"].ToString();
nodes.Add(tn);
//If node has child nodes, then enable on-demand populating
tn.PopulateOnDemand = ((int)(dr["childnodecount"]) > 0);
}
}
When there are no Large Amounts of Data then it is not good to connect database, fetch data and add to treeview node again and again for child/sub nodes. It can be done in single attempt. See following sample:
http://urenjoy.blogspot.com/2009/08/display-hierarchical-data-with-treeview.html
This code runs perfectly for me. Thought it might be useful for somebody looking to display hierarchial data in a treeview.By far, i guess this is the simplest. Please check it out and upvote if it helps you.
Reference : https://techbrij.com/display-hierarchical-data-with-treeview-in-asp-net
C# code:
//dtTree should be accessible in both page load and AddNodes()
//DocsMenu is the treeview Id
DataTable dtTree = new DataTable();
//declare your connection string
protected void Page_Load(object sender, EventArgs e)
{
//DataTable dtTree = new DataTable();
using (con)
{
con.Open();
string sQuery = "Select topicId,parentid,name from tbl_topicMaster";
SqlCommand cmd = new SqlCommand(sQuery, con);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dtTree);
da.Dispose();
con.Close();
}
AddNodes(-1, DocsMenu.Nodes);
}
void AddNodes(int id, TreeNodeCollection tn)
{
foreach (DataRow dr in dtTree.Select("parentid= " + id))
{
TreeNode sub = new TreeNode(dr["name"].ToString(), dr["topicId"].ToString());
tn.Add(sub);
AddNodes(Convert.ToInt32(sub.Value), sub.ChildNodes);
}
}
aspx code:
<asp:TreeView ID="DocsMenu" runat="server" ImageSet="BulletedList"
NodeIndent="15" >
<HoverNodeStyle Font-Underline="True" ForeColor="#6666AA" />
<NodeStyle Font-Names="Tahoma" Font-Size="8pt" ForeColor="Black" HorizontalPadding="2px"
NodeSpacing="0px" VerticalPadding="2px"></NodeStyle>
<ParentNodeStyle Font-Bold="False" />
<SelectedNodeStyle BackColor="#B5B5B5" Font-Underline="False" HorizontalPadding="0px"
VerticalPadding="0px" />
</asp:TreeView>