How to write all textboxes content to text file using streamwritter? - c#

I am a civil engineer who is learning to code (so please don't judge). I am using streamwriter to write textboxes data to txt file but I have hundreds of textboxes. Writing texboxes name one by one is making me crazy and database is not an option. I searched internet for more than 3 hours now but couldn't find the appropriate solution.
The following code works fine but there must be a way to avoid writing all textboxes names. I would really appreciate any guideline here on how to write all textboxes content in text file?.
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
//saveFileDialog1.InitialDirectory = #"C:\";
saveFileDialog1.Title = "Save Project Files";
saveFileDialog1.DefaultExt = "txt";
saveFileDialog1.FileName = "1";
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
string pdfPath = "";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
using(StreamWriter writer = new StreamWriter(saveFileDialog1.FileName))
{
writer.WriteLine(Tb_ProjectName.Text);
writer.WriteLine(tb_ClientName.Text);
writer.WriteLine(tb_ProjectPic.Text);
writer.WriteLine(tb_AgencyName.Text);
writer.WriteLine(tb_AgencyLogo.Text);
writer.WriteLine(tb_ContractorName.Text);
writer.WriteLine(tb_ContractorLogo.Text);
}
pdfPath = saveFileDialog1.FileName;
}

David already gave the correct answer in his comment. So here written out with an additional tip:
In your code, you can iterate over all available text boxes and write their content into a file. There are two thing you have to consider. First, in which order should all textboxes be written. Second, are there any text boxes that should NOT be written into the file.
For both cases you should use the visual editor to set of all text boxes the TabIndex property to set the order in which the content should be written and you can use the property Tag to contain something to mark a text box for not being written into the file.
The code sketch would look something like this:
using(StreamWriter writer = new StreamWriter(saveFileDialog1.FileName))
{
var textBoxesToWrite = this.Controls
.OfType<TextBox>()
.Where(textBox => textBox.Tag != null)
.OrderBy(textBox => textBox.TabIndex)
foreach (var textBox in textBoxesToWrite)
{
writer.WriteLine(textBox.Text);
}
}

1: Create a panel and put all your textboxes in it.
2: Use a foreach loop to get all textboxes from this panel:
string allTextBoxContent = string.Empty;
foreach (var control in panel1.Controls)
{
if (control is TextBox textbox)
{
allTextBoxContent += textbox.Text;
}
}

Related

C# OpenFileDialog/CommonOpenFileDialog

I am working on this piece of code that is supposed to open a file dialog and put them into a textbox.
The error is that every time I select more than 1 file while running the app, I get an error in the textbox. If I select only one file, it works fine.
The code is this
private void filePickerButton_Click(object sender, RoutedEventArgs e)
{
// Create the OpenFileDialog object
OpenFileDialog dialog = new OpenFileDialog();
dialog.InitialDirectory = "C:\\Users";
dialog.Multiselect = true;
// Check to see if we have a result
if (dialog.ShowDialog() == true)
{
filePickerTextBox.Text = dialog.FileNames.ToString();
}
else
{
outputTextBox.Text = "Operation cancelled." + "\n" + outputTextBox.Text;
}
}
I am switching between dialog.Filename.ToString(); (to select one file) and dialog.Filenames.ToString(); to select multiple. When using the latter and selecting a file (whether its only one, or more that one, doesn't matter) the my text box shows System.String[]
Anyone know how to fix this?
Thx!
when you are selecting multiple files you get a array of files, as your textbox says: System.String[]
you could use:
filePickerTextBox.Text = string.join(",", dialog.FileNames);

ListView of recently opened files

I'm doing a text editor. How do I display a list of the last opened files in the RichTextBox in ListView? You can also click on the ListView string and open the file. Something like the history of opening files. Files are opened using Button (the code below).
private void buttonOpen_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Rich Text Format | *.rtf";
if (ofd.ShowDialog() == DialogResult.OK)
{
richTextBox1.LoadFile(ofd.FileName);
}
else
{
}
}
The easiest way i have done this was store all opened files within a settings string and store all recently opened files within that string with a delimiter like \n(i use this because you cant include it in a fie name so no errors are thrown).
For example, the settings string is stored like this
"C:\my file1\nC:\myFile2\nC:\my file 3"
And when adding a new file to the list
MyApp.Properties.Settings.recents = MyApp.Properties.Settings.recents + "\n" + ofd.FileName;
MyApp.Properties.Settings.Default.Save();
you then split that and use a forloop for each occurance to generate a new listview item like this
string[] recentFiles = MyApp.Properties.Settings.recents.split('\n');
foreach (string recentItem in recentFiles) { MyListView.add(recentItem); }

OpenFileDialog cuts off pre-populated file name [duplicate]

This question already has answers here:
Default name with OpenFileDialog C#?
(3 answers)
Closed 1 year ago.
I use the following to display an Open File dialog:
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.FileName = Properties.Settings.Default.Last_competition_file;
fdlg.Filter = "FS database files (*.fsdb)|*.fsdb|All files (*.*)|*.*";
fdlg.FilterIndex = 0;
if (fdlg.ShowDialog(this) == DialogResult.Cancel) return false;
(Properties.Settings.Default.Last_competition_file contains the whole path to the last file)
Problem: For a file name "c:\data\nationals_2014.fsdb", the File name field only shows "ionals_2014.fsdb".
When clicking into the File name field, and moving the cursor to the left, the remainder of the file name & path re-appears. But I'm looking for a way to make the whole file name visible from the beginning.
Note that this is not a length issue. I also tried setting path and file name separately (through OpenFileDialog.InitialDirectory), but even then only the tail end of the (now much shorter) file name was displayed.
Any ideas how to get the Open File dialog to show the full pre-populated file name from the beginning?
Caveat: This is a Kludge, not a real answer.
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.FileName = Properties.Settings.Default.Last_competition_file;
fdlg.Filter = "FS database files (*.fsdb)|*.fsdb|All files (*.*)|*.*";
fdlg.FilterIndex = 0;
fdlg.ShowHelp = true;
fdlg.HelpRequest += new System.EventHandler(HelpRequested); ;
if (fdlg.ShowDialog(this) == DialogResult.Cancel) return false;
private void HelpRequested(object sender, EventArgs e)
{
MessageBox.Show(".. is no Help", "There..");
}
The style of the Dialog reverts to an older incarnation.
Shrug. Some workarounds make me wonder about many things..
I got the same thing on windows 10 with an open file dialog set up like this:
var dialog = new OpenFileDialog{
Filter = "excel files (*.xlsx)|*.xlsx",
InitialDirectory = #"c:\temp",
FileName = #"MyFileNameExceeds14Characters.xlsx"
};
dialog.ShowDialog();
Work-arounds:
Set AutoUpgradeEnabled = false to revert to an older dialog style. But then you're stuck with the older UI.
Make sure the file name is under 14 characters long. If you don't have direct control of the file name, then run it through Path.GetFileNameWithoutExtension() to slim it down as much as possible.
Use a SaveFileDialog instead, which does not have this issue.
Inserting code:
SendKeys.Send("{HOME}");
before the line :
if (fdlg.ShowDialog(this) == DialogResult.Cancel) return false;
does the job.
Found a good answer on another thread:
c# Sending keyboard commands to another window / process
This does a good job of fixing the file name display.
I use a timer anyway in order to make sure that dialog is centered on active screen. Once the dialog is displayed:
IntPtr handle = FindWindowByCaption(IntPtr.Zero, dialogTitle));
SetForegroundWindow(handle);
SendKeys.SendWait("{HOME}");
SendKeys.Flush();

Multi-line textbox shows mult-line string as One-Line

I am making a program where you enter an item's name and it's description. Then you add it to a listbox and after you are done you can save all the items to a 'txt' file. (Using StreamWriter). This program also has an edit button that allows you to edit the description in the listbox by removing it first from the listbox and then showing it back in the textbox (, so you can edit it)
If the description is multi-line, it will successfuly show it multi-line when I select it in the listbox and click the edit button that will show it back in the textbox. BUT if I save all the items in the listbox to a file first. And then open up the file again so it load the items back into the listbox. And then clicking the edit button...
The multi-line description will show as a one-line description in the textbox.
I am not sure why - but I've also made a label that will show the exact string that the textbox is suppose to show and the label is showing it multi-lined while textbox isn't!
The string is definitely multi-line but the multi-line textbox is showing it one-line after loading the items back into the listbox using StreamReader.
Example of the multi-line string: (named "theString1")
This is line 1
This is line 2
Using the following code: TextBox1.Text = theString1; this appears in the text box:
This is line1This is line2
But if I use the same code with a label. It will show it correctly.
If someone can explain to me why this is happening I will be more than happy. I just need an explanation.
Thanks in advance.
---[More info]---
Just so you know. I came up with this code myself so it is probably set-up all wrong.
I will be happy if you tell me a better way to do this.
I am using a list to store the description text + the item name. I seperated these two using '`' .And splited the string (see code).
This is the code that happens when you click the edit button. It removes the item from
the listbox and shows it in the textbox so you can edit it and add to listbox again:
int index = listBox.SelectedIndex;
itemName.Text = listBox.SelectedItem.ToString();
var descVar = descList.ElementAt(index).Split('`');
string theString1 = descVar[1];
TextBox1.Text = theString1;
This is how it saves it to a file:
FileDialog save = new SaveFileDialog();
save.Title = "Save information...";
save.DefaultExt = "Text File|*.txt";
save.Filter = "Text File|*.txt";
if (save.ShowDialog() == DialogResult.OK)
{
StreamWriter sw = new StreamWriter(save.FileName);
foreach (string s in listBox.Items) //This writes the names of item names.
{
sw.WriteLine(s);
}
sw.WriteLine("`1`"); //I use this to seperate the item names from description.
foreach (string s in descList) //This writes the descriptions that are stored in a list named "descList".
{
sw.WriteLine(s);
sw.WriteLine("``"); //I use this to seperate descriptions from each other because they are multi-line.
}
sw.WriteLine("`2`"); //Just something so I know where it ends. :D
sw.Close();
}
else
{
}
And this is how it loads: (This can definitely be better!)
FileDialog load = new OpenFileDialog();
load.Title = "Load information...";
load.DefaultExt = "Text File|*.txt";
load.Filter = "Text File|*.txt";
if (load.ShowDialog() == DialogResult.OK)
{
List<string> loadDesc = new List<string>(); //Don't ask you will see why
descList.Clear();
while (listBox.Items.Count > 0) //This removes all items in the listbox to load new ones.
{
int index = 0;
listBox.Items.RemoveAt(index);
descList.Clear();
itemName.Text = "";
}
StreamReader rw = new StreamReader(load.FileName);
for (; true; )
{
string read = rw.ReadLine();
if (read == "`1`") //When it reaches the separator I made it stops reading.
{
break;
}
else
{
listBox.Items.Add(read);
}
}
for (; true; )
{
string read = rw.ReadLine();
if (read == "`2`")
{
break;
}
else
{
loadDesc.Clear();
loadDesc.Add(read);
for (; true; ) //Please tell me if this can be done differently.
{
string read2 = rw.ReadLine();
if (read2 != "``") //This will keep reading the whole description until it reaches the separator.
{
loadDesc.Add(read2); //Adds each line into the list I created.
}
else
{
break;
}
}
string oneBigString = string.Join("\n", loadDesc); //This basically converts all strings in a list into one string.
descList.Add(oneBigString); //And this finally add the string to the main list from where it then loads.
}
}
}
else
{
}
I believe that is it.
If there is anything else you need - tell me.
string oneBigString = string.Join("\n", loadDesc); is where the issue is.
Use Environment.NewLine instead of \n
I'm also just going to go over a couple of things that could be improved with your code (there are a lot, but I just want to cover a couple).
while (listBox.Items.Count > 0) //This removes all items in the listbox to load new ones.
You don't need to iterate over every element in the listbox to remove it. You can just do listBox.clear()
Also, using break to get out of loops is generally bad practice. This should be written as...
for (; true; )
{
string read = rw.ReadLine();
if (read == "`1`") //When it reaches the separator I made it stops reading.
{
break;
}
else
{
listBox.Items.Add(read);
}
}
this
string read = rw.ReadLine()
while(read != "`1`")
{
listBox.Items.Add(read);
read = rw.ReadLine()
}
but theres more, what if 1 is never found in the file? It would crash your program, so you also need to check if there is more data to be read...
string read = rw.ReadLine()
while(read != "`1`" && !sw.EndOfStream) // Make sure you're not at the end of the file
{
listBox.Items.Add(read);
read = rw.ReadLine()
}

C# How to copy and paste files from a Data Set using a button?

I have a button, that button saves XML files, those XML files consist of files from a certain Data Set, How can i use that same button to copy the files listed, and paste them in a different directory.
Code for my button:
private void buttonSaveXML_Click(object sender, EventArgs e)
{
SaveFileDialog saveFile = new SaveFileDialog();
saveFile.Filter = "XML Files|*.xml";
saveFile.Title = "Save a Xml File";
saveFile.InitialDirectory = #"C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\fxo\NewVersion";
saveFile.ShowDialog();
if (saveFile.FileName != "")
{
FileStream fs = (FileStream)saveFile.OpenFile();
dsVersions.WriteXml(fs);
}
Edit: I need to incorporate a code with this button that will copy and paste ALL the files in a dataGrid and be able to save an xml file while doing so.
You can use the FileSystem.CopyFile Method to do the job.

Categories