Screenshot
I have a "simple" Question: How can i display the content of a selected item from a Listbox into a Textbox.
I tried it with
//string value1 = listBox1.SelectedItem.ToString();//textBox1.Text = value1;
but it will show me just the filename of the selcted item(i already find out why).
And i also tried somthing like:
//string value1 = listBox1.SelectedItem.ToString();//textBox1.Text = File.ReadAllLines(value1);
I know that i'll need the actual path of the selected file to "ReadAllLines"
And here is the Problem i have no clue how to get it, may someone can help me please.
If the file that you want to read is located relatively to the app path then use AppDomain.CurrentDomain.BaseDirectory get the app path, and then System.IO.Path.Combine to combine that path with your target relative path (or just the file name, if the file is located in the same folder as the app).
My Solution with the help from Dialecticus:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string value1 = listBox1.SelectedItem.ToString();
string path1 = System.IO.Path.Combine(dataPath, value1);
textBox1.Text = System.IO.File.ReadAllText(path1);
}
*dataPath contains the path with the actual path
string dataPath = #"C: \Users\....;
Related
i want to export my datagrid to txt file with format like this:
//inside txt file, each item on one row
item1[id],item1[name]
item2[id],item2[name]
Something like that, with each item on one row, split by a comma.
Currently my code is like this:
var directory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
var file = Path.Combine(directory, "123.txt");
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < datagrid.Items.Count; i++)
{
////////My Setting class
Setting setting= (Setting)datagrid.Items[i];
//////// I need help for the below lines with formatting
strBuilder.Append(setting.id);
strBuilder.Append(setting.name);
}
File.WriteAllText(file, strBuilder.ToString());
Also my second question is : the output directory of 123.txt file is in bin/debug folder, can i change it to the current working directory/work space of the project?
use this link for details sample export-data-from-a-datagrid or this exporting-datagrid-to-csv-without-a-gui-in-wpf
or if you want to just export use this code :
private void button_Click(object sender, RoutedEventArgs e)
{
dataGrid1.SelectAllCells();
dataGrid1.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
ApplicationCommands.Copy.Execute(null, dataGrid1);
dataGrid1.UnselectAllCells();
String result = (string)Clipboard.GetData(DataFormats.CommaSeparatedValue);
File.AppendAllText("D:\\test.csv", result, UnicodeEncoding.UTF8);
}
for path issue use "..\" how-to-navigate-a-few-folders-up
So i am attempting to teach myself C#, I have a program that I originally wrote in batch and am attempting to recreate in C# using WPF. I have a button that allows a user to set a directory, that directory selected is then displayed in a text box above a listbox which adds every subfolder, only first level, to the listbox. Now all this works fine but it writes out the entire directory path in the listbox. I have been trying to figure out how to strip the leading directory path off the list box entries for over an hour to no avail. Here is what I have so far:
private void btn_SetDirectory_Click(object sender, RoutedEventArgs e)
{
//Create a folder browser dialog and set the selected path to "steamPath"
var steamPath = new FolderBrowserDialog();
DialogResult result = steamPath.ShowDialog();
//Update the text box to reflect the selected folder path
txt_SteamDirectory.Text = steamPath.SelectedPath;
//Clear and update the list box after choosing a folder
lb_FromFolder.Items.Clear();
string folderName = steamPath.SelectedPath;
foreach (string f in Directory.GetDirectories(folderName))
{
lb_FromFolder.Items.Add(f);
}
}
Now I tried changing the last line to this, and it did not work it just crashed the program:
foreach (string f in Directory.GetDirectories(folderName))
{
lb_FromFolder.Items.Add(f.Substring(f.LastIndexOf("'\'")));
}
I am fairly certain that the LastIndexOf route is probably the right one but I am at a dead end. I apologize if this is a dumb question but this is my first attempt at using C#. Thanks in advance.
This can solve your issue
string folderName = steamPath.SelectedPath;
foreach (string f in Directory.GetDirectories(folderName))
{
// string[] strArr = f.Split('\\');
lb_FromFolder.Items.Add(f.Split('\\')[f.Split('\\').Length-1]);
}
You can use this code:
string folderName = steamPath.SelectedPath;
foreach (string f in Directory.GetDirectories(folderName))
{
lb_FromFolder.Items.Add(f.Remove(0,folderName.Length));
}
I want to mimic the functionality of the following image using Visual C#:
This I know is not a textbox or a combobox or a richtext (Maybe).
I managed to get the add function, where I get directories and I can select them:
private void button8_Click(object sender, EventArgs e)
{
this.folderBrowserDialog1.ShowNewFolderButton = false;
this.folderBrowserDialog1.RootFolder = System.Environment.SpecialFolder.MyComputer;
DialogResult result = this.folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
// the code here will be executed if the user selects a folder
string path = this.folderBrowserDialog1.SelectedPath;
}
}
How do I list them like in the image, should I write it to an ini file, or XML file, and then if so how do I list it in the box as shown.
I also need to detect the OS and have few default folders in the list.
Not quite sure what you want, but the image shows a list with a string and bool value. So you can use something like this:
public class DirOptions
{
string Path = string.Empty;
bool IncludeSubDirs = false;
}
Then you can store your data inside a List<>:
var list = new List<DirOptions>();
To detect OS:
Please see this question Get OS Version / Friendly Name in C#
Here is the application on codeplex all i did is created a new text box and trying to get path of current node selected into this text box, but i am getting extra things which i dont need at all,
Link to application,
Codeplex app
Code Line i am using is ,
TextBox1.Text = nodeCurrent.FullPath;
and output i am getting is something like this,
My Computer\C:\\Documents and Settings\Administrator\Desktop
My Computer here is Root Node, which i dont need, all i want is
C:\Documents and Settings\Administrator\Desktop
Picture added
Here is the function i am using it
private void tvFolders_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
//Populate folders and files when a folder is selected
this.Cursor = Cursors.WaitCursor;
//get current selected drive or folder
TreeNode nodeCurrent = e.Node;
string newPath = getFullPath(nodeCurrent.FullPath);
tbDirectory.Text = newPath;
//clear all sub-folders
nodeCurrent.Nodes.Clear();
if (nodeCurrent.SelectedImageIndex == 0)
{
//Selected My Computer - repopulate drive list
PopulateDriveList();
}
else
{
//populate sub-folders and folder files
PopulateDirectory(nodeCurrent, nodeCurrent.Nodes);
}
this.Cursor = Cursors.Default;
}
It looks to me like the getFullPath method in that code will do exactly what you want. It strips the MyComputer\ string and returns the rest. Write:
string newPath = getFullPath(nodeCurrent.FullPath);
add the following line in the code and it will remove recurring "\" in the path
newPath = newPath.Replace("\\\\", "\\");
I am totally new to visual C#. Whilst I can sort of manage console apps, I easily get lost when it comes to coding forms.
I am currently making an "app launcher" which reads a text file line by line. Each line is a path to a useful program somewhere else on my pc. A link label is automatically made for each path (i.e. each line) in the text file.
I would like the .Text property of the link label to be an abbreviated form of the path (i.e. just the file name, not the whole path). I have found out how to shorten the string in this way (so far so good !)
However, I would also like to store the full path somewhere - as this is what my linklabel will need to link to. In Javascript I could pretty much just add this property to linklabel like so: mylinklabel.fullpath=line; (where line is the current line as we read through the text file, and fullpath is my "custom" property that I would like to try and add to the link label. I guess it needs declaring, but I am not sure how.
Below is the part of my code which creates the form, reads the text file line by line and creates a link label for the path found on each line:
private void Form1_Load(object sender, EventArgs e) //on form load
{
//System.Console.WriteLine("hello!");
int counter = 0;
string line;
string filenameNoExtension;
string myfile = #"c:\\users\jim\desktop\file.txt";
//string filenameNoExtension = Path.GetFileNameWithoutExtension(myfile);
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader(myfile);
while ((line = file.ReadLine()) != null)
{
//MessageBox.Show(line); //check whats on each line
LinkLabel mylinklabel = new LinkLabel();
filenameNoExtension = Path.GetFileNameWithoutExtension(line); //shortens the path to just the file name without extension
mylinklabel.Text = filenameNoExtension;
//string fullpath=line; //doesn't work
//mylinklabel.fullpath=line; //doesn't work
mylinklabel.Text = filenameNoExtension; //displays the shortened path
this.Controls.Add(mylinklabel);
mylinklabel.Location = new Point(0, 30 + counter * 30);
mylinklabel.AutoSize = true;
mylinklabel.VisitedLinkColor = System.Drawing.Color.White;
mylinklabel.LinkColor = System.Drawing.Color.White;
mylinklabel.Click += new System.EventHandler(LinkClick);
counter++;
}
file.Close();
}
So, how can I store a full path as a string inside the linklabel for use in my onclick function later on?
Many thanks in advance
Jim
Use Tag property, then it can be retrieved by casting first parameter of LinkClick (object sender) to LinkLabel:
mylinklabel.Tag = line;
in LinkClick:
((LinkLabel)sender).Tag
Store full path in LinkLabel Tag Property, you could get the full path like
string full path = myLinkLabel.Tag.ToString();
Hope this help.
Reading from a text file isn't pretty good. You could read from a xml file, then it would be very simple to create the linklabels and other stuff. A xml sample:
<Programs>
<Program Name="Calculator" Path="calc">
<Program Name="Notepad" Path="C:\blabla">
</Programs>
Then you could make a name variable, and a path variable and load the values from the file. But if your a beginner, then a txt file will also do, but it's a pain to load each line's values from the file.