I just want to say that I only joined stackoverflow a few weeks ago and everyone has been very helpful, thank you. I am down to my last two homework assignments for the semester. What I am trying to do right now is import the data I save to a text file from a program I wrote earlier. Basically the text file is named "client.txt" and the data in it looks like this
account#,firstname,lastname,balance
what I am trying to do now is write a windows form that will read the data in that text file and place it into appropriate corresponding text boxes in the form. Here is my code so far, I believe I am on the right track but I am having trouble because I need the program to do a openfiledialog so I can manually choose the client.txt file and then import the data. Right now I am getting an error "System.IO.StreamReader does not contain a constructor that takes 0 arguments"
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.IO;
namespace Chapter_17_Ex.Sample_2
{
public partial class Form1 : Form
{
OpenFileDialog filechooser = new OpenFileDialog();
public Form1()
{
InitializeComponent();
}
private void btnImport_Click(object sender, EventArgs e)
{
StreamReader fileReader = new StreamReader();
string inputrecord = fileReader.ReadLine();
//string filename;
string[] inputfields;
if (inputrecord != null)
{
inputfields = inputrecord.Split(',');
txtAccount.Text = inputfields[0];
txtFirstName.Text = inputfields[1];
txtLastName.Text = inputfields[2];
txtBalance.Text = inputfields[3];
}
else
{
MessageBox.Show("End of File");
}
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
To use a StreamReader you need to construct it passing, at least, the filename to read.
This could be accomplished using the OpenFileDialog variable declared at the form global level
// Show the OpenFileDialog and wait for user to close with OK
if(filechooser.ShowDialog() == DialogResult.OK)
{
// Check if the file exists before trying to open it
if(File.Exists(filechooser.FileName))
{
// Enclose the streamreader in a using block to ensure proper closing and disposing
// of the file resource....
using(StreamReader fileReader = new StreamReader(filechooser.FileName))
{
string inputrecord = fileReader.ReadLine();
string[] inputfields;
....
// The remainder of your code seems to be correct, but a check on the actual
// length of the array resulting from the Split call should be added for safety
}
}
}
Notice that both the OpenFileDialog and the StreamReader are complex objects that have many properties and different ways to work. You really need to look at their constructors and properties list in the MSDN documentation to exploit their full functionality
Related
I use a GD4430 handheld scanner from the company Datalogic with the included OPOS driver. With the following code I manage to address the scanner. When I start the program, the scanner becomes active and you can scan. But I can not display the results in a TextBox.
Does anyone see where the error lies?
Visual Studio 2010 C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace TestRead
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
axOPOSScanner1.BeginInit();
axOPOSScanner1.Open("USBHHScanner");
axOPOSScanner1.ClaimDevice(0);
axOPOSScanner1.DeviceEnabled = true;
axOPOSScanner1.DataEventEnabled = true;
axOPOSScanner1.PowerNotify = 1; //(OPOS_PN_ENABLED);
axOPOSScanner1.DecodeData = true;
}
void axOPOSScanner1_DataEvent(object sender, AxOposScanner_CCO._IOPOSScannerEvents_DataEventEvent e)
{
textBox1.Text = axOPOSScanner1.ScanDataLabel;
textBox2.Text = axOPOSScanner1.ScanData.ToString();
axOPOSScanner1.DataEventEnabled = true;
axOPOSScanner1.DataEventEnabled = true;
}
}
}
Was not the processing of AxOPOSScanner1.BeginInit() on the source originally in Form1.Designer.cs instead of here?
(I am assuming that the source file name is Form1.cs)
As below(in Form1.Designer.cs):
this.axOPOSScanner1 = new AxOposScanner_CCO.AxOPOSScanner();
((System.ComponentModel.ISupportInitialize)(this.axOPOSScanner1)).BeginInit();
this.SuspendLayout();
There is a possibility that the problem has occurred because you moved it to Form1.cs or calling BiginInit() on both Form1.Designer.cs and Form1.cs.
Or, the following processing does not exist in Form1.Designer.cs, or there is a possibility that the specified function name(axOPOSScanner1_DataEvent) is wrong.
this.axOPOSScanner1.DataEvent += new AxOposScanner_CCO._IOPOSScannerEvents_DataEventEventHandler(this.axOPOSScanner1_DataEvent);
In addition:
What you should do is to temporarily store the return value of all the methods, add a process to determine whether the method was executed normally, likewise It is to read the ResultCode property immediately after setting the property(possibly causing an error) and add processing to judge whether the property setting was done normally.
Also, although not related to DataEvent, PowerNotify setting must be done before DeviceEnabled = true.
I'm trying to create a library for C#, that would get the maximum number in a listbox.
Currently I am just trying the method in the program before creating the library. The following code is what I have:
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.IO;
namespace SPE16
{
public partial class FormExamStatistics : Form
{
List<double> ExamScores = new List<double>();
double highScore = 0;
public FormExamStatistics()
{
InitializeComponent();
}
private double HighScore(List<double> anyList) //return the highest score
{
return highScore = ExamScores.Max();
}
private void buttonAddFromFile_Click(object sender, EventArgs e)
{
StreamReader reader;
reader = File.OpenText("ExamScores.txt");
while (!reader.EndOfStream)
{
double Scores;
double.TryParse(reader.ReadLine(), out Scores);
ExamScores.Add(Scores);
listBoxScores.Items.Add(Scores);
labelHighScore.Text = highScore.ToString();
}
reader.Close();
/////////////
HighScore(ExamScores);
/////////////
}
}
}
Now, it is supposed to return the maximum value from the list created on top, which is populated by a text file "ExamScores.txt". This text file contains 60 (double) scores with a maximum number of 120.
The maximum number, should be 120, but it returns "0".
Now I need to make this as a method first, in order to create a (dll) library later.
What am I doing wrong?
you need to check your file because.NET Framework design guidelines recommend using the Try methods. Avoiding exceptions is usually a good ide
if (value == null)
{
return 0.0;
}
return double.Parse(value, NumberStyles.Float | NumberStyles.AllowThousands, provider)
please post a your file content
did you tried,
private void buttonAddFromFile_Click(object sender, EventArgs e){
StreamReader reader;
reader = File.OpenText("ExamScores.txt");
while (!reader.EndOfStream){
double Scores;
double.TryParse(reader.ReadLine(), out Scores);
ExamScores.Add(Scores);
listBoxScores.Items.Add(Scores);
labelHighScore.Text = highScore.ToString();
}
reader.Close();
/////////////
HighScore(ExamScores);
/////////////
}
Proper sample for the question would be:
var highScore = 0;
labelHighScore.Text = highScore.ToString();
highScore = 42;
Written this way it clearly demonstrates that showing value first and only than changing it does not actually display updated value.
Fix: set value before showing it, likely labelHighScore.Text = highScore.ToString(); should be just moved to the end of the function.
Note that there are likely other problems in the code based on strange way HighScore returns result and how code completely ignores result of the function.
I am writing a program that involves some heavy conversion of an Excel file into a very specifically formatted flat file. There are over 50,000 rows that need converted, so needless to say, it will take a while to process.
With that said, using a BackgroundWorker would make the most sense.
Everything I have executes properly and works fine except for one issue: trying to call the BackgroundWorker.ReportProgress() method from an instantiated class to update a counter on the parent Form.
If I'm not making sense, maybe my code will make more sense:
The Processing GUI Form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
namespace CityTaxImport
{
public partial class Processing : Form
{
string s_sourceFile;
bool b_fileSaved;
CityConvert convert = new CityConvert();
public Processing(string s_incomingPath)
{
BackgroundWorker bg_Taxes = new BackgroundWorker();
s_sourceFile = s_incomingPath;
//background worker
bg_Taxes.DoWork += new DoWorkEventHandler(bg_Taxes_DoWork);
bg_Taxes.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_Taxes_RunWorkerCompleted);
bg_Taxes.ProgressChanged += new ProgressChangedEventHandler(bg_Taxes_ProgressChanged);
bg_Taxes.WorkerSupportsCancellation = true;
bg_Taxes.WorkerReportsProgress = true;
InitializeComponent();
bg_Taxes.RunWorkerAsync();
}
#region METHODS
#region BACKGROUND WORKER
//do work/runworker Async stuff
private void bg_Taxes_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker bg_Taxes = sender as BackgroundWorker;
CityConvert convert = new CityConvert();
convert.ConvertFile(s_sourceFile);
}
//when the worker completes, let user know, end program
private void bg_Taxes_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
pb_Progress.MarqueeAnimationSpeed = 0;
//lets the user know the file is done and prompts them on where to save it at
if (MessageBox.Show(this, "The file has been created.\nChoose where you would like to save it.",
"Conversion Finished", MessageBoxButtons.OK, MessageBoxIcon.Asterisk) == DialogResult.OK)
{
while (b_fileSaved != true)
{
SaveFile();
}
}
}
//used to update the progress count
public void bg_Taxes_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//RIGHT HERE IS WHAT SHOULD UPDATE THE COUNTER
lb_recordCount.Text = convert.i_RowCount.ToString();
}
#endregion
And now the class with all of the hard work:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace CityTaxImport
{
class CityConvert
{
#region VARIABLES AND OBJECTS AND ALL THE OTHER VARS AND CHARS
//the Excel squad
Excel._Application xl_app;
Excel._Workbook xl_wrkBk;
Excel._Worksheet xl_wrkSht;
//our friend object Type.Missing
private object o_miss = Type.Missing;
//dataset and table
private DataSet ds_taxes;
private DataTable dt_taxes;
private DataRow dr_taxes;
//strings and counts and stuff
private string s_sourceFile;
private int i_xlRowTotal;
private int i_xlRowCount;
private int i_dtRowCount;
private string s_output;
public int i_RowCount{get; set;}
#endregion
#region METHODS
//the initial convert file method called by the main window
public bool ConvertFile(string s_selectedFile)
{
s_sourceFile = s_selectedFile;
CreateDataSet();
OpenExcel();
PopulateDateSet();
WriteFile();
CloseExcel();
return true;
}
//builds the dataset to use
//creates the column names that will be written into and then written to the flat file
//SOME WILL JUST BE SPACES
private void CreateDataSet()
{
ds_taxes = new DataSet();
ds_taxes.Tables.Add("Taxes");
dt_taxes = new DataTable();
dt_taxes = ds_taxes.Tables["Taxes"];
dt_taxes.Columns.Add("Pr_Ward");
dt_taxes.Columns.Add("Pr_Block");
dt_taxes.Columns.Add("Pr_Map");
dt_taxes.Columns.Add("Pr_Parcel");
dt_taxes.Columns.Add("Pr_LeaseHold");
dt_taxes.Columns.Add("ParFill");
dt_taxes.Columns.Add("Stub");
dt_taxes.Columns.Add("Pa_Amt");
dt_taxes.Columns.Add("TOTFLG");
dt_taxes.Columns.Add("Pr_WardBATCH");
dt_taxes.Columns.Add("BSEQ");
dt_taxes.Columns.Add("TRANSNO");
dt_taxes.Columns.Add("TRANCD");
dt_taxes.Columns.Add("Pa_BatchDate_TD");
dt_taxes.Columns.Add("Pa_BatchDate_ED");
dt_taxes.Columns.Add("BUSDATE");
dt_taxes.Columns.Add("METH");
dt_taxes.Columns.Add("Pa_Amt2");
dt_taxes.Columns.Add("Payment_ID");
dt_taxes.Columns.Add("OWNSEQ");
dt_taxes.Columns.Add("Pr_OwnerInfo1");
}
//time to populate the dataset form the info from the ExcelSheet
private void PopulateDateSet()
{
//
i_xlRowTotal = 2;
while (xl_wrkSht.Cells.Range["A" + i_xlRowTotal].Value2 != null)
{
i_xlRowTotal++;
}
i_xlRowCount = 2;
i_xlRowTotal = i_xlRowTotal - 2;
for (i_dtRowCount = 0; i_dtRowCount < (i_xlRowTotal); ++i_dtRowCount)
{
//this is used to make conversions of the strings to add paddings, length modifiers, what have you...
//all that fun stuff
dr_taxes = dt_taxes.NewRow();
dr_taxes["Pr_Ward"] = Convert.ToString(xl_wrkSht.Cells.Cells.Range["P" + (i_xlRowCount)].Value2);
dr_taxes["Pr_Block"] = Convert.ToString(xl_wrkSht.Cells.Range["Q" + (i_xlRowCount)].Value2);
dr_taxes["Pr_Map"] = Convert.ToString(xl_wrkSht.Cells.Range["R" + (i_xlRowCount)].Value2);
dr_taxes["Pr_Parcel"] = Convert.ToString(xl_wrkSht.Cells.Range["S" + (i_xlRowCount)].Value2);
dr_taxes["Pr_LeaseHold"] = Convert.ToString(xl_wrkSht.Cells.Range["T" + (i_xlRowCount)].Value2);
dr_taxes["ParFill"] = #" ";//12 spaces
dr_taxes["Stub"] = #" ";//10 spaces ALWAYS
dr_taxes["Pa_Amt"] = AppendAmt();
dr_taxes["TOTFLG"] = "N";
dr_taxes["Pr_WardBATCH"] = AppendWard();
dr_taxes["BSEQ"] = AppendBSEQ();
dr_taxes["TRANSNO"] = "000000000";
dr_taxes["TRANCD"] = "P";
dr_taxes["Pa_BatchDate_TD"] = AppendBatchDates();
dr_taxes["Pa_BatchDate_ED"] = AppendBatchDates();
dr_taxes["BUSDATE"] = #" "; //6 spaces
dr_taxes["METH"] = "Check";
dr_taxes["Pa_Amt2"] = AppendAmt();
dr_taxes["Payment_ID"] = AppendID();
dr_taxes["OWNSEQ"] = "000";
dr_taxes["Pr_OwnerInfo1"] = AppendOwner();
dt_taxes.Rows.Add(dr_taxes);
++i_xlRowCount;
i_RowCount = i_xlRowCount;
//RIGHT HERE IS WHERE I WANT TO CALL THE
Processing.bg_Taxes.ReportProgress() //method
}
}
I have tried Processing.bg_Taxes.ReportProgress(); but I get the Object reference is required for the non-static...method error (which I understand what that is.)
I have also looked at a lot of other Q&As on here about the using BackgroundWorkers however none of them seem to quite answer my question or I am just not getting it (which may be the issue as well).
My questions are, then: is there a way to call that method without making my BackgroundWorker static?
And with that: is there any problem with MAKING it static (I have always been told avoid static methods and what have you when writing code).
And finally: am I missing something in my logic here about how exactly I should be going about this? Is there another more "best practice" way?
Any help or advice is appreciated.
Thank you all in advance.
UPDATE
I ended up solving my problem by just some of the essential methods over to the Form class and altering my code from there. Just wanted to throw it out there and thank everyone for pointing in me in the right directions.
iam trying to write a class which imports *.vcf files (Vcard), because i didn´t found a adequate .net class to solve that job.
So i decided to treat the *.vcf file like a *.txt file. I just import the whole file, line by line, with a StreamReader. Finally i save the line into a List object.
The Code:
private List<string> vcardList = new List<String>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
using (StreamReader reader = new StreamReader(#"H:\VS.vcf"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
vcardList.Add(line);
}
}
}
After importing the text i needed to edit the lines, because i need to remove all the unnecessary symbols.
I tried to use the RedEx claa:
private void button1_Click(object sender, EventArgs e)
{
vcardList[0] = Regex.Replace(vcardList[0], "BEGIN:", string.Empty);
}
that works very well, for the first line! but the *.vcf file is very complex and allways different.
So my question is: Is there a better way to solve that problem?
This is the *.vcf file:
BEGIN:VCARD
VERSION:2.1
N;LANGUAGE=de;CHARSET=Windows-1252:Test;Mustermann;;;(geschäftlich)
FN;CHARSET=Windows-1252:Test Mustermann (geschäftlich)
ORG:Mustermann CompanyTITLE;CHARSET=Windows-1252:CEO
TEL;WORK;VOICE:0049 1111 22 769 23 - 1
TEL;CELL;VOICE:0049 2222 33 71 55 90
ADR;WORK;PREF;CHARSET=Windows-1252:;;Frobuehl 22;Gothtown;;101092;England
LABEL;WORK;PREF;CHARSET=Windows-1252;ENCODING=QUOTED-PRINTABLE:Leihb=FChl 21=0D=0A=
101092 Frobuehl
X-MS-OL-DEFAULT-POSTAL-ADDRESS:2
URL;HOME:www.Test-Mustermann.de
EMAIL;PREF;INTERNET:Test#Test-Mustermann.de
X-MS-OL-DESIGN;CHARSET=utf-8:<card
END:VCARD
I only need the name and address. Thanks in advance
Pretty old, but it still works: https://github.com/drlongnecker/Thought.vCards
You can try to use this sample.
Helle, sry for the long delay.
I solved my problem now with the follwing code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Outlook = Microsoft.Office.Interop.Outlook;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Outlook.ContactItem contact;
Outlook.Application app = new Outlook.Application();
contact = (Outlook.ContactItem)app.Session.OpenSharedItem(#"C:\vv.vfc");
MessageBox.Show(contact.FirstName);
}
}
}
This is just an example of how to easily import a VCF file with C# . i hope this helps. Of course i wouldnt implement it in that way, i rather would create a method with a parameter "incomingFile" or smth else.
Berry
the solution with the outlook application is not effictive.
Outlook.Application app = new Outlook.Application();
this will open the outlook first. and actually you need only to open the vcard and parse it to extract the information you want from it.
C# purely does not has specific method or class for work with vcfs.
But these solutions can be way.last one is the best:
Work with Microsot.office.interop.outlook.
Ohhh nooo.it will open outlook first and then after steps you can do your work.surely its not best solution.
Use Thought vcard.its not too bad but image that you have multiple vcfs and you merge them in one vcf.with this package its too hard(or almost impossible) to work with it.
Use VCardlib .it doesnt has previous problem but its not update for work with vcf version4 until now.
I use MixERP.NET.VCard and its more simple and effective.
I'm developing an application that has a TextBox. I want to write its contents to a file, but how can I do this?
There are many ways to accomplish this, the simplest being:
using(var stream = File.CreateText(path))
{
stream.Write(text);
}
Be sure to look at the MSDN page for File.CreateText and StreamWriter.Write.
If you weren't targeting the .NET Compact Framework, as your tags suggest, you could do even simpler:
File.WriteAllText(path, string);
System.IO.File.WriteAllText("myfile.txt", textBox.Text);
If you're stuck on some brain-dead version of the BCL, then you can write that function yourself:
static void WriteAllText(string path, string txt) {
var bytes = Encoding.UTF8.GetBytes(txt);
using (var f = File.OpenWrite(path)) {
f.Write(bytes, 0, bytes.Length);
}
}
Try this:
using System.Text;
using System.IO;
static void Main(string[] args)
{
// replace string with your file path and name file.
using (StreamWriter sw = new StreamWriter("line.txt"))
{
sw.WriteLine(MyTextBox.Text);
}
}
Of course, add exception handling etc.
For a richTextBox, you can add a "Save" button for this purpose. Also add a saveFileDialog control from Toolbox, then add following code in button's click event.
private void button1_Click(object sender, EventArgs e)
{
DialogResult Result = saveFileDialog1.ShowDialog();//Show the dialog to save the file.
//Test result and determine whether the user selected a file name from the saveFileDialog.
if ((Result == DialogResult.OK) && (saveFileDialog1.FileName.Length > 0))
{
//Save the contents of the richTextBox into the file.
richTextBox1.SaveFile(saveFileDialog1.FileName);
}
}