Random Line of Text Selector in C#
Submitted by donbermoy on Thursday, July 17, 2014 - 07:35.
This tutorial will teach you how to create a program that selects a line of text from a text file using C#.
So, now let's start this tutorial!
1. Let's start with creating a Windows Form Applicationin C# for this tutorial by following the following steps in Microsoft Visual Studio 2010: Go to File, click New Project, and choose Windows Application.
2. Next, add a button named Button1 to have the random line selector. ou must design your interface like this:
3. For Button1, have this code below to have the random line selector.
Output:
For more inquiries and need programmer for your thesis systems in any kind of programming languages, just contact my number below.
Best Regards,
Engr. Lyndon Bermoy
IT Instructor/System Developer/Android Developer/Freelance Programmer
If you have some queries, feel free to contact the number or e-mail below.
Mobile: 09488225971
Landline: 826-9296
E-mail:donbermoy@engineer.com
Add and Follow me on Facebook: https://www.facebook.com/donzzsky
Visit and like my page on Facebook at: https://www.facebook.com/BermzISware
![design](https://www.sourcecodester.com/sites/default/files/linedesign.png)
- private void Button2_Click(object sender, EventArgs e)
- {
- //display a new OpenFileDialog to allow the user to select a .txt Text file for the input of the tool.
- {
- //filter to only text file
- fo.Filter = "Text Files | *.txt";
- fo.RestoreDirectory = true;
- //have only one line to select
- fo.Multiselect = false;
- //show the dialog
- fo.ShowDialog();
- // if filename is not null
- if (fo.FileName != null)
- {
- //create a new list of string named 'lines' and read the entire text file to the list
- {
- while (sr.Peek() != -1)
- {
- lines.Add(sr.ReadLine());
- }
- }
- //Finally we get a random number using our globally available 'random' variable and output the line at the index of that random line
- int number = System.Convert.ToInt32(random.Next(lines.Count));
- MessageBox.Show(lines[number]);
- }
- }
![output](https://www.sourcecodester.com/sites/default/files/lineoutput.png)
Add new comment
- 115 views