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);
}
}
Related
I have a program I have to finish which involves opening a file that has numbers, displaying it, then also displaying how many numbers the file has and the sum of them.
Im currently stuck on how to add all the numbers read and display it :/
Here is my code:
private void btnReadRandomNumbers_Click(object sender, EventArgs e)
{
StreamReader inputFile;
try
{
int number = 0;
int count = 0;
int sum = 0;
lstRandomNumbers.Items.Clear();
if (fodOpenFile.ShowDialog() == DialogResult.OK)
{
inputFile = File.OpenText(fodOpenFile.FileName);
lstRandomNumbers.Items.Clear();
while (!inputFile.EndOfStream)
{
number = int.Parse(inputFile.ReadLine());
count = count + 1;
lstRandomNumbers.Items.Add(number);
}
lblNumberCount.Text = count.ToString();
lblSumNumbers.Text = number.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show("There is a problem with the disk file." + Environment.NewLine + ex.Message, "User Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
As seen in the Picture, the sum is only reading the last number of the list and im not sure why
Thanks for reading!
in line number = int.Parse(inputFile.ReadLine()); replaced number for each line!
you can write all code with this:
private void btnReadRandomNumbers_Click(object sender, EventArgs e)
{
try
{
lstRandomNumbers.Items.Clear();
if (fodOpenFile.ShowDialog() == DialogResult.OK)
{
var linesOfFile = File.ReadAllLines(fodOpenFile.FileName).Select(int.Parse).ToList();
lblSumNumbers.Text = linesOfFile.Sum().ToString();
lblNumberCount.Text = linesOfFile.Count().ToString();
lstRandomNumbers.DataSource = linesOfFile;
}
}
catch (Exception ex)
{
MessageBox.Show("There is a problem with the disk file." + Environment.NewLine + ex.Message, "User Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
You are almost there. Try your same code with minor modification. I have added inline comments.
private void btnReadRandomNumbers_Click(object sender, EventArgs e)
{
StreamReader inputFile;
try
{
int number = 0;
int count = 0;
int sum = 0;
//lstRandomNumbers.Items.Clear(); //don't need this
if (fodOpenFile.ShowDialog() == DialogResult.OK)
{
inputFile = File.OpenText(fodOpenFile.FileName);
//lstRandomNumbers.Items.Clear();//don't need this
while (!inputFile.EndOfStream)
{
number = int.Parse(inputFile.ReadLine());
count = count + 1;
//lstRandomNumbers.Items.Add(number);//don't need this
sum+=number; // add this
}
lblNumberCount.Text = count.ToString();
lblSumNumbers.Text = sum.ToString(); //change `number' to `sum`
}
}
catch (Exception ex)
{
MessageBox.Show("There is a problem with the disk file." + Environment.NewLine + ex.Message, "User Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
#Issa, Please let me know if this helps.
Give this a go:
private void btnReadRandomNumbers_Click(object sender, EventArgs e)
{
if (fodOpenFile.ShowDialog() == DialogResult.OK)
{
var lines = File.ReadAllLines(fodOpenFile.FileName);
var result =
lines
.Select(x => int.Parse(x))
.Aggregate(
new { count = 0, sum = 0 },
(a, x) => new { count = a.count + 1, sum = a.sum + x });
lstRandomNumbers.Items.Clear();
lstRandomNumbers.Items.AddRange(lines);
lblNumberCount.Text = result.count.ToString();
lblSumNumbers.Text = result.sum.ToString();
}
}
static void Main(string[] args)
{
var res = 0;
var r = new Regex(#"\d");// you can try "\d+" and you will see the difference
var matches = r.Matches("feawfwe312faewfa4gaeg1feaga67awfaw2");
if (matches != null && matches.Count > 0)
{
foreach (var m in matches)
res += int.Parse(m.ToString());
}
Console.WriteLine(res);
Console.ReadKey();
}
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);
}
}
}
}
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();
}
Halllo
I have made my first project and it works, well sort of, I can not get it to close serial port.
I am running 200hz in the Serialmonitor and the save funktion works perfect.
I suspect that it attempts to read data while I am trying to close the port.
It does not come up with an error but hanging in the debugger trying to close the port.
MY CODE IN VISUAL STUDIO 2015:
using System;
using System.Windows.Forms;
using System.IO.Ports;
namespace Arduino_Serial
{
public partial class Form1 : Form
{
private SerialPort myport;
private DateTime datetime;
private string in_data1;
private int runtime_sec = 0;
private float runtime_milis = 0;
public Form1()
{
InitializeComponent();
}
private void Start_Click_1(object sender, EventArgs e)
{
myport = new SerialPort();
myport.BaudRate = 115200;
myport.PortName = Port_name_tb.Text;
myport.Parity = Parity.None;
myport.DataBits = 8;
myport.StopBits = StopBits.One;
myport.DataReceived += Myport_DataReceived;
try
{
myport.Open();
timer2.Enabled = true;
timer1.Enabled = true;
Data_tb.Text = "\"Arduino\"" + "\n";
Data_tb.AppendText("Time" + "\t" + "Raw_data" + "\t" + "MAP" + "\n");
Data_tb.AppendText("Sec " + "\t" + "Raw_data" + "\t" + "KPA" + "\n");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
void Myport_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
in_data1 = myport.ReadLine();
Invoke(new EventHandler(displaydata_event));
}
private void displaydata_event(object sender, EventArgs e)
{
datetime = DateTime.Now;
string time = datetime.Hour + ":" + datetime.Minute + ":" + datetime.Second;
Data_tb.AppendText(("\n")+ (runtime_milis) + ("\t")+ in_data1 );
}
private void Stop_bt_Click(object sender, EventArgs e)
{
try
{
myport.ReadTimeout = 1000000000;
myport.Close();
timer2.Enabled = false;
timer1.Enabled = false;
runtime_milis = 0;
runtime_sec = 0;
}
catch (Exception ex2)
{
MessageBox.Show(ex2.Message, "Error");
}
}
private void Save_bt_Click(object sender, EventArgs e)
{
try
{
datetime = DateTime.Now;
String time = datetime.Year + "-"+ datetime.Month + "-"+ datetime.Day + "_" + datetime.Hour + "." + datetime.Minute + "." + datetime.Second;
string pathfile = #"C:\DATA\";
string filename = "Arduino_" + time + ".msl";
System.IO.File.WriteAllText(pathfile + filename, Data_tb.Text);
MessageBox.Show("Data has been saved");
Close();
}
catch (Exception ex3)
{
MessageBox.Show(ex3.Message, "Error");
}
}
private void timer1_Tick(object sender, EventArgs e)
{
runtime_sec++;
}
private void timer2_Tick(object sender, EventArgs e)
{
runtime_milis++;
}
}
}
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