I have this code but it's not working. I've tried several different versions but nothing is working. I'm a newbie and still don't understand everything.
OpenFileDialog filedialog = new OpenFileDialog();
private void button3_Click(object sender, EventArgs e)
{
filedialog.ShowDialog();
filedialog.FileOk += filedialog_FileOk;
}
void filedialog_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
using (StreamReader myStream = new StreamReader(filedialog.FileName))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = myStream.ReadLine()) != null)
{
listBox1.Items.Add(line);
}
}
}
I think there is a requirement for to much plain text in this editor.
You're adding the event handler after the call to ShowDialog() has returned. Move it to before and it might work.
According to the documentation, FileOK event occurs when Open or Save button is clicked.
You are attaching the event handler inside the click.
You might want to do it on page load or somewhere before the click occurs.
Eg :
OpenFileDialog filedialog = new OpenFileDialog();
protected void Page_Load(object sender, EventArgs e)
{
filedialog.FileOk += filedialog_FileOk;
}
private void button3_Click(object sender, EventArgs e)
{
filedialog.ShowDialog();
}
void filedialog_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
using (StreamReader myStream = new StreamReader(filedialog.FileName))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = myStream.ReadLine()) != null)
{
listBox1.Items.Add(line);
}
}
}
Related
This is the code for my windows form. The goal of the form is to be able to preview a pdf on the application and then chose a folder with a drop down that you would like to copy the file to (this is what a "house" refers to in the code). This is a little project for work to make it simpler to organize files that get sent to the company. The listBox works populating with all the pdfs and the preview window works as well (this is the axAcroPDF component). But when hitting the send button to copy the file it says the file is being used by another process.
public partial class Form1 : Form { public Form1() { InitializeComponent();
}
string selectedPDF = "";
string selectedHouse = "";
DirectoryInfo currentPDF;
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "PDF Files(*.pdf) |*.pdf;";
openFileDialog1.ShowDialog();
if(openFileDialog1.FileName != null)
{
axAcroPDF1.LoadFile(openFileDialog1.FileName);
}
}
private void refreshBTN_Click(object sender, EventArgs e)
{
DirectoryInfo dinfo = new DirectoryInfo(#"C:\Users\bkamide\Desktop\ExamplePDFS");
FileInfo[] smFiles = dinfo.GetFiles("*.pdf");
foreach (FileInfo fi in smFiles)
{
pdfList.Items.Add(Path.GetFileName(fi.Name));
}
}
private void pdfList_SelectedIndexChanged(object sender, EventArgs e)
{
string firstSelectedItem = pdfList.SelectedItem.ToString();
selectedPDF = firstSelectedItem;
DirectoryInfo dinfo = new DirectoryInfo(#"C:\Users\bkamide\Desktop\ExamplePDFS\" + firstSelectedItem);
currentPDF = dinfo;
}
private void btnSend_Click(object sender, EventArgs e)
{
openFileDialog1.Reset();
axAcroPDF1.EndInit();
var sourceFile = new FileInfo(currentPDF.FullName);
var dest = Path.Combine(#"C:\Users\bkamide\Desktop\ExamplePDFS\", selectedHouse, sourceFile.FullName);
sourceFile.CopyTo(dest, true);
}
private void cbHouse_SelectedIndex(object sender, EventArgs e)
{
selectedHouse = cbHouse.SelectedIndex.ToString();
}
}
I tried in the send method to reset the openFileDialog and axAcroPDF (not sure if I did that right) to see if those were the processes that could be using the file. I also tried restarting my computer to make sure nothing in the background was using it as well. I also did try the using method but I was not quite sure how to implement it within this.
How can I delete from a text file in Winforms?
My aim is to delete a selected text from a text box and it can also be deleted in my text file.
Specifically, my need is that if the user delete the text from a text box it also be deleted from text file.
My code is:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog of = new OpenFileDialog();
of.ShowDialog();
textBox1.Text = of.FileName;
}
private void button2_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(textBox1.Text);
textBox2.Text = sr.ReadToEnd();
sr.Close();
}
private void button3_Click(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter(textBox1.Text, true);
sw.WriteLine(textBox2.Text);
sw.Close();
}
private void button4_Click(object sender, EventArgs e)
{
textBox2.SelectedText = "";
string selectedText = "theTextYouWantToDelete";
string fileContent = File.ReadAllText(#"C:\demo\demo.txt");
File.WriteAllText(#"C:\demo\demo.txt",
fileContent.Replace(selectedText, ""));
}
private bool SelectedText(char arg)
{
throw new NotImplementedException();
}
}
As far as I understand it, you should simply be able to write
private void button4_Click(object sender, EventArgs e) {
File.WriteAllText(#"C:\demo.txt", textBox2.Text, ""));
}
This will replace the contents of your file with the current contents of the textbox. Assuming the user has already deleted the needed text from the textbox, it should work correctly.
See the documentation for File.WriteAllText fore more info.
This will replace the selectedText with an empty string
string selectedText = textBox2.Text;
string fileContent = File.ReadAllText(#"C:\demo.txt");
File.WriteAllText(#"C:\demo.txt", fileContent.Replace(selectedText, ""));
I am creating a console application that will take names as an input and will store it in a text file and then i want to retrieve the names beginning with A.
The console application has two textboxes and two buttons. By hitting button1 the text entered in the textbox1 will be copied in the text file, and by clicking button2 U would like to retrieve the name beginning with A and display it in textbox2.
private void button1_Click(object sender, EventArgs e)
{
TextWriter txt = new StreamWriter("d:\\demo.txt");
txt.Write(textBox1.Text);
txt.Close();
}
private void button2_Click(object sender, EventArgs e)
{
textBox2.Text = File.ReadAllText("d:\\demo.txt");
}
I know how to retrieve the entire data of the text file by using
textBox2.Text = File.ReadAllText("d:\\demo.txt");
Please help me to retrieve the names beginning with A.
Change Write to WriteLine and then you can read each name as a separate line. When you do, check the first letter with StartsWith. If it starts with an a, append it to textbox2 using +=:
private void button1_Click(object sender, EventArgs e)
{
TextWriter txt = new StreamWriter("d:\\demo.txt");
txt.WriteLine(textBox1.Text);
txt.Close();
}
private void button2_Click(object sender, EventArgs e)
{
string line;
System.IO.StreamReader file = new System.IO.StreamReader(#"d:\\demo.txt");
while((line = file.ReadLine()) != null)
{
if (line.ToLower().StartsWith("a"))
{
textBox2.Text += " " + line;
}
}
}
You didn't provide required details but are you looking for something like that; (writing the texts as lines to a file and reading it)
private void button1_Click(object sender, EventArgs e)
{
TextWriter txt = new StreamWriter(#"d:\\demo.txt", append: true);
txt.WriteLine(textBox1.Text);
txt.Close();
}
private void button2_Click(object sender, EventArgs e)
{
var lines = File.ReadAllLines(#"d:\\demo.txt").Where(x => x.StartsWith("A"));
textBox2.Text = string.Join(",", lines);
}
I am using a OpenFileDialog to Open a File i want to process in my application, but the processing takes few seconds, and during that processing time the OpenFileDialog stays visible, and it's bothering!!! i want to hide my OpenFileDialog during the processing time !
Same problem goes to the SaveFileDialog
private void ofdImportation_FileOk(object sender, CancelEventArgs e)
{
Processing(); //Takes Few Seconds
//ofdImportation remains visible during that time...
//i want to hide it...
}
thank you everybody...
if (OpenFileDialog.ShowDialog() == DialogResult.Ok)
{
// Do stuff
}
The OK and Cancel events should be for UI specific behaviour irrespective of whatever the resulting file is for.
Separation of concerns
Clicking ok gives you a file, cancel gives you say a null, then you have a class with a process method that you pass the file name from the dialog to.
It shouldn't care where the file name came from.
Think about the hurdles you'd have to leap to unit test Processing()
Assuming you have a button to open the Dialog
Solution 1 (this way the window freezes so its not really a solution, i post it anyway):
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.Ok)
{
Thread.Sleep(10000);
}
}
Solution 2 (use of BackGroundWorker, a helpful tool for async jobs):
public partial class Form1 : Form
{
BackgroundWorker bgw;
String fileUrl;
public Form1()
{
InitializeComponent();
bgw = new BackgroundWorker();
bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
}
void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
button1.Text = fileUrl;
}
void bgw_DoWork(object sender, DoWorkEventArgs e)
{
Thread.Sleep(10000);
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
var dlr = ofd.ShowDialog();
if (dlr == DialogResult.Ok)
{
fileUrl = ofd.FileName;
bgw.RunWorkerAsync();
}
}
}
edit: 'Thread.Sleep(10000)' simulates your long running process ('Processing();')
I am trying to clear the contents of a listbox when a new tab is seleced. Here is what I got, but nothing happens.
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
if (tabControl1.SelectedTab == tabControl1.TabPages["entryTab"])
{
readBox.Items.Clear();
reminderBox.Items.Clear();
}
}
Try something like this in your form load
tabControl1.Selecting += new TabControlCancelEventHandler(tabControl1_SelectedIndexChanged);
// Try this set null to DataSource
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
if (tabControl1.SelectedTab == tabControl1.TabPages["entryTab"])
{
readBox.DataSource = null;
reminderBox.DataSource = null;
}
}