I am new at C#. I hope someone can help me.
I am programing a small Windows Forms Application.
Two textBoxes and one result label.
For hours I am trying to get from the Strings in the textBoxes a Float Value.
Later some one will write for example 1.25 in TextBox1 and divide it with a value in the second TextBox.
I tryed lot of code. If a code is working (not red underlined) than I get this
Error Message: "Error kind of System.Format.Exception in mscorlib.dll".
"The entered String has wrong format".
How can I fix this?! Or what am I m doing wrong?! Please help. I am a Noob.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
string a = textBox1.Text;
string b = textBox2.Text;
float num = float.Parse(textBox1.Text);
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
}
}
}
`
If you use the Parse function & an invalid number is entered - then you will get an error message (in the form of an unhandled exception) of the type you described.
You can either implement exception handling :
float num;
try
{
num = float.Parse(textBox1.Text);
}
catch (FormatException)
{
// report format error here
}
you can also catch the out of range & null argument exceptions : https://msdn.microsoft.com/en-us/library/2thct5cb(v=vs.110).aspx
Or use the TryParse method :
float num;
bool NumberOK = float.TryParse(textBox1.Text, out num);
if (!NumberOK)
{
// report error here
}
https://msdn.microsoft.com/en-us/library/26sxas5t(v=vs.110).aspx
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.
So I'm trying to make a simple program in Visual C# that counts the number of "Connected Devices", which can be seen as the amount of buttons clicked.
The code should check which button was clicked and change it's background image. It should also update the count and label on the form.
First of all, here's my 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;
namespace Device_Storage
{
public partial class Form1 : Form
{
int totalDevices = 0;
public Form1()
{
InitializeComponent();
}
private void addDevice(object sender, EventArgs e)
{
try
{
Button clickedBtn = sender as Button;
Image add_image = Properties.Resources.addDevice;
Image remove_image = Properties.Resources.removeDevice;
if (clickedBtn.BackgroundImage == Properties.Resources.addDevice)
{
clickedBtn.BackgroundImage = remove_image;
totalDevices++;
}
else if (clickedBtn.BackgroundImage == Properties.Resources.removeDevice)
{
clickedBtn.BackgroundImage = add_image;
totalDevices--;
}
updateLabel();
} catch (Exception ex)
{
MessageBox.Show(ex.Message, "An Error Occured");
}
}
private void updateLabel()
{
label1.Text = "Connected devices: " + totalDevices;
}
}
}
(I didn't change any of the using statements yet, I usually do that when I'm finished or am 100% sure I won't be using the namespace)
I can't find anything wrong with the code myself and Visual Studio (2015) doesn't give an error.
When I click a button (there are 36 total buttons) nothing happens, the label doesn't update, the image doesn't change, nothing. I don't even get an error, the program doesn't crash.
If anyone can see what I did wrong and can help me fix it that would be really appreciated.
(Edit: My resources folder contains 2 png files, "addDevice.png" and "removeDevice.png")
(New info: all buttons start with the background image "addDevice.png" as to represent an empty slot)
I'm new here hoping for some help with geckoFX in C#
So I just downloaded the geckoFX and did the following.
Downloaded: geckofx.dll
downloaded: XULRunner
I added the geckofx browser successfully and works fine but when I try to run this code to add JavaScript to the page I get an error.
The error I'm getting is: skybound.geckoFX.AutoJSContext does not contain a definition for evaluate script and jscontext.
Also I don't know if this helps but AutoJSContext and EvaluateScript are not hightlighting.
Here is my code
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using Skybound.Gecko;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Skybound.Gecko.Xpcom.Initialize(#"C:\Program Files\xulrunner");
}
private void geckoWebBrowser1_DocumentCompleted(object sender, EventArgs e)
{
string outString = "";
using (AutoJSContext java = new AutoJSContext(geckoWebBrowser1.Window.JSContext))
{
java.EvaluateScript(#"window.alert('alert')", out outString);
}
}
}
You should call EvaluateScript like so:
java.EvaluateScript(#"window.alert('alert')", (nsISupports)geckoWebBrowser1.Window.DomWindow, out result);
I have a C# program that utilizes a find function however it is able to find the word but does not highlights the found word in the richTextBox.
Can someone please advise me on the codes?
Thanks.
Find Function Class Form:
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 Syscrawl
{
public partial class Find_Form : Form
{
FTK_Menu_Browsing_History fmbh = new FTK_Menu_Browsing_History();
public Find_Form()
{
InitializeComponent();
}
public void searchButton_Click(object sender, EventArgs e)
{
string s1 = fmbh.getSearchBrowsing().ToLower();
string s2 = textBoxSearch.Text.ToLower();
if (s1.Contains(s2))
{
MessageBox.Show("Word found!");
this.fmbh.richTextBoxBrowsing.Find(s2);
this.fmbh.richTextBoxBrowsing.SelectionLength = s2.Length;
this.fmbh.richTextBoxBrowsing.SelectionColor = Color.Red;
this.Close();
}
else
{
MessageBox.Show("Word not found!");
}
}
}
}
You need to select what you are looking for first. This:
int offset = s1.IndexOf(s2);
richTextBox1.Select(offset, s2.Length);
After that you can make the whole highlightining. Another tip, to prevent the flickering in the selection process, use this code in your form:
protected override void WndProc(ref Message m)
{
if (m.Msg == 0) {
if (!_doPaint)
return;
}
base.WndProc(ref m);
}
Before selecting anything set _doPaint to false and after the selection set it to true.
Hope I can help!
You need to call s1.IndexOf(s2, StringComparison.CurrentCultureIgnoreCase) to find the position of the match.
Also, it looks like your Find form creates its own instance of the History form; it doesn't use the existing instance.
You should consider accepting a constructor parameter.