This is really frustrating me. I'm new to C Sharp so looking for some assistance. My Save/Save As is totally fubar.
Two questions really:
How do I save changes to an existing file without popping a save dialog? If I click save it pops a dialog which is fine so I save it, then make some changes and click Save again it pops a dialog rather than just saving the file to the name already given.
How do I show the filename rather than the full path in the save as dialog? It shows as File Name: C:\Users\username\desktop\save\filename.xml
This is in MainForm.cs.
private void biFileSave_Click(object sender, EventArgs e)
{
// Save diagram
EditorForm editForm = this.ActiveDiagramForm;
if (editForm != null)
{
if (!editForm.HasFileName)
{
if (this.saveEditorDialog.ShowDialog(this) == DialogResult.OK)
{
this.ActiveDiagram.SaveSoap(this.saveEditorDialog.FileName);
}
}
else
{
this.ActiveDiagram.SaveSoap(this.saveEditorDialog.FileName);
}
}
private void biFileSaveAs_Click(object sender, EventArgs e)
{
// Save As diagram
EditorForm editForm = this.ActiveDiagramForm;
if (editForm != null)
{
if (editForm.HasFileName)
{
this.saveEditorDialog.FileName = editForm.FileName;
}
if (this.saveEditorDialog.ShowDialog(this) == DialogResult.OK)
{
this.ActiveDiagram.SaveSoap(this.saveEditorDialog.FileName);
string strFileName = this.saveEditorDialog.FileName;
}
}
}
This is in EditForm.cs
public string FileName
{
get
{
return this.fileName;
}
set
{
this.fileName = value;
this.Text = Path.GetFileNameWithoutExtension(this.fileName);
}
}
public bool HasFileName
{
get
{
return (this.fileName != null && this.fileName.Length > 0);
}
}
EDIT:
Thank you for helping me on this so quickly! My Save works as expected now, however it introduced a strange issue with Save As (code above).
If I open a file (test.xml) that I have saved, then click Save As (name it test2.xml) it saves to the new file. BUT, when I open that test.xml again and make changes and click Save it saves those changes to the test2.xml. Very strange...any ideas?
Where in code is FileName set? From the sample you've posted, I don't see it being set anywhere, but perhaps it is elsewhere. This may work:
private void biFileSave_Click(object sender, EventArgs e)
{
// Save diagram
EditorForm editForm = this.ActiveDiagramForm;
if (editForm != null)
{
if (!editForm.HasFileName)
{
if (this.saveEditorDialog.ShowDialog(this) == DialogResult.OK)
{
this.ActiveDiagram.SaveSoap(this.saveEditorDialog.FileName);
editForm.FileName = this.saveEditorDialog.FileName;
}
}
else
{
this.ActiveDiagram.SaveSoap(this.saveEditorDialog.FileName);
}
}
1) The Save dialog box will simply return the file path the user wishes to save to. Using this path, you can then perform your save function. If you want to save to the current document, simply skip the dialog box and perform your save function with a cached version of the chosen path.
For example, in your form, have a variable:
string currentFilePath = "";
When the user first opens a Save Dialog Box, fill that variable with the path the user chose.
The next time the user saves (instead of save as), perform a check:
if(!String.IsNullOrEmpty(currentFilePath))
//save method using currentFilePath as the path to save to
2) You need to set the FileName somewhere. You can then use Path.GetFileName on the FileName to get just the name and extension.
Related
So what original program I wrote was display pdf file list on comboBox from c:\temp location. But then, I wanted to give user an option to change folder so I created another form called Form2. This Form2 only opens when user press button from Form1 and it closes when user hit save button in Form2. So, I wrote code in Form2. btnSDS opens filepath and displays the path on textBox. How do I make Form1 to get folder location from Form2?
Process
user starts program and form 1 opens and grabs pdf file name from default folder.
user wants to change default folder so he clicks admin button from form 1 and it opens form 2 which is admin form.
user changes default folder setting of folder 1 from folder 2 and closes folder 2.
default folder setting changes in folder 1.
when user opens folder 2 again, default folder setting remains in textBox in folder 2.
// Form2
private void btnSDS_Click(object sender, EventArgs e)
{
var folderBrowserDialog1 = new FolderBrowserDialog();
// Show the FolderBrowserDialog.
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string folderName = folderBrowserDialog1.SelectedPath;
textBoxSDSLocation.Text = folderName;
}
}
// Form1
private void Form1_Load(object sender, EventArgs e)
{
DirectoryInfo test = new DirectoryInfo(#"c:\temp"); //Assuming Test is your Folder
FileInfo[] Files = test.GetFiles("*.pdf"); //Getting Text files
comboSDS.DataSource = Files;
comboSDS.DisplayMember = "Name";
}
private void comboSDS_SelectedIndexChanged(object sender, EventArgs e)
{
//axAcroPDF2.LoadFile(#"C:\temp\" + comboSDS.Text);
//axAcroPDF2.src = #"C:\temp\" + comboSDS.Text;
axAcroPDF2.LoadFile(#"Form2.textBoxSDSLocation.Text" + comboSDS.Text);
axAcroPDF2.src = #"Form2.textBoxSDSLocation.Text" + comboSDS.Text;
axSetting();
}
Actually you need to design a dialog form.
There is a predefined dialog for choosing a Folder in Windows Form project; It's called FolderBrowserDialog this is a sample code for that:
privatevoid BrowseFolderButton_Click(object sender, EventArgs e) {
FolderBrowserDialog folderDlg = newFolderBrowserDialog();
folderDlg.ShowNewFolderButton = true;
// Show the FolderBrowserDialog.
DialogResult result = folderDlg.ShowDialog();
if (result == DialogResult.OK) {
textBox1.Text = folderDlg.SelectedPath;
Environment.SpecialFolder root = folderDlg.RootFolder;
}
}
You can Set Default path using this code:
folderDlg .SelectedPath = //myFolder;
If you didn't want to use this default. you can build your own Dialog. In Form2:
public partial class Form2:Form
{
public string SelectedPath {get; set;}
private SelectPath_Click(object sender, EventArgs e)
{
// if path is a valid path {
SelectedPath = txtBoxPath.text;
this.DialogResult = DialogResult.OK;
this.Close();
// } else { CloseForm or Display an Error or ... }
}
}
this is pretty clear that i added a Button to the second form. you may want to choose another way.
you can use your codes like FolderBrowserDialog (SampleCode):
Form2 FolderDialog = new Form2();
if (FolderDialog.ShowDialog() == DialogResult.OK)
{
/// Set New Path
Foo.Text = FolderDialog.SelectedPath;
}
else
{
// User Didn't selected a Valid path or he closed your form without response.
}
I created a windows form that displays and image as a Logo. I was able to browse and display an image to the PictureBox with this code:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "jpg (*.jpg)|*.jpg|bmp (*.bmp)|*.bmp|png (*.png)|*.png";
if (ofd.ShowDialog() == DialogResult.OK && ofd.FileName.Length > 0)
{
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.Image = Image.FromFile(ofd.FileName);
}
}
I want the placed image saved in that PictureBox to be displayed every time the Form is called. What code do I need to write in order to do that?
On the load event of the form you can set the image of the picture box. By going to project settings, Resources tab, you can add an image as a Resource and reference it using the ProjectNamespace.Resources.NameOfResource.
You need a special kind of pictureBox that shows the logo. Let's call this a LogoBox. If you make this a user control you can use Visual Studio Toolbox to add it to your controls.
In Visual Studio:
Open the project where the LogoBox is to be used, or put it in a DLL, so it can be used by several executables.
Menu: Project - Add User Control, Name it LogoBox
Use the Toolbox to add a PictureBox to the user control.
Change the Dock style of picture box to DockStyle.Fill
Use properties to add an event handler for the Load Event, let's call it OnLoad.
Your LogoBox class will need a property to change the image that will be used as a logo. I use the same function as PictureBox.Image, but call it Logo:
[BindableAttribute(true)]
public Image Logo
{
get {return this.pictureBox1.Image;}
set
{
this.pictureBox1.Image = image;
}
}
This code is not enough: the next time you load this LogoBox you want it to load its last set Logo. The esiest method is to save the last set image in a file, because then you know certain that if the user of your LogoBox deletes the original image after setting it you still have your own saved copy.
You'll need a filename for the file. User project properties - settings to create a filename.
Make it a string property with application scope (it will never change)
Name: LogoFileName
Value: think of something nice. Logo.Img?
.
[BindableAttribute(true)]
public Image Logo
{
get {return this.pictureBox1.Image;}
set
{
this.pictureBox1.Image = image;
image.Save(Properties.Settings.Default.LogoFileName)
}
}
Finally load the image when your LogoBox is loaded:
private void OnFormLoading(object sender, EventArgs e)
{
var img = Image.FromFile(Properties.Settings.Default.LogoFileName);
this.pictureBox1.Image = img;
}
Don't use this.Logo = img, because that will save the image again which is a waste of time.
The only thing to do is error handling if the logo file does not exist.
Then lets have a static thing.
Within your form, implement a static paths for your image..say
public string prg_form_image
{
get { return "myimage.jpg"; }
}
public string prg_image_path
{
get { return this.AppDomain.CurrentDomain.BaseDirectory + "image\\"; }
}
private string myImage
{
get
{
return File.Exists(prg_image_path + prg_form_image)
? prg_image_path + prg_form_image
: prg_image_path + "default.jpg";
}
}
public Image img
{
get { return Image.FromFile(prg_image_path + prg_form_image); }
}
private void SetImage()
{
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.Image = img;
}
private void Form_Load(object sender, EventArgs e)
{
SetImage();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "jpg (*.jpg)|*.jpg|bmp (*.bmp)|*.bmp|png (*.png)|*.png";
if (ofd.ShowDialog() == DialogResult.OK && ofd.FileName.Length > 0)
{
if(File.Exists(prg_image_path + prg_form_image))
{
File.Delete(prg_image_path + prg_form_image);
}
if(!Directory.Exists(prg_image_path)) { Directory.Create(prg_image_path); }
Image imgIn = Image.FromFile(ofd.FileName);
imgIn.SaveAs(prg_image_path + prg_form_image);
SetImage();
}
}
Notes : Folder name image should exists along-side your executable program. a default.jpg should also exist inside the folder image.
I am developing an add-in for outlook 2010.
Basically, I have a button on my ribbon that takes the selected email, and saves it to a text file. If the email contains a certain subject then the save is done automatically to a hard coded file path. If not, a windows form is opened asking the user to enter a filepath.
When the user has selected a path, and clicked 'OK' the save takes place and then the form closes... but then it re-opens... it seems to be creating a new instance of it or something... if I click 'Cancel' or 'X' it closes, but I can't see why it's not closing properly the first time.
Below is my code
//This is myRibbon.cs
private void btn_SaveFile_Click(object sender, RibbonControlEventArgs e)
{
//other code
if (subject = "xyz")
{
//other code
textFile.Save();
}
else
{
MyPopup popup = new MyPopup();
popup.ShowDialog();
}
}
//This is MyPopup.cs
private void btnOK_Click(object sender, EventArgs e)
{
var filePath = txtFilePath.Text;
if (!string.IsNullOrWhiteSpace(filePath))
{
SaveEmailToText(filePath);
this.Close();
}
else
{ //show message box with error }
this.Close();
}
private static void SaveEmailToText(string filePath)
{
//other code
textFile.Save();
}
I have simplified this quite a bit so its easier to read.
Any help would be greatly appreciated.
Consider to use OpenFileDialog instead of your popup form
Use your popup (or file dialog) only for getting file name
Keep email saving code in one place (otherwise you will have duplicated code)
Verify DialogResult of dialog form, before processing further
Forms are disposable - using statement will dispose them automatically
Do not close dialog form - set it's DialogResult property instead
Here is refactored code:
private void btn_SaveFile_Click(object sender, RibbonControlEventArgs e)
{
string filePath = defaultPath;
if (subject != "xyz")
{
using(MyPopup popup = new MyPopup())
{
// user can close popup - handle this case
if (popup.ShowDialog() != DialogResult.OK)
return;
filePath = popup.FilePath;
}
}
SaveEmailToText(filePath);
}
private void SaveEmailToText(string filePath)
{
//other code
textFile.Save();
}
And your popup, which should be replaced with OpenFileDialog:
private void btnOK_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(FilePath))
{
//show message box with error
DialogResult = DialogResult.Cancel;
return;
}
// you can assign default dialog result to btnOK in designer
DialogResult = DialogResult.OK;
}
public string FilePath
{
get { return txtFilePath.Text; }
}
So i am creating a simple program that keeps track of my notes from work. The code i have works fine but i was thinking today about a different way to make it work and still achieve the same end result.
Currently the user types everything into several textboxes and checks a few checkboxes they click the save button and all the information plus some predetermined formatting is put into a text file and then they click the copy button and the textfile is read and output to the notes_view textbox so they can ensure the notes are formatted properly and it also copies to the clipboard.
Now what i would like it to do is as the user is typing in each textbox it will output automatically to the notes_view textbox and also the same with the checkboxes(needs to keep the formatting and predetermined lines of text as well) and then the user can just push one button that will copy it to the clipboard without having to use the file to store the information.
I am hoping this would be as simple as my program currently is but just going a different way to get the same end result.
I am rather new to C# and programming in general so any ideas on how to do this and where i should begin please let me know. Also i do understand this will essentially require an entire rewrite of my code.
Here is the current complete code for my program as is.
public partial class notes_form : Form
{
public notes_form()
{
InitializeComponent();
}
private void save_button_Click(object sender, EventArgs e)
{
//Starts the file writer
using (StreamWriter sw = new StreamWriter("C:\\INET Portal Notes.txt"))
{
string CBRSame = cust_btn_text.Text;
if (cbr_same.Checked)
{
cust_callback_text.Text = CBRSame;
}
//Writes textboxes to the file
sw.WriteLine("**Name: " + cust_name_text.Text);
sw.WriteLine("**BTN: " + cust_btn_text.Text);
sw.WriteLine("**CBR: " + cust_callback_text.Text);
sw.WriteLine("**Modem: " + cust_modem_text.Text);
//Statements to write checkboxes to file
string checkBoxesLine = "**Lights:";
foreach (Control control in pnlCheckBoxes.Controls)
{
if (control is CheckBox)
{
CheckBox checkBox = (CheckBox)control;
if (checkBox.Checked && checkBox.Tag is string)
{
string checkBoxId = (string)checkBox.Tag;
checkBoxesLine += string.Format("{0}, ", checkBoxId);
}
}
}
//Newline for checkboxes
sw.WriteLine(checkBoxesLine);
//Continues textboxes to file
sw.WriteLine("**Troubleshooting: " + tshooting_text.Text);
sw.WriteLine("**Services Offered: " + services_offered_text.Text);
sw.WriteLine("**Other Notes: " + other_notes_text.Text);
sw.Flush();
}
}
//Button that will pull all the text from the text file and then show it in the notes textbox and also push to clipboard
private void generate_button_Click(object sender, EventArgs e)
{
//Loads the reader
StreamReader streamreader = new StreamReader("C:\\INET Portal Notes.txt");
//Reads the text from the INET Portal Notes.txt
notes_view_text.Text = "";
while (!streamreader.EndOfStream)
{
string read_line = streamreader.ReadToEnd();
notes_view_text.Text += read_line + "\n";
}
streamreader.Close();
//Copies text to clipboard for pasting into INET
Clipboard.SetText(notes_view_text.Text);
}
//Button to reset entire form
private void reset_form_button_Click(object sender, EventArgs e)
{
//Reset checkboxes panel
try
{
foreach (Control ctrl in pnlCheckBoxes.Controls)
{
if (ctrl.GetType() == typeof(CheckBox))
((CheckBox)ctrl).Checked = false;
}
//resets textboxes
cust_name_text.Clear();
cust_btn_text.Clear();
cust_callback_text.Clear();
cust_modem_text.Clear();
tshooting_text.Clear();
services_offered_text.Clear();
other_notes_text.Clear();
notes_view_text.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
I've not looked closely at your code, but I'd imagine you can simply hook to a TextChanged (or similar) property, then call the same code you were calling for your Save process.
Update the save process to use an in-memory stream (rather than writing to disk), or re-write it to use something more "fitting" for your new scenario eg a stringbuilder as was already suggested.
Does that help?
Ok I am going to try this again. I got more information now. I understand I can not use open and save dialogs and there is no database. So I am still kinda lost cause I was shown how to do it with open and save dialogs before. I am going to put what I am suppose to do and then so far the code I have. The code I have I have to build off and add too. I will also show what I am suppose to add to it. I am just trying to find the best way to understand this cause right now I am not. I am still new and I know the last couple days people have been trying to help me understand and then I was told it wasnt with the open and save dialog. Here is what I am suppose to do.
•Add a textbox named txtFilePath <--- already have that
•Add a button next to the above textbox that says “Load” (name it appropriately)<-already have that
•Add a button that says “Save” (name it appropriately) <-- already have this
•When thebutton “Load” is clicked, read the file specified in the textbox
(txtFilePath: Absolute path not relative) and add the objects found
within to the listbox<--- Not understanding
•When the user clicks the “Save” button, write the selected record to
the file specified in txtFilePath (absolute path not relative) without
truncating the values currently inside<-- not understanding
Here is the one part of code I have:`
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void addButton_Click(object sender, EventArgs e)
{
EditDialog newEmployeeDialog = new EditDialog();
if (newEmployeeDialog.ShowDialog() == DialogResult.OK)
{
employeeList.Items.Add(newEmployeeDialog.StaffMember);
}
}
private void deleteButton_Click(object sender, EventArgs e)
{
if (employeeList.SelectedIndex == -1)
return;
if (MessageBox.Show("Really delete this employee",
"Delete", MessageBoxButtons.YesNo,
MessageBoxIcon.Question)
== DialogResult.Yes)
{
employeeList.Items.Remove(
employeeList.SelectedItem);
}
}
private void editButton_Click(object sender, EventArgs e)
{
if (employeeList.SelectedIndex == -1)
return;
int employeeNum = employeeList.SelectedIndex;
EditDialog newEmployeeDialog = new EditDialog();
newEmployeeDialog.StaffMember =
(Employee)employeeList.SelectedItem;
if (newEmployeeDialog.ShowDialog() == DialogResult.OK)
{
employeeList.Items.RemoveAt(employeeNum);
employeeList.Items.Insert(employeeNum, newEmployeeDialog.StaffMember);
employeeList.SelectedIndex = employeeNum;
}
}
private void employeeList_SelectedIndexChanged(object sender, EventArgs e)
{
if (employeeList.SelectedIndex != -1)
{
Employee currentEmployee = (Employee)employeeList.SelectedItem;
firstName.Text = currentEmployee.FirstName;
lastName.Text = currentEmployee.LastName;
jobTitle.Text = currentEmployee.JobTitle;
}
else
{
firstName.Text = lastName.Text = jobTitle.Text = "";
}
}
`
Now I know you can not see the button click but I do have them mark. I know when you use open and save how it works. How I can go about this? I would use stream writer right.I understand that the user will type the path into the textbox and when the user hits load, it will load the file that they are specified. Now I am just trying to understand a code to be able to word this right.
would it be something like this:
String filePath = this.txtFilePath.Text;
since I need to name the textbox txtFilePath. I know some of you might say this is simple but when you are first learning it don't seem that simple. I have been trying something to help me understand since I do my college from home. Thank you for reading hoping to hear from you guys.
Update: Would it be something like this
Reading a file
private void Load_Click(object sender, EventArgs e)
{
StreamReader myReader = new StreamReader(C:\\")
txtFilePath.Text = my reader.read to end();
myReader.Close();
}
then there is writing a file
{
StreamWriter myWriter = new StreamWriter("C:\\test.txt", true);
myWriter.Write("Some text");
myWriter.WriteLine("Write a line");
myWriter.WriteLine("Line 2");
myWriter.Close();
}
If this is correct then I have to get it where if the file is not there for the notepad to pop up so they can add it then they can save it without deleting anything out the file or files.
Assuming the file contains a list of employee names, you should be able to load them into your listbox using something like this:
var filepath = txtFilePath.Text;
if (File.Exists(filepath))
{
var lines = File.ReadAllLines(filepath);
foreach (var line in lines)
employeeList.Items.Add(line);
}
Then assuming you want to add a new employee name to the file that the user just entered into the listbox:
var filepath = txtFilePath.Text;
if (File.Exists(filepath))
using (var sw = File.AppendText(filepath))
sw.WriteLine((string)employeeList.Text);
else
using (var sw = File.CreateText(filepath))
sw.WriteLine((string)employeeList.Text);
This hasn't been tested, but it should work nearly as-is...