Auto find files, pass to connection string and read - c#

Firstly, I would just like to add that I am an absolute beginner at C#, I'm doing my best to learn so I am sorry if this is a noob question, but I have hit a brick wall.
I am working on a program that when finished it will find .DBF files from a specified folder, read the file and insert into a mysql database. I am stuck pretty much at the first hurdle.
I am trying to make the program loop through each file it finds and read them.
I can't seem to be able to access the filename string from the GetFiles() Void.
Is there another way around passing the filename to the queryString rather than specifying it myself?
here is my code -
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
namespace WindowsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//OPEN PROGRAM
private void Form1_Load(object sender, EventArgs e)
{
this.richTextBox1.Text = "Waiting for commands...";
this.toolStripStatusLabel1.Text = "Waiting for commands...";
}
// FIND FILES BUTTON CLICK
private void button1_Click(object sender, EventArgs e)
{
this.richTextBox1.Text = "Looking for files...";
GetFiles();
}
// function to read files at source
private void GetFiles()
{
List<String> Myfiles = new List<string>();
string[] allFiles = System.IO.Directory
.GetFiles(#"C:\Users\74-des\Desktop\", "*.DBF");
if (allFiles.Length > 0)
{
try
{
foreach (string filename in allFiles)
{
this.richTextBox1.Text = string.Join(Environment.NewLine,allFiles);
string filenameWithoutPath = Path.GetFileName(filename);
}
}
catch (SystemException excpt)
{
this.richTextBox1.Text = excpt.Message;
}
}
}
private void ReadData()
{
this.toolStripStatusLabel1.Text = "Preparing To Read Data";
this.Refresh();
DirectoryInfo dir = new DirectoryInfo(#"C:\Users\74-des\Desktop\");
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + dir + ";Extended Properties=dBase IV";
string queryString = "SELECT * FROM " + "test4.DBF";
try
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
if (reader.IsDBNull(1))
{
this.richTextBox1.Text = "Null";
}
else
{
string DATE = reader.GetValue(0).ToString();
string TIME = reader.GetValue(1).ToString();
string CODE = reader.GetValue(2).ToString();
string item = reader.GetValue(3).ToString();
this.richTextBox1.Text = DATE + TIME + " " + CODE + " " + item;
this.Refresh();
}
}
reader.Close();
connection.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button2_Click(object sender, EventArgs e)
{
ReadData();
}
}
}

you can do the following
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
namespace WindowsApplication4
{
public partial class Form1 : Form
{
private string mDirectory; // this will hold the directory path you are working on
private string[] mFiles; // this will hold all files in the selected directory
public Form1()
{
InitializeComponent();
}
//OPEN PROGRAM
private void Form1_Load(object sender, EventArgs e)
{
this.richTextBox1.Text = "Waiting for commands...";
this.toolStripStatusLabel1.Text = "Waiting for commands...";
}
// FIND FILES BUTTON CLICK
private void button1_Click(object sender, EventArgs e)
{
this.richTextBox1.Text = "Looking for files...";
GetFiles();
}
// function to read files at source
private void GetFiles()
{
mDirectory = #"C:\Users\74-des\Desktop\"; // better to use OpenFolderDialog to choose the directory
mFiles = System.IO.Directory.GetFiles(mDirectory, "*.DBF");
if (mFiles.Length > 0)
{
try
{
foreach (string filename in mFiles)
{
this.richTextBox1.Text = string.Join(Environment.NewLine, mFiles);
string filenameWithoutPath = System.IO.Path.GetFileName(filename);
}
}
catch (SystemException excpt)
{
this.richTextBox1.Text = excpt.Message;
}
}
}
private void ReadData()
{
this.toolStripStatusLabel1.Text = "Preparing To Read Data";
this.Refresh();
string connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=dBase IV", mDirectory);
try
{
foreach (var file in mFiles)
{
string queryString = string.Format("SELECT * FROM " + "{0}.DBF", System.IO.Path.GetFileNameWithoutExtension(file));
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
if (reader.IsDBNull(1))
{
this.richTextBox1.Text = "Null";
}
else
{
string DATE = reader.GetValue(0).ToString();
string TIME = reader.GetValue(1).ToString();
string CODE = reader.GetValue(2).ToString();
string item = reader.GetValue(3).ToString();
this.richTextBox1.Text = DATE + TIME + " " + CODE + " " + item;
this.Refresh();
}
}
reader.Close();
connection.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button2_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(mDirectory))
MessageBox.Show("You should Get Files first!");
else
ReadData();
}
}
}
hope it will help you

Related

How do i pass a variable value from Console application to windows form application in C# (visual studio)

I am doing a project in which i have to send the variable data from my console application project to windows form application( i have to write that data into textbox). I am trying to pass a variable val to my form and below code is what i tried to do but passed value(num variable in windows form) is zero instead of 1 (serial.Val in console application which is passed as argument and then i am calling the form).
Can anyone please help me with that ?
This is my windows forms code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsFormsApplication2;
namespace WindowsFormsApplication2
{
public partial class Serial_comm_1 : Form
{
//private static int temp;
private DateTime Datetime;
string indata;
static SerialPort COMport;
// private static int num;
public Serial_comm_1(int num)
{
InitializeComponent();
string Port_Name = "COM3"; // Store the selected COM port name to "Port_Name" varaiable
int Baud_Rate = 9600; // Convert the string "9600" to int32 9600
COMport = new SerialPort(Port_Name, Baud_Rate);
COMport.Parity = Parity.None;
COMport.StopBits = StopBits.One;
COMport.DataBits = 8;
COMport.Handshake = Handshake.None;
COMport.RtsEnable = true;
COMport.DtrEnable = true;
TextBox_Transmit_Data.Text = num.ToString();
//try to open the port
#region
try
{
COMport.Open();
textBox_System_Log.Text = "";
}
catch (UnauthorizedAccessException SerialException) //exception that is thrown when the operating system denies access
{
MessageBox.Show(SerialException.ToString());
textBox_System_Log.Text = Port_Name + Environment.NewLine + Baud_Rate;
textBox_System_Log.Text = textBox_System_Log.Text + Environment.NewLine + SerialException.ToString();
COMport.Close();
}
catch (System.IO.IOException SerialException) // An attempt to set the state of the underlying port failed
{
MessageBox.Show(SerialException.ToString());
textBox_System_Log.Text = Port_Name + Environment.NewLine + Baud_Rate;
textBox_System_Log.Text = textBox_System_Log.Text + Environment.NewLine + SerialException.ToString();
COMport.Close();
}
catch (InvalidOperationException SerialException) // The specified port on the current instance of the SerialPort is already open
{
MessageBox.Show(SerialException.ToString());
textBox_System_Log.Text = Port_Name + Environment.NewLine + Baud_Rate;
textBox_System_Log.Text = textBox_System_Log.Text + Environment.NewLine + SerialException.ToString();
COMport.Close();
}
catch //Any other ERROR
{
MessageBox.Show("ERROR in Opening Serial PORT -- UnKnown ERROR");
COMport.Close();
}
#endregion
}
private void Button_Transmit_Data_Click(object sender, EventArgs e)
{
//Local Variables
string Port_Name = "COM3"; // Store the selected COM port name to "Port_Name" variable
int Baud_Rate = 9600; // Convert the string "9600" to int32 9600
string Data = TextBox_Transmit_Data.Text; //Store the string in Textbox to variable "Data"
COMport.ReadTimeout = 3500; //Setting ReadTimeout =3500 ms or 3.5 seconds
Console.WriteLine(COMport.IsOpen);
COMport.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
//Program1 prog = new Program1();
//If we are able to open the port
if (COMport.IsOpen == true)
{
COMport.WriteLine(Data); // Send Data
textBox_System_Log.Text = Port_Name + Environment.NewLine + Baud_Rate;
textBox_System_Log.Text = textBox_System_Log.Text + Environment.NewLine + Data + " Written to Port" + Environment.NewLine;
}
else
{
TextBox_Received_Data.Enabled = true; // Enable the Receive Groupbox
MessageBox.Show("Unable to Write to COM port ");
COMport.Close();
}
}
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
indata = sp.ReadLine();
this.Invoke(new EventHandler(display_data_event));
}
private void display_data_event(object sender, EventArgs e)
{
Datetime = DateTime.Now;
String time = Datetime.Hour + ":" + Datetime.Minute + ":" + Datetime.Second;
textBox_System_Log.AppendText(time + "\t\t\t" + indata + Environment.NewLine);
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void textBox_Received_Data_TextChanged(object sender, EventArgs e)
{
}
private void TextBox_Transmit_Data_TextChanged(object sender, EventArgs e)
{
}
}
}
This is my trail of console application:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WindowsFormsApplication2;
using System.Windows.Forms;
namespace ConsoleApplication1
{
class Program1
{
private int val;
public int Val
{
get { return val; }
set { val = value; }
}
static void Main(string[] args)
{
Program1 serial = new Program1();
serial.Val = 1;
System.Windows.Forms.Application.Run(new Serial_comm_1(serial.Val));
//Serial_comm_1 serial_form1 = new Serial_comm_1(serial.Val);
}
}
}
From your app you want to start the other app:
// Create a new Process
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo = new System.Diagnostics.ProcessStartInfo();
process.StartInfo.FileName = #"C:\Projects\Temp912\bin\Debug\Temp912.exe";
process.StartInfo.Arguments = "Test Argument";
process.StartInfo.UseShellExecute = false;
process.Start();
Now from your Windows Form App, modify the Main method:
using System;
using System.Windows.Forms;
namespace Temp912
{
static class Program
{
[STAThread]
static void Main(string[] args)
{
string arg1 = "";
if ((args != null) && (args.Length > 0))
{
arg1 = args[0];
MessageBox.Show("Arg1: " + arg1, "Arg App Started With Parameter");
}
else
{
MessageBox.Show("Arg1: N/A", "Arg App Started Without Parameter");
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
If you need to pass the parameter value(s) to your Main Form, expose a property or properties on your form, and set the value(s) before you launch the form.
Edit Per Question:
Form Code
public string MyProperty { get; set; } // change the data type to int or whatever
Than in Program.cs, instead of:
Application.Run(new Form1());
Do this:
// create an instance of your form
Form1 form1 = new Form1();
// set the property or properties
form1.MyProperty = arg1;
Then call:
// this is should work, I didn't test this like the other code
Application.Run(form1);

Access Database Assignment

I need help with my Microsoft access database assignment using C# on visual studios. I have all the code written, but I keep getting errors on the query message area in the combo box event handler. The error that I keep getting says that I have an issue with the query expression by the zip code table and INNER JOIN area.
Here is the code -
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace Final_Programming
{
public partial class customerInformationFRM : Form
{
public customerInformationFRM()
{
InitializeComponent();
}
OleDbConnection cusInfoConnection = new OleDbConnection();
string chosenCustomer;
// Method for access database connection
private void databaseConnection()
{
try
{
// Establishes where provider to go to in order to open microsoft access file
string connect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
"FinalDatabase.accdb;Persist Security Info=False;";
// Open database connection
cusInfoConnection.ConnectionString = connect;
cusInfoConnection.Open();
}
catch (Exception errMsg)
{
// Messagebox pops up if theres an error
MessageBox.Show("Error in databaseConnection method: " + errMsg.Message,
"databaseConnection method error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
// Method to fill combo box
private void fillComboBox()
{
try
{
string cusInfoQRY = "SELECT PersonalInfo.[IDnumber] FROM PersonalInfo";
// Define Adapter
OleDbDataAdapter cusNumDA = new OleDbDataAdapter(cusInfoQRY, cusInfoConnection);
cusNumDA.Fill(cusNumDS, "IDnumber");
cusNumCMB.DataSource = cusNumDS.Tables[0];
cusNumCMB.DisplayMember = "IDnumber";
cusNumCMB.ValueMember = "IDnumber";
}
catch (Exception errMsg)
{
MessageBox.Show("Error in fill combo box method: " + errMsg.Message,
"Combo box error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void customerInformationFRM_Load(object sender, EventArgs e)
{
try
{
databaseConnection();
fillComboBox();
}
catch (Exception errMsg)
{
MessageBox.Show("Error in form load: " + errMsg.Message,
"Form load error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void cusNumCMB_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
cusNumDS.Clear();
customerInfoDS.Clear();
orderInfoDS.Clear();
chosenCustomer = cusNumCMB.Text;
if (chosenCustomer != "System.Data.DataRowView")
{
string cusInfoSQL = "SELECT PersonalInfo.FirstName, PersonalInfo.LastName, PersonalInfo.PhoneNumber, " +
"PersonalInfo.EmailAddress, PersonalInfo.Address, ZipCode.City, ZipCode.State, ZipCode.Zip" +
"FROM ZipCode INNER JOIN PersonalInfo ON ZipCode.[Zip] = PersonalInfo.[Zip] where PersonalInfo.IDnumber = '" +
chosenCustomer + "'";
OleDbDataAdapter customerNumberDA = new OleDbDataAdapter(cusInfoSQL, cusInfoConnection);
customerNumberDA.Fill(customerInfoDS, "customerInfo");
DataRow customerInfoDR = customerInfoDS.Tables[1].Rows[0];
firstNameTB.Text = customerInfoDR[0].ToString();
lastNameTB.Text = customerInfoDR[1].ToString();
phoneNumTB.Text = customerInfoDR[2].ToString();
emailTB.Text = customerInfoDR[3].ToString();
addressTB.Text = customerInfoDR[4].ToString();
cityTB.Text = customerInfoDR[5].ToString();
stateTB.Text = customerInfoDR[6].ToString();
zipTB.Text = customerInfoDR[7].ToString();
string orderSQL = "SELECT OrderInfo.[OrderDate], " +
"OrderInfo.[OrderShipped], OrderInfo.[ShippingFee]FROM OrderInfo where " +
"OrderInfo.[OrderNumber] = '" + chosenCustomer + "'";
OleDbDataAdapter itemsDA = new OleDbDataAdapter(orderSQL, cusInfoConnection);
itemsDA.Fill(orderInfoDS, "order");
decimal total = 0.0m;
foreach (DataRow currentRow in orderInfoDS.Tables[0].Rows)
{
total = Convert.ToDecimal(currentRow[3]);
customerDataDGV.Rows.Add(currentRow[0].ToString(), currentRow[1].ToString(), currentRow[2].ToString(), Convert.ToString(total.ToString("C")));
totalShippingTB.Text = Convert.ToString(total.ToString("C"));
}
}
}
catch (Exception errMsg)
{
MessageBox.Show("Error in combo box event handler: " + errMsg.Message,
"Combo box error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
}

File I/O Exceptions

i am currently working on a Windows Forms App in c# which will allow the user to add or delete records. when i hit the button to display all the records written to the file the files appear, but when i try to delete by transact number i get an exception saying that "The process cannot access the the because it is being used somewhere else". i have tried putting it in a try-catch block to make sure the reader/writer will close and still not working code will be attached any help is greatly appreciated. p.s im not looking for code to finish this project just help getting by this exception and make it work like it is suppose.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MMFileIO
{
public partial class MMAssignment3 : Form
{
StreamWriter writer;
StreamReader reader;
string record = "";
public MMAssignment3()
{
InitializeComponent();
}
private void MMAssignment3_Load(object sender, EventArgs e)
{
txtFile.Text = #"c:\burnable\assignment3.txt";
if (!Directory.Exists(txtFile.Text.Substring
(0, txtFile.Text.LastIndexOf('\\'))))
MessageBox.Show("File path does not exist");
}
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
if (radNew.Checked)
writer = new StreamWriter(txtFile.Text, append: false);
else
writer = new StreamWriter(txtFile.Text, append: true);
}
catch(Exception ex)
{
if (writer != null)
writer.Close();
MessageBox.Show($"exception adding new record: {ex.Message}");
return;
}
record = $"{txtTransact.Text}::{txtDate.Text}::{txtSerial.Text}::" +
$"{txtToolPurchased.Text}::${txtPrice.Text}::{txtQty.Text}::" +
$"${txtAmount.Text}";
try
{
writer.WriteLine(record);
lblMessage.Text = ($"Record added");
txtTransact.Text = txtDate.Text = txtSerial.Text =
txtToolPurchased.Text = txtPrice.Text = txtQty.Text =
txtAmount.Text = "";
}
catch(Exception ex)
{
MessageBox.Show($"exception adding a new record: {ex.Message}");
}
finally
{
writer.Close();
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
reader = new StreamReader(txtFile.Text);
List<string> records = new List<string>();
while (! reader.EndOfStream)
{
record = reader.ReadLine();
records.Add(record);
}
if (records.Count == 0)
MessageBox.Show("No records left in file");
reader.Close();
writer = new StreamWriter(txtFile.Text, append: false);
foreach (string item in records)
{
}
}
private void btnCloseFile_Click(object sender, EventArgs e)
{
txtDataDisplay.Text = "";
reader.Close();
}
private void btnDisplay_Click(object sender, EventArgs e)
{
reader = new StreamReader(txtFile.Text);
txtDataDisplay.Text = $"{"#".PadRight(10)}\t" +
$"{"Purchase-Date".PadRight(10)}\t{"Serial #".PadRight(10)}\t" +
$"{"Manufacturing Tools".PadRight(10)}\t{"Price".PadRight(10)}\t" +
$"{"Qty".PadRight(10)}\t{"Amount".PadRight(10)}\n{"".PadRight(50)}\n";
while (!reader.EndOfStream)
{
record = reader.ReadLine();
string[] fields = record.Split(new string[] { "::" }, StringSplitOptions.None);
txtDataDisplay.Text += $"{fields[0].PadRight(10)}\t" +
$"{fields[1].PadRight(10)}\t{fields[2].PadRight(10)}\t" +
$"{fields[3].PadRight(30)}\t{fields[4].PadRight(10)}\t" +
$"{fields[5].PadRight(10)}\t{fields[6].PadRight(10)}\n";
}
reader.Close();
}

FileSystemWatcher works 3-5 times before throwing exceptions - C#

File comes in over EDI as .today. I need to change it to .txt and move it to another folder. Everything works just fine for about 3-5 files, then starts throwing exceptions. I tried handling those, but that doesn't solve the problem. I'm also getting sporadic (filename cannot be null) exceptions as well. I just can't seem to figure this out.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
using System.Security.Permissions;
namespace FileConverterService
{
class ConverterService
{
//Configure watcher & input
private FileSystemWatcher _watcher;
public bool Start()
{
_watcher = new FileSystemWatcher(#"C:\FTP_base\temp", "*.today");
_watcher.Created += new FileSystemEventHandler(FileCreated);
_watcher.IncludeSubdirectories = false;
_watcher.EnableRaisingEvents = true;
return true;
}
//Configure output creation and append file name to include .txt extension
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
private void FileCreated(object sender, FileSystemEventArgs e)
{
try
{
string dateTime = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string content = File.ReadAllText(e.FullPath);
string upperContent = content.ToUpperInvariant();
var dir = Path.GetDirectoryName(e.FullPath);
var convertedFileName = Path.GetFileName(e.FullPath) + dateTime + ".txt";
var convertedPath = Path.Combine(dir, convertedFileName);
File.WriteAllText(convertedPath, upperContent);
}
catch (IOException f)
{
if (f is IOException)
{
MessageBox.Show("Exception Caught"); //was just testing
}
}
MoveConvert();
}
//Move converted file to EDI processing folder
public static void MoveConvert()
{
try {
string dateTime = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string rootFolderPath = #"C:\FTP_base\temp\";
string moveTo = #"C:\FTP_base\INbound\inbound_" + dateTime + ".txt";
//string moveTo = #"F:\FTP_base\Office Depot\INbound\inbound_" + dateTime + ".txt";
string filesToMove = #"*.txt"; // Only move .txt
string myfile2 = System.IO.Directory.GetFiles(rootFolderPath, filesToMove).FirstOrDefault();
string fileToMove = myfile2;
//moving file
File.Move(fileToMove, moveTo);
MoveOriginal();
}
catch (IOException e)
{
if (e is IOException)
{
MessageBox.Show("File already exists."); //was just testing
}
}
}
public static void MoveOriginal()
{
try {
string dateTime = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string rootFolderPath2 = #"C:\FTP_base\temp\";
string moveTo2 = #"C:\FTP_base\archive\archive_" + dateTime + ".archive";
//string moveTo2 = #"F:\Xcelerator_EDI\OfficeDepot\DataFiles\Inbound\Archive2\archive_" + dateTime + ".archive";
string filesToMove2 = #"*.today"; // Only move .today
string myfile = System.IO.Directory.GetFiles(rootFolderPath2, filesToMove2).FirstOrDefault();
//foreach (string file in fileList)
string fileToMove2 = myfile;
//moving file
File.Move(fileToMove2, moveTo2);
}
catch (IOException e)
{
if (e is IOException)
{
MessageBox.Show("IO Exception Occurred"); //was just testing
}
}
}
//Stop Service control
public bool Stop()
{
_watcher.Dispose();
return true;
}
}
}
Perhaps the files are still in use. The FileSystemWatcher event is raised when a file is created, but the creating process can still be writing to it. See here for a possible solution.

Summing numbers in many TextBox and writing them to a file

This program is about inserting expenses someone is making so in the textboxes i have to insert only numbers. So I have to save all those numbers from the textboxes into a txt file, but summed. Can you help me with some ideas?
private void button2_Click_1(object sender, EventArgs e)
{
try
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(textBox1.Text + " " + textBox2.Text + " " + textBox3.Text + " " + textBox4.Text);
File.WriteAllText(fileName, sb.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Here's a robust approach to read out numbers from TextBoxes and write them to an output file:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
try
{
// populate textboxes
var boxs = new[] {textBox1, textBox2};
// get user input
var decimals = new List<decimal>();
var expenses = GetExpenses(boxs, decimals);
if (!expenses)
throw new InvalidOperationException("Expecting numbers");
// write to file
using (var stream = File.Create("output.txt"))
using (var writer = new StreamWriter(stream))
{
foreach (var d in decimals)
{
writer.WriteLine(d);
}
var total = decimals.Sum();
writer.WriteLine("Total: " + total);
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
private bool GetExpenses(TextBox[] boxs, List<decimal> list)
{
if (boxs == null) throw new ArgumentNullException(nameof(boxs));
if (list == null) throw new ArgumentNullException(nameof(list));
foreach (var box in boxs)
{
var text = box.Text;
decimal result;
if (!decimal.TryParse(text, out result))
return false;
list.Add(result);
}
return true;
}
}
}
You would need a line that adds up the numbers like this:
private void button2_Click_1(object sender, EventArgs e)
{
try
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(textBox1.Text + " " + textBox2.Text+ " " + textBox3.Text+ " " + textBox4.Text);
sb.AppendLine((Int32.Parse(textBox1.Text) + Int32.Parse(textBox2.Text) + Int32.Parse(textBox3.Text) + Int32.Parse(textBox3.Text)).ToString())
File.WriteAllText(fileName, sb.ToString());
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

Categories

Resources