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...
Related
I am working on a project and i have to perform a task in that project that i have to print/find data from a MS Access Database 2016 File through a specific text or keyword i'll try everything but can't solve my problem so after trying everything i decided to post my problem here to get some help to solve it.
I attached my code you can see that but that code doesn't performing any thing and i got a error while try to search anything the error is
A first chance exception of type 'System.FormatException' occurred in mscorlib.dll
Additional information: Input string was not in a correct format.
If there is a handler for this exception, the program may be safely continued.
This is the error I am facing while perfroming the task.
namespace Vechile_Registration_System
{
public partial class Verification : Form
{
public Verification()
{
InitializeComponent();
}
private void Verification_Load(object sender, EventArgs e)
{
}
private void btnsearch_Click(object sender, EventArgs e)
{
searchDataBase();
}
private void searchDataBase()
{
string strsearch = txtsearch.Text.Trim().ToString();
StringBuilder sb = new StringBuilder();
vehicleBindingSource.Filter = string.Format("[Registration No] LIKE '%{0}%'", strsearch);
string strFilter = sb.ToString();
vehicleBindingSource.Filter = strFilter;
if (vehicleBindingSource.Count != 0)
{
dataGridView1.DataSource = vehicleBindingSource;
}
else
{
MessageBox.Show("No Records Found. \n The Vehcile may not register or you have enter wrong Registration Number.");
}
}
private void button1_Click(object sender, EventArgs e)
{
this.Hide();
Form1 MMenu = new Form1();
MMenu.ShowDialog();
}
}
}
PLEASE READ CAREFULLY:
You've deleted a very important line and because of this, no data is being loaded into your data source.
We are making the first change in Verification.cs file. Change the Verification_Load exactly like this:
private void Verification_Load(object sender, EventArgs e)
{
vehicleTableAdapter.Fill(vehicleDataSet.Vehicle);
// If you want the grid view to show no data at the beginning
// Uncomment the following line
// vehicleBindingSource.Filter = "1 = 0";
}
You've somehow managed to remove the searchbutton_Click event handler.
Please apply these steps exactly as they are suggesting:
In the solution explorer double click the Verification.cs. This should open the form in design mode.
On the form, right click the SEARCH button and select Properties from the menu.
In the Properties window at the top, there are some icons. Find the "Events" icon with a thunderbolt (lightning) shape. Click this.
Now, at the very top, there is the "Click" event.
Be very careful with typing and enter btnsearch_Click
And that's all.
Hope this helps.
Please mark as answer if it does
**** ORIGINAL ANSWER ****
This should solve your problem.
Please use exactly this code.
private void searchDataBase()
{
string strsearch = txtsearch.Text.Trim().ToString();
StringBuilder sb = new StringBuilder();
vehicleBindingSource.Filter = string.Format("[Registration No] LIKE '%{0}%'", strsearch);
if (vehicleBindingSource.Count != 0)
{
dataGridView1.DataSource = vehicleBindingSource;
}
else
{
MessageBox.Show("No Records Found. \n The Vehcile may not register or you have enter wrong Registration Number.");
}
}
I want to copy some text on textbox2 to a txt file.I want to create a kk.txt file after clicking the button and need to store textbox2 text to that kk file.
Here is the code i tried but it only create kk.txt file and not storing textbox2 data.
private void button6_Click(object sender, EventArgs e)
{
//textBox4.Text +=Clipboard.GetText()+Environment.NewLine;
Clipboard.SetText(textBox2.Text);
System.IO.File.Create(#"C:/Ebaycodes/kk.txt");
string path = #"C:/Ebaycodes/kk.txt";
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.Write(textBox2.Text);
sw.Dispose();
}
}
}
could somebody help me to fix this error.
The problem is your if statement, it only runs if the file doesn't exist. You created it, so it does exist, and the if doesn't run. You can change your entire routine to this:
private void button6_Click(object sender, EventArgs e)
{
Clipboard.SetText(textBox2.Text);
File.WriteAllText(#"c:\Ebaycodes\kk.txt", textbox2.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?
I'm new for c#, and i need to write a programme with a button (clicking it to show a .txt file)
could someone give me some idea or may be an example code
thanks
Answer for WinForms:
Place textBox named tbBrowser and Button named bBrowse on form. Double-click button to create button Click handler. Place the following code in the handler:
String filename = #"C:\Temp\1.txt";
using (StreamReader rdr = new StreamReader(filename))
{
String content = rdr.ReadToEnd();
tbBrowser.Text = content;
}
See StreamReader documentation for reference.
Answer for ASP.NET would be completely different, but it's unlikely you are asking about that (at least word program in question makes me think so)
You haven't said if you wanted to use winforms, wpf or something else. Anyway, the code below will work for winforms - just add a textbox to your form:
private void button1_Click(object sender, EventArgs e)
{
// Create reader & open file
using (TextReader tr = new StreamReader(#"C:\myfile.txt"))
{
textBox1.Text += tr.ReadToEnd();
}
}
If you are creating windows form appln add a button to you form
double click the button
and in the method write the following code
private void button1_Click(object sender, EventArgs e)
{
string filePath = "give your path";
// or you can give your path in app.config and read from app.config if you want
// to change the path .
if (File.Exists(filePath))
{
StreamReader reader = new StreamReader(filePath);
do
{
string textLine = reader.ReadLine() + "\r\n";
}
while (reader.Peek() != -1);
reader.Close();
}
}
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.