|
Hi Im new to programming, im taking an online class and sometimes it takes a while for someone to get back to me.
We created a notepad program and i want the user of the program to be able to save the file and once the first initial save is saved it wont prompt the user with another pop up asking where to save the file it will automatically save it to the last place it was saved. While writing this i think i answered my other question for the save as haha =^) the Save As would just use the same save click event method.haha
The other is how would i check to see if the user has saved there file prior to closing the program.
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFile = new SaveFileDialog();
saveFile.Title = "Save File";
saveFile.Filter = "Text File|*.txt|All Files (*.*)|*.*";
DialogResult dr = saveFile.ShowDialog();
if (dr == DialogResult.OK)
{
StreamWriter sw = new System.IO.StreamWriter(saveFile.FileName);
Form activeForm = this.ActiveMdiChild;
if (activeForm != null)
{
TextBox activeText = (TextBox)activeForm.ActiveControl;
if (activeText != null)
{
sw.Write(activeText.Text);
sw.Close();
}
}
}
}
//this is my close, it works but not right if the person has saved their data it will still show the message box because it has text in the text box.
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
if (edittextBox.Text != null)
{
MessageBox.Show("Please make sure you save your data!");
}
else
{
Close();
}
}
Thanks for your Help ?=^)
modified on Friday, December 3, 2010 9:01 PM
|
|
|
|
|
All you need to do is store the value of the filename, and check to see if that value is set. If it's not, then display the dialog.
|
|
|
|
|
But be sure to clear it if the user starts a new document...otherwise the program will overwrite the old one when saving.
|
|
|
|
|
Would i do this in the private void saveToolStripMenuItem_click event?
Sorry for sounding so obtuse haha I'm a newbie
|
|
|
|
|
Basically, you get the value as soon as you've get the filename (and path). Store this as a member rather than a local variable.
|
|
|
|
|
Good Response Old Boy!
------------------------------------
I will never again mention that I was the poster of the One Millionth Lounge Post, nor that it was complete drivel. Dalek Dave
CCC League Table Link
CCC Link[ ^]
|
|
|
|
|
The traditional way is to have a "global" boolean variable indicating whether there have been any changes since the last save.
Basicially:
Saved -> false
User saves the file: Saved -> true
User types something or otherwise makes a change: Saved -> false
User saves file: Saved -> true
etc etc etc
Then just check the variable before clsoing the program. If it's false, prompt the user to save things.
|
|
|
|
|
Cool so when you say global out side of any of the components in the Form or Form1_Load, and not in one of my click events?
public partial class Form1 : Form
{
int count;
"bool Saved;"
}
private void Form1_Load(object sender, EventArfs e)
{
bool Saved;
}
im learning here hahaha
thanks for all your help =^) Ill get this sooner or latter ?=^0
|
|
|
|
|
Some people will say globals are naughty, and they're often right. In this case, not so much.
But, just to keep them happy, you don't really need a separate variable for it...if you put the filename (or an initial fake filename like "unsaved") in the title bar and append a * to it when it needs to be saved and remove it when it has been saved.
Then, instead of checking some variable, you just check the Text property of the form. If the last character is a *, then it needs to be saved.
Same principle, just cooler.
And more work for you, of course. But that's a good thing, if you really want to learn this stuff.
|
|
|
|
|
Good Answer.
Gets a 5.
------------------------------------
I will never again mention that I was the poster of the One Millionth Lounge Post, nor that it was complete drivel. Dalek Dave
CCC League Table Link
CCC Link[ ^]
|
|
|
|
|
you need both:
- a string holding the file path
- a boolean "dirty" flag
the path is set when you open an existing document or save the document; and it gets nulled at start, and when the user "clears" the document (no content => no path).
the dirty flag gets cleared any time you set the path (to null or to an actual path); and set on any change you make in the document (yes, that is in many many places in the code of a typical editor).
then, when you want to exit the app, the dirty flag tells you to ask the user: "shouldn't I save your current document first?"; same if your app can only handle one document at the time, and the user is about to open one while still holding dirty data.
And whenever the user saves without "SaveAs" (i.e. by performing "Save" or answering "yes" to "shouldn't I save ...", the path variable tells you whether you should ask for a path (if null) or use what you have already; a save through "SaveAs" always must ask for a path (and the answer gets stored in the string variable, unless cancelled).
Optionally, you could disable the "Save" menu item as long as path is null, forcing the user to use SaveAs.
Optionally again, you could have shortcut keys, and CTRL/S should do what "Save" does, i.e. ask for a path if and only if path is null. And to be top-notch, CTRL/S should even work when "Save" is disabled, i.e. when you don't have a path.
|
|
|
|
|
I usually use the same structure for this kind of things. Declare two private fields on the class (the form in this case);
bool _dirty = false;
string _filename = null;
Write the methods to open and save the file:
void Open(string filename)
{
_filename = filename;
_dirty = false;
}
void Save()
{
if (_filename != null)
Save(_filename);
else
SaveAs();
}
void Save(string filename)
{
_filename = filename;
_dirty = false;
}
void SaveAs()
{
if (dlg.ShowDialog() == DialogResult.OK)
Save(dlg.FileName);
}
Subscribe to the Closing event (when it is a Form):
void frm_FormClosing(object sender, FormClosingEventArgs e)
{
if (_dirty)
{
DialogResult dr = MessageBox.Show(this, "Do you want to save the changes?",
"Warning", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
if (dr == DialogResult.Yes)
Save();
else
e.Cancel = dr == DialogResult.Cancel;
}
}
So all you have to do is set _dirty field to true whenever there is any change. In your case, it might be in the TextChanged event of the TextBox.
|
|
|
|
|
This is so cool Thanks to all that has help with this you guys are Awesome =^)This makes learning allot more enjoyable ;^) because this stuff ant easy. haha
|
|
|
|
|
Well i think i got this thing working =^)except for one thing the save method?
I cant seem to figure out how to have it save back to its original place.
This is what i got for my save_click event
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog Save_File = new SaveFileDialog();
Save_File.Title = "File Saved";
Save_File.Filter = "Text Files|*.txt|All Files (*.*)|*.*";
DialogResult dr = Save_File.ShowDialog();
try
{
if (saveFileDialog1.FileName != "")
{
StreamWriter sw = new StreamWriter(Save_File.FileName);
sw.Write(txtBox);
sw.Close();
}
if (dr == DialogResult.OK)
{
StreamWriter sw = new StreamWriter(Save_File.FileName);
sw.Write(txtBox.Text);
sw.Close();
}
}
catch
{
SaveAs();
}
}
I know this displays a dialog box for asking where to save the file...
i also tried this to and still nothing
if (saveFileDialog1.FileName != "")
{
richTextBox1.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.PlainText);
}
else
{
evtSaveAs_Click(sender, e);
}
now should i create a Save method or is this fine? I know by creating a method i can use the same code in multiple places with out needing to write it all over again. But this is such a small app.
All you guys Rock Thanks so Much for your help ?=^)
Peace
|
|
|
|
|
Have another look at the methodology I posted in my previous answer. If you use it you will see that on your save_click event handler you only have to call Save method. If the file is new (_filename field is null) the it will call SaveAs method, asking for a file name, and if the file is not new it will save the changes with the same name it had. If you also have a SaveAs_click event handler, you should only call SaveAs method. Anyhow, I can see several mistakes on your code.
First of all, you are creating a new instance of a SaveFileDialog every time you want to save a file, but you do not dispose it at the end of the method. The best here is to add the dialog to the form at design time, dragging and dropping it from the toolbox as if you were adding any other control. This way you will only need one instance of the dialog and it will be disposed when your form gets also disposed. In my previous post this SaveFileDialog was the dlg object I used in the SaveAs method.
Once you call the ShowDialog method, the only one thing you have to check is the DialogResult object it returns. Checking for its FileName property before is a mistake, becouse if it returns a DialogResult.Ok then you can be sure its FileName property is right. In your code you have placed two consecutive if clauses, and if the user selects a filename both of them will evaluate their condition to true, so both of them will execute.
There is another important thing to pay attention. You are not disposing or closing the StreamWriter if there is an exception in the Write method. There are several ways to do this, but this is the one I like most:
try
{
using (StreamWriter sw = new StreamWriter(filename))
{
}
}
catch (Exception ex)
{
}
As I said, have another look at my previous post and make some tests with it. Once you completely understand it you will see that it is all you need and you can apply the same logic to many different applications.
|
|
|
|
|
You rock bro Thanks for your help =^)
So the _fileName field is null will mean that the file is empty or a new file. haha ill get this ?=^)
Haha... and the save dialog box would pop up twice haha thats why.
Thanks again for all your help
Now i have another question
now were importing and exporting XML files But im getting an error in the form
private int ReadInPeople()
{
XmlNodeList nodeList = m_xmlDoc.DocumentElement.ChildNodes;
foreach (XmlNode PersonNode in nodeList)
{
Person myXmlPerson = new Person();
foreach (XmlNode PersonTag in PersonNode.ChildNodes)
{
switch (PersonTag.Name)
{
"Here im getting an error asking me if i want to create a method with "FirstName" but in my Person class i just have fields and properties. So do i need to create a method for each one of my cases?"
case "firstName":
myXmlPerson.FirstName(PersonTag.FirstChild.Value);
break;
case "lastName":
myXmlPerson.LastName(PersonTag.FirstChild.Value);
break;
Ext.....
This is a snipit of my Person.cs class
private string firstName;
private string lastName;
public string MI;
private string address;
public string city;
public string state;
public string zip;
public string time;
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
public string Address
{
get { return address; }
set { address = value; }
}
public string PrintLable()
{
return firstName + " " + MI + " " + lastName + "\n" + address + "\n" + city + ", " + state + " " + zip + "\n" + time;
}
Thanks guys you rock
|
|
|
|
|
Hi, dear all,
We create an application using c#, we need to create report using Word 2007.
In the report template, I create some document variables and some field codes that will display these document variable in word file.
But if I repeat inserting this template in report because I should put this section in a loop. I got a problem, all these document variables are overwritten by the last run in the loop because of the document variable values are reset.
So I want to delete the field codes at the end of each loop so the content will not be overwirtten, but I don't know how to remove/delete word field codes from c#?
Would you please help me?
Thanks!
|
|
|
|
|
I am using XPathNavigator to sort nodes by name. Is there a method for writing the sorted nodes to the same or different file?
foreach( XPathNavigator item in navigator.Select( expr ) )
{
}
Thanks,
Mark
|
|
|
|
|
How about something like this?
static void Main(string[] args)
{
XDocument x = XDocument.Parse(sXml);
Reorder(x.FirstNode);
x.Save(newFileName);
}
private static void Reorder(XNode node)
{
var kids = (from nd in node.XPathSelectElements("*") orderby nd.Name.LocalName select nd).ToList();
if (kids.Count>1)
{
(node as XElement).ReplaceNodes(kids);
}
kids.ForEach(f => Reorder(f));
}
|
|
|
|
|
The xml is displayed in a TreeView control so alphabetical sorting by 'name' attribute was necessary. I worked out something similar to your reply and problem solved. Haven't had a prior occasion to use Linq however.
Thanks for the help!
modified on Friday, December 3, 2010 3:28 PM
|
|
|
|
|
of course not. ( there are several ways as you'd expect, heres one, not the best not the worst )
how's this ?
static void Main(string[] args)
{
string newFileName = "c:\\myfilename.xml";
XmlDocument docSource = new XmlDocument();
docSource.LoadXml(XML);
Reorder(docSource.DocumentElement);
docSource.Save(newFileName);
}
private static void Reorder(XmlNode node)
{
SortedList<string, XmlNode> childlist = SortedChildNodes(node);
node.RemoveAll();
for (int i = 0; i < childlist.Count; i++)
{
Reorder(node.AppendChild(childlist.Values[i]));
}
}
static SortedList<string, XmlNode> SortedChildNodes(XmlNode node)
{
SortedList<string, XmlNode> ret = new SortedList<string, XmlNode>();
for (int i = 0; i < node.ChildNodes.Count; i++)
{
string name = node.ChildNodes[i].Name;
XmlNode nd = node.ChildNodes[i];
ret.Add(name, nd);
}
return ret;
}
|
|
|
|
|
Hi guys.
I want to make a program which avoids every acces to p2p so you cannot use p2p networking.
How can i do that?
I write in C# and VB so both languages is good enough for me
|
|
|
|
|
You don't even need a program. Just pull out there network cable! haha
it is difficult to block because it is basically just one software connecting to another over internet on which ever port. I imaging connecting clients get host address from a server of some sort so I guess you would want to be blocking access to said server somehow, effectively rendering their p2p software useless. There are probably many other network admin type things you can do.
But it sounds like you don't have a real plan in order to implement a program for
Life goes very fast. Tomorrow, today is already yesterday.
|
|
|
|
|
Okay.
So I Guess it is not possible
|
|
|
|
|
If you find out the requirements of preventing such tool then a program may be possible. But the question is... what would it take to stop p2p software working. You such research how p2p software works and look for a clue there
Life goes very fast. Tomorrow, today is already yesterday.
|
|
|
|