The following piece of code reads a .txt file and reads a certain line that starts with the characters declared in the code.
private void rb_point1_CheckedChanged(object sender, EventArgs e)
{
string line;
StreamReader file = new StreamReader(ccpath);
while ((line = file.ReadLine()) != null)
{
if (line.StartsWith("point01:"))
{
message = (line.Split(':')[1]);
txtb_message.Text = message;
}
}
}
private void rb_point2_CheckedChanged(object sender, EventArgs e)
{
string line;
StreamReader file = new StreamReader(ccpath);
while ((line = file.ReadLine()) != null)
{
if (line.StartsWith("point02:"))
{
message = (line.Split(':')[1]);
txtb_message.Text = message;
}
}
}
private void rb_point3_CheckedChanged(object sender, EventArgs e)
{
string line;
StreamReader file = new StreamReader(ccpath);
while ((line = file.ReadLine()) != null)
{
if (line.StartsWith("point03:"))
{
message = (line.Split(':')[1]);
txtb_message.Text = message;
}
}
}
private void rb_point4_CheckedChanged(object sender, EventArgs e)
{
string line;
StreamReader file = new StreamReader(ccpath);
while ((line = file.ReadLine()) != null)
{
if (line.StartsWith("point04:"))
{
message = (line.Split(':')[1]);
txtb_message.Text = message;
}
}
}
private void rb_point5_CheckedChanged(object sender, EventArgs e)
{
string line;
StreamReader file = new StreamReader(ccpath);
while ((line = file.ReadLine()) != null)
{
if (line.StartsWith("point05:"))
{
message = (line.Split(':')[1]);
txtb_message.Text = message;
}
}
}
The issue I have is that I have 50 Radio Buttons which means 50 times this code needs repeating. I have no ideas on how to shorten this down or at least make is easier on the eyes
A first improvement would be a method that does what you want and accepts a parameter for the difference. Like so:
private void rb_point1_CheckedChanged(object sender, EventArgs e)
{
ReadLineAndDisplayText("point01:");
}
private void ReadLineAndDisplayText(string lineStart)
{
string line;
StreamReader file = new StreamReader(ccpath);
while ((line = file.ReadLine()) != null)
{
if (line.StartsWith(lineStart))
{
message = (line.Split(':')[1]);
txtb_message.Text = message;
}
}
}
Like that you already get rid of most duplication.
Next is to not have a new rb_point1_CheckedChanged() method for each radio button, but assign the same method to all of the buttons. You can then use sender to identify the radio button that was pressed. In the designer, you can e.g. assign the Tag, so your code is like this:
private void anyRadioButton_CheckedChanged(object sender, EventArgs e)
{
RadioButton radio = (RadioButton) sender;
string lineStart = (string) radio.Tag;
ReadLineAndDisplayText(lineStart);
}
Like that you'll end up with only 2 methods.
Related
So, I am a newbie in C# and I have this listbox in my program that is duplicating the contents that it's reading from a textbox.
Whenever I start my program, it loads the contents of the save.txt file to the listbox, but when it does that, it loads a duplicate of all the save.txt content. I tried clearing the listbox before loading the contents but it's not working.
Here's my code:
private void readList()
{
string line;
listBox.Items.Clear(); //I tried to clear the listbox but it's not working
listBox.Items.AddRange(File.ReadAllLines(#"C:\Users\Paul.DESKTOP-HGGDG1D\Desktop\My C# apps\MyAgenda\MyAgenda\MyAgenda\bin\Debug\save.txt"));
using (StreamReader sr = new StreamReader("save.txt"))
while ((line = sr.ReadLine()) != null)
{
listBox.Items.Add(line);
}
}
public myAgenda()
{
InitializeComponent();
readList();
}
private void add_btn_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(add_txt.Text))
{
MessageBox.Show("Error: Please enter a value");
}
else
{
holder = add_txt.Text;
listBox.Items.Add(ctr + " " + holder);
ctr++;
add_txt.Text = " ";
}
}
private void button1_Click(object sender, EventArgs e)
{
const string sPath = "save.txt";
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath);
foreach (var item in listBox.Items)
{
SaveFile.WriteLine(item);
}
SaveFile.Close();
Application.Exit();
}
You are filling listbox two time in readlist method i.e.
First Time :
listBox.Items.AddRange(File.ReadAllLines(#"C:\Users\Paul.DESKTOP-HGGDG1D\Desktop\My C# apps\MyAgenda\MyAgenda\MyAgenda\bin\Debug\save.txt"));
Second Time :
using (StreamReader sr = new StreamReader("save.txt"))
while ((line = sr.ReadLine()) != null)
{
listBox.Items.Add(line);
}
You can remove either of one approach to fill up the content. First approach is better to use for readability.
You are copying the content twice on your listBox.
Try to do this:
private void readList()
{
string line;
listBox.Items.Clear();
//Comment out this line then put the File Directory on the StreamReader
//listBox.Items.AddRange(File.ReadAllLines(#"C:\Users\Paul.DESKTOP-HGGDG1D\Desktop\My C# apps\MyAgenda\MyAgenda\MyAgenda\bin\Debug\save.txt"));
using (StreamReader sr = new StreamReader(#"C:\Users\Paul.DESKTOP-HGGDG1D\Desktop\My C# apps\MyAgenda\MyAgenda\MyAgenda\bin\Debug\save.txt"))
while ((line = sr.ReadLine()) != null)
{
listBox.Items.Add(line);
}
}
I have these list in notepad 1-5 with names
Arman
Betty
Charlie
Delson
Ezra
Situation: when i click the button the name will appear in the richtext one by one until the end of the number. I have this codes yet It's not yet working.
private void button5_Click(object sender, EventArgs e)
{
string file_name = "\\test1.txt";
file_name = textBox1.Text + file_name; //textBox1.Text is my path
int counter = 0;
string line = "";
// Read the file and display it line by line.
StreamReader file = new StreamReader(file_name);
while ((line = file.ReadLine()) != null)
{
richTextBox2.Text = (line);
counter++;
}
file.Close();
// Suspend the screen.
richTextBox2.Text = line; //I use richtext for displaying the output
}
Try this;
private void button1_Click(object sender, EventArgs e)
{
using (StreamReader sr = File.OpenText("yourPath"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
textBox1.Text = line;
this.Refresh();
Thread.Sleep(1000);
}
}
}
Edit 1:
Sorry I made for textbox. Check this;
private void button1_Click(object sender, EventArgs e)
{
using (StreamReader sr = File.OpenText("yourPath"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
richTextBox1.Text += line + "\n";
this.Refresh();
Thread.Sleep(1000);
}
}
}
Since you don't specify if you are writing this application for WPF or WinForms I will assume you are using WPF's RichTextbox. Here is an example:
using (StreamReader sr = new StreamReader("SampleInput.txt"))
{
string line = string.Empty;
while ((line = sr.ReadLine()) != null)
{
rbResult.Document.Blocks.Add(new Paragraph(new Run(line)));
}
}
Can anybody help me write multiple lines to Text file and then search a specific word in that file. I hope the code will use (File.Exists) if any.... thank you in advance
My Code:
private void button1_Click(object sender, EventArgs e)
{
int counter = 0;
string line;
string lines = textBox1.Text;
StreamWriter file2 = new StreamWriter("D:\\test.txt",true);
file2.WriteLine(lines);
file2.Close();
string text = textBox1.Text;
StreamReader file3 = new StreamReader("D:\\test.txt");
while ((line = file3.ReadLine()) != null)
{
if (line.Contains(text))
{
MessageBox.Show("Name "+text+" is Found!");
textBox2.Text = text;
break;
}
counter++;
}
file3.Close();
}
thank you all .... I lastly found my Answer I modified the code as below:
private void button1_Click(object sender, EventArgs e)
{
int counter = 0;
string line;
string lines = textBox1.Text;
StreamWriter file2 = new StreamWriter("D:\\test.txt",true);
file2.WriteLine(lines);
file2.Close();
string text = textBox2.Text;
StreamReader file3 = new StreamReader("D:\\test.txt");
while ((line = file3.ReadToEnd()) != null)
{
if (line.Contains(text))
{
MessageBox.Show("Name "+text+" is Found!");
textBox2.Text = text;
break;
}
counter++;
}
file3.Close();
}
This is my code:
protected void Button1_Click(object sender, EventArgs e)
{
FileInfo SelectedFileInfo = (FileInfo)ListBox1.SelectedItem;
StreamReader FileRead = new StreamReader(SelectedFileInfo.FullName);
string CurrentLine = "";
//int LineCount = 0;
while(FileRead.Peek() != -1)
{
CurrentLine = FileRead.ReadLine();
//LineCount++;
//if(LineCount % 5 == 2)
{
ListBox2.Items.Add(CurrentLine);
}
}
FileRead.Close();
}
but throws exception about:
Cannot convert type 'System.Web.UI.WebControls.ListItem' to 'System.IO.FileInfo'
When populating the listbox, use the filename instead instead the FileInfo
Then when in Button1_Click, use ListBox1.SelectedValue to get the selected file name
protected void Button1_Click(object sender, EventArgs e)
{
ListBox2.Items.Clear();
if (ListBox1.SelectedIndex > -1)
{
string filename = ListBox1.SelectedValue;
StreamReader FileRead = new StreamReader(filename);
string CurrentLine = "";
//int LineCount = 0;
while (FileRead.Peek() != -1)
{
CurrentLine = FileRead.ReadLine();
ListBox2.Items.Add(CurrentLine);
}
FileRead.Close();
}
else
{
ListBox2.Items.Add("Please select a file first");
}
}
protected void Btn_Load_Click(object sender, EventArgs e)
{
DirectoryInfo dinfo = new DirectoryInfo(#"C:\errorlog");
FileInfo[] Files = dinfo.GetFiles("*.txt");
foreach (FileInfo file in Files)
{
ListBox1.Items.Add(file.FullName);
}
}
}
I have made a method so that when you click on Browse From File the openDialogBox appear. But it does not . What is wrong ?
This is the method that I made to Open the OpenFileDialog:
public void Lista()
{
string[] col2 = new string[dataGridView1.Rows.Count];
for (int i = 0; i < dataGridView1.Rows.Count; i++)
if (col2[i] == "Browse From File...")
{
DialogResult result2 = openFileDialog2.ShowDialog();
if (result2 == DialogResult.OK)
{
// filename = openFileDialog1.FileName;
}
}
}
This is the method where I call the method Lista.
private void button1_Click(object sender, EventArgs e)
{
// opens window **BROWSE**
openFileDialog1.Title = "Choose File CSV ";
string filename = "";
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
filename = openFileDialog1.FileName;
textBox1.Text = filename;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader(textBox1.Text);
stringforData = file.ReadLine();
while ((line = file.ReadLine()) != null)
{
//read inside the table
fileList.Add(line.Split(';'));
}
file.Close();
this.ToDataGrid();
this.Lista();
}
}
DataGridView by only having one editing control for all the rows. Here's how I handled a similar situation, First try a delegate to the EditControlShowing event
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
OpenFileDialog ofd = new OpenFileDialog();
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.Columns.Add("ID", "Product ID");
DataGridViewComboBoxColumn comboxboxCol = new DataGridViewComboBoxColumn();
comboxboxCol.HeaderText = "Type";
comboxboxCol.Items.Add("Obj1");
comboxboxCol.Items.Add("Obj2");
comboxboxCol.Items.Add("Obj3");
dataGridView1.Columns.Add(comboxboxCol);
dataGridView1.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(Grid_EditingControlShowing);
}
void Grid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
ComboBox combo = e.Control as ComboBox;
if (combo != null)
{
// the event to handle combo changes
EventHandler comboDelegate = new EventHandler(
(cbSender, args) =>
{
ofd.ShowDialog();
});
// register the event with the editing control
combo.SelectedValueChanged += comboDelegate;
}
}
}
}
Hope this will solve your Issue