C# Copy TextBox and the settings i've used copy aswel - c#

Basically, I have around 40 textBoxes on a form, which I want to copy, the settings are on the first boxes I have, but I copied the first row and the save settings I used did not copy, so only the first row of boxes save the text. The code is:
textBox1.Text = WindowsFormsApplication12.Properties.Settings.Default.Method.ToString();
textBox2.Text = WindowsFormsApplication12.Properties.Settings.Default.Price.ToString();
textBox3.Text = WindowsFormsApplication12.Properties.Settings.Default.PerHour.ToString();
textBox4.Text = WindowsFormsApplication12.Properties.Settings.Default.Viable;
try
{
WindowsFormsApplication12.Properties.Settings.Default.Method = textBox1.Text;
WindowsFormsApplication12.Properties.Settings.Default.PerHour = Convert.ToInt32(textBox3.Text);
WindowsFormsApplication12.Properties.Settings.Default.Total = Convert.ToInt32(textBox4.Text);
WindowsFormsApplication12.Properties.Settings.Default.Viable = textBox40.Text;
WindowsFormsApplication12.Properties.Settings.Default.Save();
}
catch (FormatException ex)
{
MessageBox.Show("Error : Make sure you have only entered numbers! \n\n" + ex.ToString());
}

Related

C# - Using loop to open dialog box

I'm trying to make a program that loads a configuration file from another application.
If the file exists, it loads it and displays a message, but if the configuration file is not valid, it displays an error message and then opens a dialog box to load the correct file. But if the user reloads the wrong file, the same dialog box should appear again but that's when my code fails.
Similarly, if the file did not exist from the beginning, it displays a dialog box to load the file, but if it is given to cancel the dialog box or an incorrect file is selected again, my code fails.
I know that the solution would be to use loops but I'm not sure how to structure it.
Pd: searchfile() is my function to open dialog box and readconfig() is my function to read config file of another application.
strfilenamepath = #"C:\Users\test\dogs.exe.config";
if (File.Exists(strfilenamepath))
{
onlyFilename = System.IO.Path.GetFileName(strfilenamepath);
textBox1.Text = onlyFilename;
try
{
string[] valores = readConfig(strfilenamepath);
MessageBox.Show(valores[0] + valores[1] + valores[2]);
}
catch (Exception ex)
{
MessageBox.Show("Error loading config file." + ex.Message);
searchFile();
onlyFilename = System.IO.Path.GetFileName(strfilenamepath);
textBox1.Text = onlyFilename;
string[] valores = readConfig(strfilenamepath);
MessageBox.Show(valores[0] + valores[1] + valores[2]);
}
}
else
{
searchFile();
onlyFilename = System.IO.Path.GetFileName(strfilenamepath);
textBox1.Text = onlyFilename;
try
{
readConfig(strfilenamepath);
string[] valores = readConfig(strfilenamepath);
MessageBox.Show(valores[0] + valores[1] + valores[2]);
}
catch (Exception ex)
{
MessageBox.Show("Error loading config file." + ex.Message);
searchFile();
onlyFilename = System.IO.Path.GetFileName(strfilenamepath);
textBox1.Text = onlyFilename;
string[] valores = readConfig(strfilenamepath);
MessageBox.Show(valores[0] + valores[1] + valores[2]);
}
}
It is easier to design it if you extract the reading logic to another method that handles exceptions and returns a Boolean to signal the success and the computed result. The TryDoSomething pattern does exactly this.
In pseudo code
public bool TryReadConfig(string path, out string[] valores)
{
valores = null;
try {
valores = read the values;
return true;
} catch {
Display message;
return false;
}
}
The main loop in pseudo code
strfilenamepath = #"C:\Users\test\dogs.exe.config";
while (true) {
if (File.Exists(strfilenamepath) && TryReadConfig(strfilenamepath, out var valores)) {
Do something with the valores;
break;
}
var ofd = new OpenFileDialog{ ... };
if (ofd.ShowDialog() == DialogResult.OK) {
strfilenamepath = ofd.Filename;
} else {
break; // The user canceled the operation.
}
}
You can do something like this:
try
{
//Code to try open the file to memory
}
catch (Exception ex)
{
while (true)
{
MessageBox.Show(#"Select an valid file");
var path = searchFile();
if (string.IsNullOrWhiteSpace(path))
continue;
try
{
//Code to try open the file to memory
}
catch (Exception ex2)
{
MessageBox.Show(#"The selected file is not valid");
continue;
}
break;
}
}

how do i start with fresh with a new file

I catch an exception in my code for a wrong file type. Then i would like to change my file and use the correct file. How do i close the execption to look fresh at the new file and process it.
below is my code. one is a main function. the second is a called function.
main function.
//data file process button
private void button9_Click(object sender, EventArgs e)
{
try
{
panel1.Visible = false; // File paths (Admin Access))
panel3.Visible = true; // File process status
label6.Visible = true; // label - File process status
panel4.Visible = false; // Admin authenticate
InitializeFile();
ParseListFileData();
ListArrayFileData();
CleanDesiredData();
GetRRData();
GetLecoData();
//cleanup();
textBox5.Text += "All RR & Leconum data processing from file - " + textfilename + " completed." + "\r\n";
textBox5.Text += "Please click EXIT to close HORIBA program" + "\r\n";
}
catch(IndexOutOfRangeException)
{
//cleanup();
textBox5.Text += "Bad File" + "\r\n";
datafilepath = "";
textBox5.Text += "Select correct file" + "\r\n";
}
}
The Called Function ParseListFileData();
public void ParseListFileData()
{
//Opens file and uses for processing
System.IO.StreamReader sr = new
System.IO.StreamReader(datafilepath);
try
{
//while loop to read file till end of file
while (!sr.EndOfStream)
{
//split data in file into differend fields
var Row = sr.ReadLine();
var values = Row.Split(',');
ColmnA.Add(values[0]);
ColmnB.Add(values[1]);
ColmnC.Add(values[2]);
ColmnD.Add(values[3]);
ColmnE.Add(values[4]);
ColmnF.Add(values[5]);
ColmnG.Add(values[6]);
ColmnH.Add(values[7]);
ColmnI.Add(values[8]);
ColmnJ.Add(values[9]);
ColmnK.Add(values[10]);
ColmnL.Add(values[11]);
ColmnM.Add(values[12]);
ColmnN.Add(values[13]);
}
sr.Close();
sr.Dispose();
}
catch (IndexOutOfRangeException e)
{
sr.Close();
sr.Dispose();
datafilepath = "";
//cleanup();
//print(e.Message.("Error encountered");
textBox5.Text += "File type not correct or missing data in file "+ e + "\r\n";
}
}
As soon as i select a new good working file, the old exception seems closed, but the old file still remains in use and shows an exception at another function. Even though i i use dispose() to close the streamreader resources.
How can i start fresh with a new file.
Im not sure what exactly is the problem, is the file handle not closed.
I see a problem with your code: you try and catch, but only on a specific exception, say you get an ArgumentException, this will not be caught, instead you can use try{}catch{}finaly{}
try
{
/blabla
}
catch (IndexOutOfRangeException e)
{
datafilepath = "";
//cleanup();
//print(e.Message.("Error encountered");
textBox5.Text += "File type not correct or missing data in file "+ e + "\r\n";
}
finaly
{ //this codes always runs wether exception or not.
sr.Close();
sr.Dispose();
}
alternative and easier solution is to use using (which closes disposables automatically when done):
using(var sr = new System.IO.StreamReader(datafilepath);) {
//try catch in here. even is something goes horribly wrong. StreamReader = fileHandle will be closed.
}

Save a file and name it at the "Same" time (NAudio), improving the Accuracy

I want to make a wavefile, and write data to it, and i want the filename to be time it began.
I know hot to write to the wave file using Wavewriter, and i know how to name it to the current time, the problem is however, to make it name the file as close as possible to the moment the audio is written.
Currently i have something like this:
private void SaveReceivedAudio(string recieve)
{
try
{
using (var folderBrowser = new FolderBrowserDialog())
{
DialogResult result = folderBrowser.ShowDialog();
if (result == DialogResult.OK)
{
path = Path.GetFullPath(folderBrowser.SelectedPath) + (Path.DirectorySeparatorChar);
waveWriter = new NAudio.Wave.WaveFileWriter(path + recieve + "- " + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss-fff") + ".wav", new WaveFormat(48000, 16, 2));
waveWriterYour = new WaveFileWriter(path + Environment.UserName + " - " + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss-fff") + ".wav", new WaveFormat(48000, 16, 2));
Record = true;
Recording.ForeColor = System.Drawing.Color.Green;
Recording.Text = "Recording";
}
else
{
Record = false;
Recording.ForeColor = System.Drawing.Color.Red;
Recording.Text = "Not Recording";
}
}
}
catch (Exception e)
{
MessageBox.Show("SaveReceivedAudio: " + e.Message);
}
}
So as you can see i am clicking a button, choosing a directory, then it will create 2 files in this example at the moment it's created, then change Record to True.
However, this isn't accurate at all, it's probably fairly close, but it all depends on how it's executed.
Now, while i am saving another thread is on loop with the current audio data, which looks like this:
private void RecordingQueueThread()
{
byte[] AudioData;
byte[] AudioData2;
while (connect)
{
try
{
if (Queue.TryTake(out AudioData, 300))
{
if (AudioData.Length == 0)
break;
else
{
if (Record)
{
waveWriter.Write(AudioData, 0, AudioData.Length);
waveWriter.Flush();
TestTimer += AudioData.Length;
}
}
}
if (RecQueue.TryTake(out AudioData2, 300))
{
if (AudioData.Length == 0)
break;
else
{
if (Record)
{
waveWriterYour.Write(AudioData, 0, AudioData.Length);
waveWriterYour.Flush();
}
}
}
}
catch (Exception e)
{
MessageBox.Show("Recording: " + e.Message);
}
}
}
Or well, maybe not in a loop, but there are 2 threads feedins this.
But as you can see, as there are 2 threads(or more) that work independetly, the audio will not be at the time of the Date i wrote earlier, it will be a bit later, and it can vary depending on, well, many thing, process time etc.
Which makes this a problem.
Best thing is if i can write the time exactly when the first data is written, i don't know how to do that however.
Any ideas?

Export directly to pdf

I am using two stored procedures, one for main report and another for subreport. Below is the code.
private void LoadSalesOrderReport()
{
string Type = gvQuotationDetails.Rows[QuoteIndex].Cells["Type"].EditedFormattedValue.ToString();
FilePath = ConfigurationManager.AppSettings["EMP_IMG_PATH"].ToString() + "\\" + ValQuoteID.ToString() + ".pdf";
DeleteExistingFile(FilePath);
try
{
AccountsPayableMaster objAPM = new AccountsPayableMaster();
QuotationReport obj = new QuotationReport();
objReportDocument.Load(Application.StartupPath + #"\rptQuotationReport.rpt");
obj.crysQuotationReport.LogOnInfo = objAPM.ConnectionDetails("SD_SalesOrderReport;1");
obj.crysQuotationReport.LogOnInfo = objAPM.ConnectionDetails("SD_GetBatchReportDetails;1");
obj.crysQuotationReport.ReportSource = objReportDocument;
objReportDocument.SetParameterValue("#QuoteID", ValQuoteID);
objReportDocument.SetParameterValue("Type", "-" + Type.ToUpper() + "-");
objReportDocument.SetParameterValue("#QuoteID", ValQuoteID, objReportDocument.Subreports[0].Name.ToString());
string[] Print = objAPM.GetPrintDetails();
SetPrintParameters(objReportDocument, Print);
obj.Show();
objReportDocument.ExportToDisk(ExportFormatType.PortableDocFormat, FilePath);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
OpenPdfFile();
}
private void OpenPdfFile()
{
try
{
Process.Start(FilePath);
}
catch (Exception ex)
{
MessageBox.Show("Please install MicrosoftOffice/Pdf Reader to view files", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
The code is working fine.But the problem is. when i click the button in front end to show the pdf directly.The crystal report form is also displayed and I know the reason as I am using obj.Show in my code.I tried to comment it but it throws an error.Can any one advise changes in my code to directly display the pdf and not the crystalreport form.

Saving a currently opened file without prompts

I am experiencing a problem with saving a currently opened file without it popping up the dialog asking what name to save it under.
To clarify myself a little more, I open a .txt file and work with it, then would like to just click 'Save' and it save the file without popping up a 'Save As' dialog box.
Here is my save code:
private void SaveFile()
{
SaveFileDialog fileChooser = new SaveFileDialog();
fileChooser.Title = "Choose Save Location";
fileChooser.Filter = "Text Files (*.txt)|*.txt";
fileChooser.OverwritePrompt = false; //Removes warning
DialogResult result = fileChooser.ShowDialog();
if (result == DialogResult.Cancel)
{
return;
}
try
{
string fileName = fileChooser.FileName;
output = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
fileWriter = new StreamWriter(output);
foreach (Employee emp in employee)
{
fileWriter.WriteLine(emp.Firstname + "," + emp.Lastname + "," + emp.Position + "," + emp.Bmonth + "," + emp.Bday + "," + emp.BYear + "," + emp.Salary + "," + emp.Hiremonth + "," + emp.Hireday + "," + emp.Hireyear);
}
fileWriter.Close();
output.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
fileWriter.Close();
output.Close();
}
}
Everything works great as far as saving it to a .txt file and loading it back in, it's just that popup that irks me.
The fileChooser object is a SaveFileDialog object. You're causing it to display by calling:
DialogResult result = fileChooser.ShowDialog();
If you don't want to show the dialog, just omit the fileChooser code and instead use:
string fileName = strAlreadyKnownFileName;
I'd firstly save the full path of the opened file in some variable lets say:
private string filepath = "path/to/my/file";
Then you need to create a button and call it i.e. "Save" double click on the button and write this simple code to save whatever you want to the current opened file:
as simple as that...
EDIT:
private void SaveFile()
{
//do your loop and stuff in here and finally write your text to the file using this
File.WriteAllText(filepath, yourtexttobesaved);
}

Categories