How to bind xml data to comboBox for making intelligence? - c#

This is my xml file;
<UserClass>
<Id>1</Id>
<Name>oss</Name>
<Address>
<Id>1</Id>
<Street>asstreet</Street>
</Address>
</UserClass>
So I want to add these "nodes" to comboBox items.
When user typed UserClass and type "."(dot) to end of "UserClass"; Id, Name and other things have to listed in combobox.
User typed "UserClass." and -> combobox get these;
UserClass.Id
UserClass.Name
UserClass.Address.Id
UserClass.Address.Street
I tried many things, include that one;
...
try
{
string parsedNode = ParseComboBox();
XmlReader rdr = XmlReader.Create(new System.IO.StringReader(_globalXml));
comboBox1.Items.Clear();
while (rdr.Read())
{
if (rdr.NodeType == XmlNodeType.Element)
{
comboBox1.Items.Add(rdr.LocalName);
}
comboBox1.DroppedDown = true;
}
//string parsedNode = ParseComboBox();
//XmlNodeList childList = xml.GetElementsByTagName(parsedNode);
////comboBox1.Items.Clear();
//foreach (XmlNode node in childList)
//{
// foreach (var osman in node.ChildNodes)
// {
// comboBox1.Items.Add(parsedNode + "." + osman);
// }
//}
}
catch (Exception)
{
MessageBox.Show("fuuu");
}
}...
private string ParseComboBox()
{
string resultAsXmlNodes = null;
string text = comboBox1.Text;
if (text.EndsWith("."))
{
char[] delimiterChars = { '.' };
string[] words = text.Split(delimiterChars);
foreach (string s in words)
{
resultAsXmlNodes += s;
}
}
return resultAsXmlNodes;
}
It's not working correctly. I believe there is an easy way to do it.
So, what is the simple way? Or simply,
How can I show node names in comboBox ?

I found multiple problems with this. Here's some example code that I got working for a form project with an XML File and one ComboBox control:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
comboBox1.KeyDown += comboBox1_KeyDown;
}
private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Decimal:
case Keys.OemPeriod:
LoadComboItems(comboBox1.Text);
break;
default:
break;
}
}
void LoadComboItems(string userInput)
{
comboBox1.Items.Clear();
string lookupName = userInput.Trim();
if (lookupName.Length > 0)
{
string _globalXML = Application.StartupPath + #"\XMLFile1.xml";
XmlReader rdr = XmlReader.Create(_globalXML);
while (rdr.Read())
{
if (rdr.LocalName == lookupName)
{
string ElementName = "";
int eCount = 0;
int prevDepth = 0;
while (rdr.Read())
{
if (rdr.NodeType == XmlNodeType.Element)
{
ElementName += '.' + rdr.LocalName;
eCount++;
}
else if (rdr.NodeType == XmlNodeType.EndElement && eCount == rdr.Depth)
{
if (rdr.Depth >= prevDepth)
{
comboBox1.Items.Add(lookupName + ElementName);
int pos = ElementName.LastIndexOf('.');
ElementName = ElementName.Substring(0, pos);
prevDepth = rdr.Depth;
}
eCount--;
}
}
}
}
if (rdr != null)
{
rdr.Close();
}
comboBox1.DroppedDown = true;
}
}
}
}

Related

import txt file to datagridview c#

hi i have txt file like this (email:password) and want to upload it into datagridview with 2 column
what i've done
bool flag = this.openFileDialog1.ShowDialog() != DialogResult.Cancel;
if (flag)
{
try
{
StreamReader streamReader = new StreamReader(openFileDialog1.FileName);
dataGridView1.AllowUserToAddRows = false;
string text = streamReader.ReadLine();
string[] array = text.Split(new char[]
{
':'
});
for (text = streamReader.ReadLine(); text != null; text = streamReader.ReadLine())
{
dataGridView1.Rows.Add();
for (int i = 0; i <= array.Count<string>() - 1; i++)
{
array = text.Split(new char[]
{
':'
});
dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[i].Value = array[i].ToString();
}
}
streamReader.Close();
}
catch (Exception var_7_106)
{
MessageBox.Show("Error+ err.Message ");
}
}
nothing imported in my datagridview
Here is the code using a datatable
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
bool flag = this.openFileDialog1.ShowDialog() != DialogResult.Cancel;
if (flag)
{
DataTable dt = new DataTable();
dt.Columns.Add("Col A", typeof(string));
dt.Columns.Add("Col B", typeof(string));
try
{
StreamReader streamReader = new StreamReader(openFileDialog1.FileName);
dataGridView1.AllowUserToAddRows = false;
string text = "";
for (text = streamReader.ReadLine(); text != null; text = streamReader.ReadLine())
{
string[] array = text.Split(new char[] { ':' });
dataGridView1.Rows.Add(array);
}
streamReader.Close();
}
catch (Exception err)
{
MessageBox.Show("Error" + err.Message );
}
dataGridView1.DataSource = dt;
}
}
}
}

foreach loop syntax error C# Visual Studio 2013 ultimate

Okay so yes I am doing homework and I am SO close on this one I know it, but ive been messing with it for over an hour and now I'm going insane, if i take the loop out my program will read the file and say weather you passed but it wont write the wrong answers in the listbox, if i put in my foreach code it gives me a syntax error.
this is my current code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace DriversLicenseExam
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string[] answerArray ={"B","D","A","A","C",
"A", "B","A","C","D",
"B", "C","D","A","D",
"C", "C","B","D","A"};
string[] studentansArray = new string[20];
List<string> incorrectList = new List<string>();
int count = 0, index = 0, qnumber = 0;
try
{
string filename = "../../" + filenametxt.Text;
StreamReader inputFile = File.OpenText(filename);
while(!inputFile.EndOfStream)
{
studentansArray[index] = inputFile.ReadLine();
if (studentansArray[index] == answerArray[index])
count++;
else
{
qnumber = index + 1;
incorrectList.Add(qnumber.ToString());
}
index++;
}
inputFile.Close();
if (count >= 15)
{
resultoutput.Text = "You Passed The Test!";
}
else
resultoutput.Text = "You Failed The Test... You're a Failure!";
}
foreach (string str in incorrectList) // <<-- error is here
{
lbox.Items.Add(str);
} // <<-- error is here
catch (Exception)
{
MessageBox.Show("File Not Found");
}
}
private void button2_Click(object sender, EventArgs e)
{
filenametxt.Text = "";
resultoutput.Text = "";
lbox.Items.Clear();
}
private void exitbutton_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
I'm not 100% sure about this, but your foreach is between your try and catch block, maybe try with that:
try
{
string filename = "../../" + filenametxt.Text;
StreamReader inputFile = File.OpenText(filename);
while(!inputFile.EndOfStream)
{
studentansArray[index] = inputFile.ReadLine();
if (studentansArray[index] == answerArray[index])
count++;
else
{
qnumber = index + 1;
incorrectList.Add(qnumber.ToString());
}
index++;
}
inputFile.Close();
if (count >= 15)
{
resultoutput.Text = "You Passed The Test!";
}
else
resultoutput.Text = "You Failed The Test... You're a Failure!";
foreach (string str in incorrectList)
{
lbox.Items.Add(str);
}
}
catch (Exception)
{
MessageBox.Show("File Not Found");
}

C# Windows Application LOC_Counter

Hey I want to create a windows application that should display the total lines, Blank lines and commented lines. I am able to calculate Total Lines, Can any one help me with the logic for blank lines and commented lines!
I want to count the Lines Of Code, for any file, i.e .html, .css, .cs, etc.
Also if possible I want the result to be exported to a Excel File!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace Line_Counter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
textbox1.Clear();
textbox2.Clear();
if (ofd.ShowDialog() == DialogResult.OK)
{
string strFilename = ofd.FileName;
textbox1.Text = Path.GetFileName(strFilename);
StreamReader sr = File.OpenText(strFilename);
int nLineCount = 0;
while (sr.ReadLine() != null)
{
nLineCount++;
}
textbox1.Text = nLineCount.ToString("0,0");
sr.Close();
}
}
private void txtFileName_TextChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
I want more text boxes that should display count of blank lines, Commented lines, and finally the total count (i.e. subtracting the no. of blank lines and commented lines from total no of lines)
If Possible single button_click for each or all in one.enter image description here
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace LOC_Counter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
void getFileList(string directory)
{
string[] dirs = Directory.GetDirectories(directory);
foreach (string dir in dirs)
{
getFileList(dir);
}
string[] files = Directory.GetFiles(directory);
foreach (string file in files)
{
StreamReader sr = File.OpenText(file);
int nLineCount = 0;
string str = string.Empty;
while (!sr.EndOfStream)
{
str = sr.ReadLine();
if (str != null && str.Length > 0 && (str.Length > 2 && str.Substring(0, 2) != "//") && (str.Length > 3 && str.Substring(0, 4) != "<!--"))
nLineCount++;
}
lstbxResult.Items.Add(file + " Line count - " + nLineCount);
}
}
private void btnBrowse_Click(object sender, EventArgs e)
{
FolderBrowserDialog FBD = new FolderBrowserDialog();
if (FBD.ShowDialog() == DialogResult.OK)
{
lstbxResult.Items.Clear();
getFileList(FBD.SelectedPath);
}
}
public static void ExportToExcel(ListBox lst, string excel_file)
{
int cols;
//open file
StreamWriter wr = new StreamWriter(excel_file);
//write rows to excel file
for (int i = 0; i < (lst.Items.Count - 1); i++)
{
wr.Write(lst.Items[i].ToString() + "\t");
wr.WriteLine();
}
//close file
wr.Close();
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
}
}

How can i make that in the ComboBox control it will show only part of each item name?

This is how i List and Add all the win32 items to the ComboBox.
using System;
using System.Collections;
using System.Management;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace GetHardwareInfo
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
cmbxOption.SelectedItem = "Win32_Processor";
cmbxStorage.SelectedItem = "Win32_DiskDrive";
cmbxMemory.SelectedItem = "Win32_CacheMemory";
cmbxSystemInfo.SelectedItem = "";
cmbxNetwork.SelectedItem = "Win32_NetworkAdapter";
cmbxUserAccount.SelectedItem = "Win32_SystemUsers";
cmbxDeveloper.SelectedItem = "Win32_COMApplication";
cmbxUtility.SelectedItem = "Win32_1394Controller";
}
private void InsertInfo(string Key, ref ListView lst, bool DontInsertNull)
{
lst.Items.Clear();
ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from " + Key);
try
{
foreach (ManagementObject share in searcher.Get())
{
ListViewGroup grp;
try
{
grp = lst.Groups.Add(share["Name"].ToString(), share["Name"].ToString());
}
catch
{
grp = lst.Groups.Add(share.ToString(), share.ToString());
}
if (share.Properties.Count <= 0)
{
MessageBox.Show("No Information Available", "No Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
foreach (PropertyData PC in share.Properties)
{
ListViewItem item = new ListViewItem(grp);
if (lst.Items.Count % 2 != 0)
item.BackColor = Color.White;
else
item.BackColor = Color.WhiteSmoke;
item.Text = PC.Name;
if (PC.Value != null && PC.Value.ToString() != "")
{
switch (PC.Value.GetType().ToString())
{
case "System.String[]":
string[] str = (string[])PC.Value;
string str2 = "";
foreach (string st in str)
str2 += st + " ";
item.SubItems.Add(str2);
break;
case "System.UInt16[]":
ushort[] shortData = (ushort[])PC.Value;
string tstr2 = "";
foreach (ushort st in shortData)
tstr2 += st.ToString() + " ";
item.SubItems.Add(tstr2);
break;
default:
item.SubItems.Add(PC.Value.ToString());
break;
}
}
else
{
if (!DontInsertNull)
item.SubItems.Add("No Information available");
else
continue;
}
lst.Items.Add(item);
}
}
}
catch (Exception exp)
{
MessageBox.Show("can't get data because of the followeing error \n" + exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void RemoveNullValue(ref ListView lst)
{
foreach (ListViewItem item in lst.Items)
if (item.SubItems[1].Text == "No Information available")
item.Remove();
}
#region Control events ...
private void cmbxNetwork_SelectedIndexChanged(object sender, EventArgs e)
{
InsertInfo(cmbxNetwork.SelectedItem.ToString(), ref lstNetwork, chkNetwork.Checked);
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
linkLabel1.LinkVisited = true;
}
#endregion
}
}
What i get is in the end that in the ComboBox in this case i call it cmbxNetwork i see in it many items all start with Win32_
For example when i click on ComboBox i see the first item is: "Win32_NetworkAdapter"
Instead Win32_NetworkAdapter i want to see in the ComboBox only: NetworkAdapter
But when i select the item it should be selected as Win32_NetworkAdapter but the user should see and select only NetworkAdapter.
I want to remove as test from the ComboBox items the Win32_
But only that the user will see it without Win32_
Also in the constructor when i'm doing now: cmbxNetwork.SelectedItem = "Win32_NetworkAdapter"; so instead if i'm doing: cmbxNetwork.SelectedItem = "NetworkAdapter"; it will be enough. THe program will use the "Win32_NetworkAdapter"; but again what i see and user in the ComboBox as item is only the NetworkAdapter
You might use objects from a self-written structure which encapsulates a value and a display string:
class Box {
public object Value { get; set; }
public string Display { get; set; }
public override string ToString() { return Display; }
}
Put your values into a Box-class and define a display-string. The ComboBox will show the result of ToString.

what might be causing this to fill this treeview multiple times?

I found this code online. It works, but for some reason it loads the file directory twice.
namespace DockSample.Controls
{
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing;
using Microsoft.VisualBasic.FileIO;
using DockSample;
//TODO: Add options for filtering by robot
public class SolutionExplorer : TreeView
{
public SolutionExplorer()
{
this.BeforeExpand += customBeforeExpand;
this.Nodes.Clear();
CreateTree(this);
}
private bool CreateTree(TreeView treeView)
{
bool returnValue = false;
try
{
// Create Desktop
TreeNode desktop = new TreeNode();
// desktop.Text = "Desktop";
// desktop.Tag = "Desktop";
// desktop.Nodes.Add("");
// treeView.Nodes.Add(desktop);
// Get driveInfo
foreach (DriveInfo drv in DriveInfo.GetDrives())
{
TreeNode fChild = new TreeNode();
if (drv.DriveType == DriveType.CDRom)
{
fChild.ImageIndex = 1;
fChild.SelectedImageIndex = 1;
}
else if (drv.DriveType == DriveType.Fixed)
{
fChild.ImageIndex = 0;
fChild.SelectedImageIndex = 0;
}
fChild.Text = drv.Name;
fChild.Nodes.Add("");
treeView.Nodes.Add(fChild);
returnValue = true;
}
}
catch
{
returnValue = false;
}
return returnValue;
}
/* Method :EnumerateDirectory
* Author : Chandana Subasinghe
* Date : 10/03/2006
* Discription : This is use to Enumerate directories and files
*
*/
public TreeNode EnumerateDirectory(TreeNode parentNode, List<string> thisFilter)
{
try
{
DirectoryInfo rootDir;
// To fill Desktop
Char[] arr = { '\\' };
string[] nameList = parentNode.FullPath.Split(arr);
string path = "";
if (nameList.GetValue(0).ToString() == "Desktop")
{
path = SpecialDirectories.Desktop + "\\";
for (int i = 1; i < nameList.Length; i++)
{
path = path + nameList[i] + "\\";
}
rootDir = new DirectoryInfo(path);
}
// for other Directories
else
{
rootDir = new DirectoryInfo(parentNode.FullPath + "\\");
}
parentNode.Nodes[0].Remove();
foreach (DirectoryInfo dir in rootDir.GetDirectories())
{
TreeNode node = new TreeNode();
node.Text = dir.Name;
node.Nodes.Add("");
parentNode.Nodes.Add(node);
}
//Fill files
foreach (FileInfo file in rootDir.GetFiles())
{
if (isValidFilter(getExtention(file.Name)))
{
TreeNode node = new TreeNode();
node.Text = file.Name;
node.ImageIndex = 2;
node.SelectedImageIndex = 2;
parentNode.Nodes.Add(node);
}
}
}
catch
{
}
return parentNode;
}
private bool isValidFilter(string ext)
{
bool result = false;
foreach(string s in filter)
{
if (ext == s)
result = true;
}
return result;
}
private string getExtention(string filename)
{
return filename.Substring(filename.IndexOf("."));
}
private void customBeforeExpand(object sender, TreeViewCancelEventArgs e)
{
if (e.Node.Nodes[0].Text == "")
{
TreeNode node = this.EnumerateDirectory(e.Node,filter);
}
}
private List<string> filter = new List<string>();
public List<string> Filter
{
get { return filter; }
set { filter = value; }
}
private void InitializeComponent()
{
this.SuspendLayout();
this.ResumeLayout(false);
}
}
}
The constructor of your control runs at both design time and run time. So as soon as you drop the control on the form, it will fill the tree view. Problem is, the nodes will be serialized to InitializeComponent(). Take a look at the Designer.cs file for your form, you'll find them back there. When you run the form, the constructor runs again, doubling the list.
You need to prevent the constructor from adding the nodes at design time. That's a bit difficult to do, you'd normally use the DesignMode property but it isn't set to true yet in the constructor. Do it like this instead:
protected override void OnHandleCreated(EventArgs e) {
base.OnHandleCreated(e);
if (!DesignMode && treeView.Nodes.Count == 0) {
CreateTree(this);
}
}
Or do it explicitly by adding a public method that you call in the form's constructor or OnLoad method. Which is rather wise, you might want to catch exceptions. Always likely when you tinker with the file system.

Categories