Add a string property to a visual c# linklabel? - c#

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.

Related

How to display a specific line at the top of a RichTextBox

I'm pulling the content from a text file into a RichTextBox. I've got the RichTextBox set up to where it only shows 6 lines at a time. I've got a search method that finds the text I need within the RichTextBox, but what I am needing it to do is display 6 specific lines. Each "item" in my text file consists of 6 lines. No matter which of the six lines the search method finds the text on, I need the RichTextBox to only display the 6 lines of each "item" with the currently selected "found" text remaining highlighted.
I've gotten it working reasonably well thanks to a few code examples I've pull from this site. But every now and then, it doesn't work entirely well, and am looking for some advice from a fresh set of eyes looking at my code and perhaps even be told an easier/more efficient way to go about it. But here is my code so far. Thanks in advance!
try
{
string s = txtFindPlaylistEntry.Text;
rtxEditPlaylistEntry.Focus();
findPosEntry = rtxEditPlaylistEntry.Find(s, findPosEntry, RichTextBoxFinds.None);
// Jump to the line we need.
int count = rtxEditPlaylistEntry.GetLineFromCharIndex(findPosEntry);
count = (count - (count % 6)) + 1; // Must be divisible by 6 then plus 1
rtxEditPlaylistEntry.SelectionStart = rtxEditPlaylistEntry.Find(rtxEditPlaylistEntry.Lines[count]);
rtxEditPlaylistEntry.ScrollToCaret();
rtxEditPlaylistEntry.Select(findPosEntry, s.Length);
findPosEntry += txtFindPlaylistEntry.Text.Length;
}
catch
{
MessageBox.Show("No occurences found");
findPosEntry = 0;
}
As of right now, I'm attempting to use a line count with modulus plus 1 to get the line I need. Like I said, it works, just not 100% of the time and I can't figure out why.
EDIT to try to accommodate Minimal, Complete, Verifiable.
I've already posted my "find" function. Here is other related code that might be useful. First, here is my code for creating the various controls I am using.
rtxEditPlaylistEntry = new RichTextBox();
rtxEditPlaylistEntry.Location = new System.Drawing.Point(15, 90);
rtxEditPlaylistEntry.Size = new System.Drawing.Size(375, 85);
rtxEditPlaylistEntry.Multiline = true;
rtxEditPlaylistEntry.ScrollBars = RichTextBoxScrollBars.None;
Here is my button function to pull text from a file and place it into the RichTextBox.
private void btnBrowseForPlaylistToEditEntry_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "LPL Files|*.lpl";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
savedFileNameEntry = openFileDialog.SafeFileName;
txtPathToPlaylistToEditEntry.Text = openFileDialog.FileName;
}
// After finding the file, load it into the richtextbox control
using (StreamReader sr = File.OpenText(openFileDialog.FileName))
{
// Initially show the first 6 lines (IE first entry). This should be accomplished by
// the richtextbox control settings
rtxEditPlaylistEntry.Text = sr.ReadToEnd();
}
previousNextCount = 0;
}
I hope this is sufficient. If not please let me know!

How do I replace a part of a line in a text file with user input?

Here's the code.
private void SaveButton_Click(object sender, EventArgs e)
{
string textBoxText = TextBox.Text;
var lines = File.ReadAllLines(#"F:\Bioshock2SP.ini");
foreach(string line in lines)
{
if (line.Contains("VoVolume="))
{
//This is where I get confused.
string settingLine = line;
string replaceline = (line.Replace(line, textBoxText));
File.WriteAllText(#"F:\Bioshock2SP.ini", settingLine);
}
break;
}
MessageBox.Show("Setting saved!");
}
The idea is to replace part of a setting in a Settings.ini file for a game I play, using the user input of a textbox in my form. The user types in a number for example, "1.56" and then hit the Save button to replace the existing line with their input. In this case that setting is the volume.
The application runs completely fine, but after hitting save and going into the settings file my input isn't saved.
There should be a change in the way you save the file.
Save each line of the file as you get it, editing if required.
void SaveButton_Click(object sender, EventArgs e)
{
var textBoxText = TextBox.Text;
var lines = File.ReadAllLines(#"F:\Bioshock2SP.ini");
using (var file = new StreamWriter(#"F:\Bioshock2SP.ini"))
foreach(string line in lines)
{
if (line.Contains("VoVolume="))
file.WriteLine(line.Substring(0, 9) + textBoxText); // Writes something like 'VoVolume=1.56'
else file.WriteLine(line); // No editing required
}
MessageBox.Show("Setting saved!");
}
I think there are a couple of separate issues with your code:
Replace Function
string replaceline = (line.Replace(line, textBoxText));
Replace accepts a string to look for and a string to replace it with. Your first argument is 'line', so it would replace the whole line with the value in textBoxText. I assume you only want to replace a portion of the line with that value. In that case, you need to use something like line.Replace(searchString, textBoxText) where you have previously defined searchString as the text you want to replace. If you don't know what that value is, but there is a pattern, you might want to look into using regular expressions which will let you define a pattern to search and replace.
WriteAllText Function
File.WriteAllText(#"F:\Bioshock2SP.ini", settingLine);
This line will replace the entire contents of BioShock2SP.ini with the value in settingLine. There are two problems here.
One is that settingLine was the saved value before you did the replacement - so it has not included the results of your replace operation. You should use replaceline (assuming it has been correctly modified).
Even if you do that, though, the other is that File.WriteAllText will replace the whole file with the value in settingLine - which is probably not what you want. You'd be better off modifying the line in the array and using File.WriteAllLines to re-output the whole array - assuming the file has multiple lines in it.
The hints above may help you resolve this - to properly answer the question though, I'd need to see a sample of what the file looks like, and the patterns you are trying to replace.

How do I get the Bitmap name when I click the image in datagridview?

I am trying to click on an image in a datagridview and then write its image/file name into a textbox so I can access this from elsewhere.
First I try just a small app to make sure I can make it all work. A Dialog contains the dataviewgrid and I put a bitmap into it as below:
public ChooseFormat()
{
InitializeComponent();
dataGridView1[0,0].Value = new Bitmap(#"C:\a\eggs\grid_app\grid_app\bin\Debug\graphics\1L5HQ60.bmp");
}
Now I click on the image but all the things I have tried I cannot get hold of the file name. The closest I get is below but this returns "System.Drawing.Bitmap" and not the file name. I am sure this must just be a tweak here to make it work but I have tried teh few things I know and nothing is working.
void DataGridView1CellContentClick(object sender, DataGridViewCellEventArgs e)
{
txtbx_choice.Text = dataGridView1[0,0].Value.ToString();
}
Drilling into the cells's data in the debugger doesn't bring up any info on the source of it. Maybe I have overlooked something..
One simple solution is to store the filename in the cell's Tag property:
string fileName = #"C:\a\eggs\grid_app\grid_app\bin\Debug\graphics\1L5HQ60.bmp";
dataGridView1[0,0].Value = new Bitmap(fileName );
dataGridView1[0,0].Tag = fileName ;
Now you can always access it:
string displayedFile = dataGridView1[0, someRow].Tag.ToString();
I have placed a Picture Box on the same form and this how I am displaying the ImageColumn's data (an Image ) in picture box
pictureBox1.Image = (Image)dataGridView1[0, 0].Value;

Strip leading characters from a directory path in a listbox in C#

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

c# - Get a string line from a text file and show the text in a label

I'm studying C# and creating this program to learn a bit more.
My program catchs the information that you have input and save it into a text file. In this part, is alright, but I'm having issues on load the file and show the information inside it.
Example, in the program I have the text boxes for user input his family information:
Dad text box:
Mom text box:
Brother text box:
The text box input is something like:
Dad text box: MyDad
Mom text box: MyMom
Brother text box: MyBrother
When the creation process of file starts, I have in the file the output that I want:
MyDad
MyMom
MyBrother
Okay, now I need to load these informations from the file and write it in another labels, like:
Your Dad is: according to example, I want "MyDad" shown here
Your Mother is: according to example, I want "MyMother" shown here
Your Brother is: according to example, I want "MyBrother" shown here
In the click event of the button to show the informations of the file I have this to check if the file was created and, if was, read it:
string path = #"C:\Users\Hypister\Desktop\Family.txt";
if (File.Exists(path))
{
using (StreamReader sr = File.OpenText(path))
{
//Here I need the function to get the lines and show it in respective labels.
}
}
else
{
MessageBox.Show("The file doesn't exists. Data cannot be loaded.");
}
But I cannot get the line for Dad, Mother and Brother from the file to show.
I hope someone can answer this and help me to gain more knowledge.
Thanks all in advance!
I coded an example for you a good C# file reference is http://msdn.microsoft.com/en-us/library/ezwyzy7b.aspx for future reference.
there 3 textboxes 3 labels and a button all default names
here is the source code hope it helps :)
private void button1_Click(object sender, EventArgs e)
{
List<string> family = new List<string>();
family.Add(textBox1.Text);
family.Add(textBox2.Text);
family.Add(textBox3.Text);
family.ToArray();
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\Users\OEM\Desktop\stackoverflow\test.txt"))
{
foreach (string line in family)
{
file.WriteLine(line);
}
}
string[] familyout = System.IO.File.ReadAllLines(#"C:\Users\OEM\Desktop\stackoverflow\test.txt");
/* this works just fine unless you have alot of labels, the code not commented out below this works better
label1.Text = familyout[0];
label2.Text = familyout[1];
label3.Text = familyout[2];
*/
int i = 0;
foreach (Control lbl in this.Controls)
{
if (lbl is Label)
{
lbl.Text = familyout[i];
i++;
}
}
}

Categories