I have searched for solution for this but all I found are questions how to prevent this.
I have a simple code for saving and loading XML.
XDocument xDoc;
public Form1()
{
InitializeComponent();
xDoc = new XDocument(new XElement("root", new XElement("data")));
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
string input = textBox1.Text;
xDoc.Root.SetElementValue("data", input);
rtxtXPreview.Text = xDoc.ToString();
txtValuePreview.Text = xDoc.Root.Element("data").Value;
}
private void button1_Click(object sender, EventArgs e)
{
SaveAndLoad();
}
private void SaveAndLoad()
{
string dataNodeValue;
xDoc.Save(path);
dataNodeValue = xDoc.Descendants("data").First().Value;
txtValuePreview.Text = dataNodeValue;
rtxtXPreview.Text = xDoc.ToString();
}
textBox1: is the input for the data element.
rtxtXPreview: is a rich textbox for displaying the text of the XML.
txtValuePreview: is a textbox for displaying the element value.
The problem is that when I enter value like:
A
B
C
The XML shows fine with the line breaks but once I hit the button the document is saved without those. So when I debugged my code I found that the characters \n\r is replaced with \n so I searched for this problem and found this code:
private void SaveAndLoadFixed()
{
string dataNodeValue;
XmlWriterSettings xmlWriterSettings =
new XmlWriterSettings { NewLineHandling = NewLineHandling.None, Indent = true };
using (XmlWriter xmlWriter = XmlWriter.Create(path, xmlWriterSettings))
{
xDoc.Save(xmlWriter);
xmlWriter.Flush();
}
//xDoc.Save(path);
XElement xDatabaseElement;
using (XmlTextReader xmlTextReader = new XmlTextReader(path) { WhitespaceHandling = WhitespaceHandling.Significant })
{
xmlTextReader.MoveToContent();
xDatabaseElement = XElement.Load(xmlTextReader);
}
dataNodeValue = xDatabaseElement.Descendants("data").First().Value;
txtValuePreview.Text = dataNodeValue;
rtxtXPreview.Text = xDatabaseElement.ToString();
}
This worked fine but why the characters \n\r not replaced with  because when I tried to type the character < or > it was replaced with < & > respectively ?
what I want is, after recording the mouse movement and saving the coordinates/ indexes/ position, I will have to load the mouse coordinates and make the mouse move according to the loaded coordinates
i don't have code to show you because am stuck at this point
' private void button3_Click_1(object sender, EventArgs e)
{
StreamWriter writer;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
string[] cvsArray = new string[10000];
saveFileDialog1.Filter = "All files (*.All)|*.All|All files (*.*)|*.*";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
writer = File.CreateText(saveFileDialog1.FileName);
// if ((myStream = saveFileDialog1.OpenFile()) != null)
//{
for (int i = 0; i < cvsArray.Length; i++)
{
string text = richTextBox1.Text;
writer.WriteLine(text);
}
// Code to write the stream goes here.
writer.Close();
//}
}
}
private void button11_Click(object sender, EventArgs e)
{
StreamReader reader;
string Line;
string[] cvsArray;
string position;
//set the filter to dialog control
openFileDialog1.Filter = FILTER;
//check if the user selected the right file
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
//open the selected file
reader = File.OpenText(openFileDialog1.FileName);
//Read the entireline form the file
Line = reader.ReadLine();
//read while it is still not the end of the file
while (!reader.EndOfStream)
{
Line = reader.ReadLine();
//Splite the line using array
cvsArray = Line.Split(':');
position = cvsArray[0];
//position = cvsArray[1];
listBox1.Items.Add(position);
}
}
}'
This is a quick and rather dirty solution:
Let's start with a few varibles:
List<Point> points = null;
Timer tt = null;
int index = 0;
Now a button to start the recoding; it initializes a List<Point> to collect the positions and creates and starts a Timer along with lambda code to do the recoding in the Timer.Tick event:
private void btn_Record_Click(object sender, EventArgs e)
{
points = new List<Point>();
index = 0;
tt = new Timer()
{ Interval = 50, Enabled = true };
tt.Tick += (ss, ee) =>
{
if (!points.Any() || points.Last() != Control.MousePosition)
points.Add(Control.MousePosition);
};
}
Next a button to stop recording:
private void btn_Stop_Click(object sender, EventArgs e)
{
if (tt!=null) tt.Stop();
}
Finally the replay button; it uses an index to loop over the the points collection in a new Timer.Tick code but using the same timer:
private void btn_Replay_Click(object sender, EventArgs e)
{
index = 0;
tt = new Timer() { Interval = 50, Enabled = true };
tt.Tick += (ss, ee) =>
{
if (index < points.Count)
{ System.Windows.Forms.Cursor.Position = points[index++]; }
else tt.Stop();
}
A few notes:
As asked in the question this will record and reply the Mmouse coodinates. It will do so in fixed intervals, so playback will look very similar to the original movements; in fact it is so hard to tell apart that I added a slowmo button with a longer interval to demonstrate.. (But the gif got too large)
The code will record the mouse positions in screen coordinates and should capture them wherever it goes, not only inside your application. See how VS is activating the code loupe!
It will not record any other mouse events, like up, down, click, doubleclick or wheel. For those you would need a global mouse hook for capturing and some external calls for replaying.
For including other mouse events you would also need a different and extended data structure; and you would also have to go from a timer-driven model to a mouse event driven one.
The example uses buttons to start and stop. Of course the movenments to and from those buttons get included in the recorded list of positions. Instead one could use a timed start, which would start recording after a few seconds and stop recording after a few seconds of inactivity..
There are various ways you can save and load the points; the simplest one is to serialize to xml; using a string path = #"..." it could look as simple as this:
private void btn_save_Click(object sender, EventArgs e)
{
if (points == null) points = new List<Point>();
XmlSerializer xs = new XmlSerializer((points).GetType());
using (TextReader tr = new StreamReader(path))
{
points = (List<Point>)xs.Deserialize(tr);
tr.Close();
}
}
private void btn_load_Click(object sender, EventArgs e)
{
XmlSerializer xs = new XmlSerializer((points).GetType());
using (TextWriter tw = new StreamWriter(path))
{
xs.Serialize(tw, points);
tw.Close();
}
}
Other ways would be using a binary formatter or a custom conversion routine. Xml is relatively stable.
Here is a short clip:
Im working on a simple project. I have windows form and when the Form open I want my "Userslistview" with 3 Columns to be filled with data from my XML which is also created by the program.
I have tried a couple of methodes but the listview just stays empty.
So here's the Load event code im using
private void MainMenu_Load(object sender, EventArgs e)
{
string xmlfile = AppDomain.CurrentDomain.BaseDirectory + "Users.xml";
if (!File.Exists(xmlfile))
{
return;
}
UserslistView.View = View.Details;
UserslistView.GridLines = true;
UserslistView.Sorting = SortOrder.Descending;
UserslistView.FullRowSelect = true;
UserslistView.Columns.Add("Active", 80);
UserslistView.Columns.Add("username", 120);
UserslistView.Columns.Add("Last Logon", 120);
UserslistView.Items.Clear();
DataSet ds = new DataSet();
ds.ReadXml(xmlfile);
ListViewItem item;
foreach (DataRow dr in ds.Tables["user"].Rows)
{
item = new ListViewItem(new string[]
{
dr["username"].ToString(),
dr["USERID"].ToString(),
dr["lastlogon"].ToString()
});
UserslistView.Items.Add(item);
}
}
and here's the XMl im using
UPDATE 1
I swapped my code for this.
private void MainMenu_Load(object sender, EventArgs e)
{
UserslistView.View = View.Details;
UserslistView.GridLines = true;
UserslistView.FullRowSelect = true;
UserslistView.Columns.Add("Active", 100);
UserslistView.Columns.Add("username", 120);
//UserslistView.Columns.Add("Last Logon", 100);
string xmlfile = AppDomain.CurrentDomain.BaseDirectory + "Users.xml";
XmlDocument doc = new XmlDocument();
try
{
doc.Load(xmlfile);
foreach (XmlNode n in doc.SelectNodes("/Users//user"))
{
ListViewItem li = new ListViewItem(n.SelectSingleNode("username").InnerText);
li.SubItems.Add(n.SelectSingleNode("lastlogon").InnerText);
UserslistView.Items.Add(li);
}
}
catch { }
}
The count for the node is 2.
But listview still stays empty
First make sure your xml is available in your project. I followed this example: How to add an xml file as a resource to Windows Forms exe
using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Linq;
private void MainMenu_Load(object sender, EventArgs e)
{
UserslistView.View = View.Details;
UserslistView.GridLines = true;
UserslistView.Sorting = SortOrder.Descending;
UserslistView.Columns.Add("Active", 80);
UserslistView.Columns.Add("username", 120);
UserslistView.Columns.Add("Last Logon", 120);
UserslistView.Items.Clear();
var doc = XDocument.Parse(Properties.Resources.Users);
var output = from x in doc.Root.Elements("user")
select new ListViewItem(new []
{
x.Element("USERID").Value,
x.Element("username").Value,
x.Element("lastlogon").Value
});
UserslistView.Items.AddRange(output.ToArray());
}
}
You can use XDocument and parse your Xml
XDocument doc = XDocument.Load(file path);
var nodes = doc.Descendants("user").Select(e=> new ListViewItem( new [] {
e.Element("username").Value,
e.Element("USERID").Value,
//e.Element("password").Value,
e.Element("lastlogon").Value
})).ToArray();
UserslistView.Items.AddRange(nodes);
This is the scenario
1-Navigate to admin page.
2-Enter username and password
3-Navigate to new page
4-Fill some text in textareas etc and post .
5-Repeat Step 3 and 4 until loop ends
The Code Below successfully does step 1 and 2. But it reaches step 3 before new page is loaded and generates the error "Object reference not set to an instance of an object" on this line doc.GetElementById("title").SetAttribute("value", "check1");
I am trying to achieve this from last 3 days but can't reached step 3 until now. Any help will be appreciated
bool AdminPagework =false;
bool postnavigationdone =false;
public Form1()
{
InitializeComponent();
webBrowser1.DocumentCompleted +=
new WebBrowserDocumentCompletedEventHandler(AdminPageCredentials);
webBrowser1.Navigate("www.website.com/admin");
}
private void AdminPageCredentials(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (AdminPagework == false && (webBrowser1.ReadyState == WebBrowserReadyState.Complete))
{
HtmlDocument doc = webBrowser1.Document;
doc.GetElementById("login").SetAttribute("value", "ADMIN");
doc.GetElementById("pass").SetAttribute("value", "123");
doc.GetElementById("submit").InvokeMember("click");
AdminPagework = true;
webBrowser1.DocumentCompleted +=
new WebBrowserDocumentCompletedEventHandler(RedirectToPostPage);
webBrowser1.Navigate("http://www.website.com/admin/post.php");
}
}
public void RedirectToPostPage(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if ((postnavigationdone == false) && (webBrowser1.ReadyState == WebBrowserReadyState.Complete))
{
HtmlDocument doc = webBrowser1.Document;
doc.GetElementById("title").SetAttribute("value", "check1");
doc.GetElementById("content").SetAttribute("value", textBox2.Text);
doc.GetElementById("post-format-video").InvokeMember("click");
doc.GetElementById("in-category-64").InvokeMember("click");
webBrowser1.Document.GetElementById("mm").SetAttribute("value", "01");
webBrowser1.Document.GetElementById("jj").SetAttribute("value", "01");
webBrowser1.Document.GetElementById("aa").SetAttribute("value", "2013");
webBrowser1.Document.GetElementById("hh").SetAttribute("value", "01");
webBrowser1.Document.GetElementById("mm").SetAttribute("value", "01");
doc.GetElementById("publish").InvokeMember("click");
postnavigationdone = true;
}
}
var titleElement = doc.GetElementById("title");
titleElement.SetAttribute("value","check1");
Try that and see if the title element is found after all, since the most likely reason it fails is: There is no element with the name "title".
I like using ScrapySharp framework (you'll find it on NuGet) for web automation.
var titleNodes = doc.DocumentNode.CssSelect("div#title").ToList();
foreach(var titleNode in titleNodes)
{
titleNode.SetAttribute("value","check1");
}
btw. why would you do that anyway, changing this attribute? Just curious...
I'm new to C# and don't have any programming experience. But I've finish a C# basics.
Now I would like to design a simple tree view by adding parent node and child node.
I would like to add a second child for the Second node, I'm quite stuck here and don't know what's next.
Any ideas?
Here is the code:
private void addParentNode_Click(object sender, EventArgs e)
{
string yourParentNode;
yourParentNode = textBox1.Text.Trim();
treeView2.Nodes.Add(yourParentNode);
}
private void addChildNode_Click(object sender, EventArgs e)
{
string yourChildNode;
yourChildNode = textBox1.Text.Trim();
treeView2.Nodes[0].Nodes.Add(yourChildNode);
}
Sorry I wasn't clear, I'm not sure if I really need this one here:
//treeView1.BeginUpdate();
//treeView1.Nodes.Clear();
What I'm trying to do, is to add Parent Nodes and child node. In my code, I can add several Parent Nodes, but if I want to add a child node, it only add in the first parent node.
I want that if I add a child node, I want to add it to the second parent or third parent.
In my code I only use one treeview here which names as treeview2
Here is the screenshot
this is how my final code looks like:
Before I put the else, I'm getting an error if I don't select anything. So I made it that way that if there is nothing selected it will add the "child node" to the "default node" or (parent1 node). It seems to work good. Thanks guys;-)
//This is for adding a parent node
private void addParentNode_Click(object sender, EventArgs e)
{
treeView2.BeginUpdate();
string yourParentNode;
yourParentNode = textBox1.Text.Trim();
treeView2.Nodes.Add(yourParentNode);
treeView2.EndUpdate();
}
//This is for adding child node
private void addChildNode_Click(object sender, EventArgs e)
{
if (treeView2.SelectedNode != null)
{
string yourChildNode;
yourChildNode = textBox1.Text.Trim();
treeView2.SelectedNode.Nodes.Add(yourChildNode);
treeView2.ExpandAll();
}
//This is for adding the child node to the default node(parent 1 node)
else
{
string yourChildNode;
yourChildNode = textBox1.Text.Trim();
treeView2.Nodes[0].Nodes.Add(yourChildNode);
}
Additional question: Are there any other ways on how the code be better? Because here, I declare the string "yourChildNode" twice. One in the if and other one in the else, are there any simplification?
It's not that bad, but you forgot to call treeView2.EndUpdate() in your addParentNode_Click() method.
You can also call treeView2.ExpandAll() at the end of your addChildNode_Click() method to see your child node directly.
private void addParentNode_Click(object sender, EventArgs e) {
treeView2.BeginUpdate();
//treeView2.Nodes.Clear();
string yourParentNode;
yourParentNode = textBox1.Text.Trim();
treeView2.Nodes.Add(yourParentNode);
treeView2.EndUpdate();
}
private void addChildNode_Click(object sender, EventArgs e) {
if (treeView2.SelectedNode != null) {
string yourChildNode;
yourChildNode = textBox1.Text.Trim();
treeView2.SelectedNode.Nodes.Add(yourChildNode);
treeView2.ExpandAll();
}
}
I don't know if it was a mistake or not but there was 2 TreeViews. I changed it to only 1 TreeView...
EDIT: Answer to the additional question:
You can declare the variable holding the child node name outside of the if clause:
private void addChildNode_Click(object sender, EventArgs e) {
var childNode = textBox1.Text.Trim();
if (!string.IsNullOrEmpty(childNode)) {
TreeNode parentNode = treeView2.SelectedNode ?? treeView2.Nodes[0];
if (parentNode != null) {
parentNode.Nodes.Add(childNode);
treeView2.ExpandAll();
}
}
}
Note: see http://www.yoda.arachsys.com/csharp/csharp2/nullable.html for info about the ?? operator.
May i add to Stormenet example some KISS (Keep It Simple & Stupid):
If you already have a treeView or just created an instance of it:
Let's populate with some data - Ex. One parent two child's :
treeView1.Nodes.Add("ParentKey","Parent Text");
treeView1.Nodes["ParentKey"].Nodes.Add("Child-1 Text");
treeView1.Nodes["ParentKey"].Nodes.Add("Child-2 Text");
Another Ex. two parent's first have two child's second one child:
treeView1.Nodes.Add("ParentKey1","Parent-1 Text");
treeView1.Nodes.Add("ParentKey2","Parent-2 Text");
treeView1.Nodes["ParentKey1"].Nodes.Add("Child-1 Text");
treeView1.Nodes["ParentKey1"].Nodes.Add("Child-2 Text");
treeView1.Nodes["ParentKey2"].Nodes.Add("Child-3 Text");
Take if farther - sub child of child 2:
treeView1.Nodes.Add("ParentKey1","Parent-1 Text");
treeView1.Nodes["ParentKey1"].Nodes.Add("Child-1 Text");
treeView1.Nodes["ParentKey1"].Nodes.Add("ChildKey2","Child-2 Text");
treeView1.Nodes["ParentKey1"].Nodes["ChildKey2"].Nodes.Add("Child-3 Text");
As you see you can have as many child's and parent's as you want and those can have sub child's of child's and so on....
Hope i help!
Example of adding child nodes:
private void AddExampleNodes()
{
TreeNode node;
node = treeView1.Nodes.Add("Master node");
node.Nodes.Add("Child node");
node.Nodes.Add("Child node 2");
node = treeView1.Nodes.Add("Master node 2");
node.Nodes.Add("mychild");
node.Nodes.Add("mychild");
}
It looks like you are only adding children to the first parent treeView2.Nodes[0].Nodes.Add(yourChildNode)
Depending on how you want it to behave, you need to be explicit about the parent node you wish to add the child to.
For Example, from your screenshot, if you wanted to add the child to the second node you would need:
treeView2.Nodes[1].Nodes.Add(yourChildNode)
If you want to add the children to the currently selected node, get the TreeView.SelectedNode and add the children to it.
Try TreeView to get an idea of how the class operates. Unfortunately the msdn documentation is pretty light on the code samples...
I'm missing a whole lot of safety checks here!
Something like (untested):
private void addChildNode_Click(object sender, EventArgs e) {
TreeNode ParentNode = treeView2.SelectedNode; // for ease of debugging!
if (ParentNode != null) {
ParentNode.Nodes.Add("Name Of Node");
treeView2.ExpandAll(); // so you can see what's been added
treeView2.Invalidate(); // requests a redraw
}
}
I needed to do something similar and came across the same issues. I used the AfterSelect event to make sure I wasn't getting the previously selected node.
It's actually really easy to reference the correct node to receive the new child node.
private void TreeView1_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
//show dialogbox to let user name the new node
frmDialogInput f = new frmDialogInput();
f.ShowDialog();
//find the node that was selected
TreeNode myNode = TreeView1.SelectedNode;
//create the new node to add
TreeNode newNode = new TreeNode(f.EnteredText);
//add the new child to the selected node
myNode.Nodes.Add(newNode);
}
Guys use this code for adding nodes and childnodes for TreeView from C# code.
*
KISS (Keep It Simple & Stupid :)*
protected void Button1_Click(object sender, EventArgs e)
{
TreeNode a1 = new TreeNode("Apple");
TreeNode b1 = new TreeNode("Banana");
TreeNode a2 = new TreeNode("gree apple");
TreeView2.Nodes.Add(a1);
TreeView2.Nodes.Add(b1);
a1.ChildNodes.Add(a2);
}
void treeView(string [] LineString)
{
int line = LineString.Length;
string AssmMark = "";
string PartMark = "";
TreeNode aNode;
TreeNode pNode;
for ( int i=0 ; i<line ; i++){
string sLine = LineString[i];
if ( sLine.StartsWith("ASSEMBLY:") ){
sLine = sLine.Replace("ASSEMBLY:","");
string[] aData = sLine.Split(new char[] {','});
AssmMark = aData[0].Trim();
//TreeNode aNode;
//aNode = new TreeNode(AssmMark);
treeView1.Nodes.Add(AssmMark,AssmMark);
}
if( sLine.Trim().StartsWith("PART:") ){
sLine = sLine.Replace("PART:","");
string[] pData = sLine.Split(new char[] {','});
PartMark = pData[0].Trim();
pNode = new TreeNode(PartMark);
treeView1.Nodes[AssmMark].Nodes.Add(pNode);
}
}
You may do as follows to Populate treeView with parent and child node. And also with display and value member of parent and child nodes:
arrayRoot = taskData.GetRocordForRoot(); // iterate through database table
for (int j = 0; j <arrayRoot.length; j++) {
TreeNode root = new TreeNode(); // Creating new root node
root.Text = "displayString";
root.Tag = "valueString";
treeView1.Nodes.Add(root); //Adding the root node
arrayChild = taskData.GetRocordForChild();// iterate through database table
for (int i = 0; i < arrayChild.length; i++) {
TreeNode child = new TreeNode(); // creating child node
child.Text = "displayString"
child.Tag = "valueString";
root.Nodes.Add(child); // adding child node
}
}
SqlConnection con = new SqlConnection(#"Data Source=NIKOLAY;Initial Catalog=PlanZadanie;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
DataTable dt = new DataTable();
public void loadTree(TreeView tree)
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT [RAZDEL_ID],[NAME_RAZDEL] FROM [tbl_RAZDEL]";
try
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
tree.Nodes.Add(reader.GetString(1));
tree.Nodes[0].Nodes.Add("yourChildNode");
tree.ExpandAll();
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Ошибка с сообщением: " + ex.Message);
}
}
You can improve that code
private void Form1_Load(object sender, EventArgs e)
{
/*
D:\root\Project1\A\A.pdf
D:\root\Project1\B\t.pdf
D:\root\Project2\c.pdf
*/
List<string> n = new List<string>();
List<string> kn = new List<string>();
n = Directory.GetFiles(#"D:\root\", "*.*", SearchOption.AllDirectories).ToList();
kn = Directory.GetDirectories(#"D:\root\", "*.*", SearchOption.AllDirectories).ToList();
foreach (var item in kn)
{
treeView1.Nodes.Add(item.ToString());
}
for (int i = 0; i < treeView1.Nodes.Count; i++)
{
n = Directory.GetFiles(treeView1.Nodes[i].Text, "*.*", SearchOption.AllDirectories).ToList();
for (int zik = 0; zik < n.Count; zik++)
{
treeView1.Nodes[i].Nodes.Add(n[zik].ToString());
}
}
}
void tree()
{
int counter = 0;
int counter1 = 0;
int counter2 = 0;
treeView1.Nodes.Clear();
var node = db.ChartOfAccounts.
Include(c => c.chartOfAccounts)
.Where(c => c.parent_account == null).ToList();
foreach (var account in node)
{
treeView1.Nodes.Add(account.account_title);
var node1 = db.ChartOfAccounts
.Where(c => c.parent_account == account.c_id).ToList();
bool t1 = db.ChartOfAccounts.Any(c => c.parent_account == account.c_id);
if (!t1) { counter = counter + 1; }
else
{
foreach (var item in node1)
{ treeView1.Nodes[(counter)].Nodes.Add(item.account_title);
bool test1 = db.ChartOfAccounts
.Any(c => c.parent_account == item.c_id);
if (!test1) { counter1 = counter1 + 1; }
else {
var node2 = db.ChartOfAccounts
.Where(c => c.parent_account == item.c_id).ToList();
foreach (var item2 in node2)
{
treeView1.Nodes[counter].Nodes[(counter1)].Nodes.Add(item2.account_title);
bool test2 = db.ChartOfAccounts
.Any(c => c.parent_account == item2.c_id);
if (!test2) { counter2 = counter2 + 1; }
else
{
var node3 = db.ChartOfAccounts
.Where(c => c.parent_account == item2.c_id).ToList();
foreach (var item3 in node3)
{ treeView1.Nodes[counter].Nodes[counter1].Nodes[counter2].Nodes.Add(item3.account_title); }
}
}
}
}
counter = counter + 1;
}
}
}