C# Form Textbox string calculation with datatable()

datatable sum row c#
datatable compute sum in c# with filter
how to calculate sum of column in gridview in c#
c# datatable compute sum group by
sum column in datatable c# using linq
datatable.compute sum multiple columns
data binding in c# windows application
datatable compute sum string column in c#

I just started with C# a week ago (programming with C++ like 2 1/2 years) and today I started my first form application. It is just a simple calculator.

So I have a form with the buttons 0-9; + ;- ;*;/ (and some more but they are not interesting for this problem) and one multiple line textbox. If the user press a button the specific symbol or digit is written directly to the output textbox. So the input part is working fine.

The problem is the calculation part. The code for this part is:

DataTable dt = new DataTable();
        double result = (double)dt.Compute(output.Text.ToString(), "");
        output.AppendText($" ={result.ToString()}");

If I run it I'm getting this error:

*System.InvalidCastException
  HResult=0x80004002
  Message=Specified cast is not valid.
  Source=SimpleCalculator
  StackTrace:
   at SimpleCalculator.Form1.result_Click(Object sender, EventArgs e) in C:\Users\Max\Documents\C#\Projects\SimpleCalculator\SimpleCalculator\Form1.cs:line 105
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.Run(Form mainForm)
   at SimpleCalculator.Program.Main() in* 

So the interesting thing is ill changed it to int 32 (what's the error message is saying)

double result = (int32)dt.Compute(output.Text.ToString(), "");

it works fine until double values then it runs to an error (what is logic) but if I change it back to double its working.

double result = (double)dt.Compute(output.Text.ToString(), "");

I'm a bit confused about this because I didn't change anything in the code and the error comes sometimes back.

I mean yeah its working but not clean enough for me. I want to have an code without any chance to run to an error.

I'm using Visual Studio 2017 Community, is it because of VB or because of bad code?

You may use the Convert class instead of casting. Example:

double result = Convert.ToDouble(dt.Compute(output.Text.ToString(), ""));

This article explains how to calculate Sum (Total) of DataTable Columns using the following two methods. 1. VB.Net. Dim dt As New DataTable(). dt.Columns. C#. int sum = Convert.ToInt32(dt.Compute("SUM(Salary)", string.Empty)); You can add your comment about this article using the form below. Filter DataGridview Rows Using TextBox in C#. 1 year ago. Add Comment. by admin. 1,247 views. In this example, I’ll show you How to Filter DataGridView With the Text Entered in TextBox. Step 1: Create a new Windows application. Add a DataGridView and textbox control. Step 2: Load data from DataTable.

You need to use double. DataTable.Compute supports multiple operators and the result sometimes is an integer and sometimes a double. So use the greater type that works with always: double.

This returns int:

new DataTable().Compute("1+1", null)  // 2 int

and this returns double:

new DataTable().Compute("1/1", null) // 1.0 double

You can use System.Convert.To.Double:

System.Convert.ToDouble(new DataTable().Compute("1+1", null));

Operators, rules and syntax is explained here

NET Page, 383-384 PrintPage Event Handler, 367 Proxy Calculator Class, 570 Retrieving the Result of a Dialog Box in C#, 212 RichTextBox Application Data, 306 Serializing Binary Data, 359 Setting Form Height Based on Screen Size, 361 Locale property DataSet class, 822 Data Table class, 823 localhost string,  In a Win Form I'm doing initial validation in the Form. So before saving data, I want to validate whether all the required fields are filled (Text Boxes) by the user. There are about 18 such Text B

You are getting error because Datatable.Compute returns Object which contains text. In C#, casting Text to Number wont compile because compiler cant convert text to number. Text may not contain only numbers but any character. You will have to use Convert.To()

If you are interested into this problematic you can read question about difference between casting and using Convert.

In you code, if you change line

 double result = (double)dt.Compute(output.Text.ToString(), "");

into

 double result = Convert.ToDouble(dt.Compute(output.Text.ToString(), ""));

it should works fine.

Column Fill Mode in the Windows Forms DataGridView Control that their proportions match the proportions of the calculated widths. Forms; public class Form1 : Form { [STAThread] public static void Main() { Application. private void AddReadOnlyColumn(String dataPropertyName, String GetType() . getting text box value from datatable. i want to get the text box value with respect to id. Posted 22-May-11 23:56pm. beginner in C#.net. Add a Solution. 1

I know about the syntax of this function, that's not the problem; this error only occurs sometimes (by integer returns too).

I'll try now kaffekopps resolution and accept his answer. If the error comes back I'll reopen this question.

In this article you will learn how to do calculations in a GridView to calculate the total amount while typing the value into a TextBox //Where MYDBConnection is the connetion string that was set up To get started let's setup the form. void BindDummyDataToGrid() {; DataTable dt = new DataTable();  This method will take the string data pointed to by the string reference returned by the Text property. It then actually writes that to the physical hard disk on the computer. Note: After you run this program, you can open the "demo.txt" file and the text you typed into the program will be there. File

For each data source on a Windows Form, there is a single CurrencyManager object. For example if you add a TextBox control to a form and bind it to a column of a table However, when you bind to a DataTable, you are a really binding to the The DisplayMember of a Combobox gets or sets a string that specifies the  In this tutorial, you will learn how to bind data from textbox to gridview in C#, in detail. Displaying data with a tabular format is a task you are likely to perform frequently. The DataGridView is designed to be a complete solution for displaying data with tabular format in Windows Forms.

Top Online Courses From ProgrammingKnowledge Python Programming Course ➡️ http://bit.ly Duration: 12:15 Posted: Apr 7, 2013 Hi, I am using a data table and want to insert value from text box what is the source code for that. After entering all records finally use submit button for save to database.

DataTables provides an API method to add your own search functions, $. faces. On the web form drag and drop a TextBox, Label and a Button; Add one The entire pattern is matched against the String value of the input field. 5 or The following C# code is a handler that make sure that a Windows Form TextBox accepts  A text box object is used to display text on a form or to get user input while a C# program is running. In a text box, a user can type data or paste it into the control from the clipboard. For displaying a text in a TextBox control , you can code like this.

Comments
  • What you mean by VB?
  • Sorry typos VS(Visual Studio)
  • Why can't you use double? If a calculation sometimes returns integers and sometimes doubles, use double because it works for both. 1+1=2 returns int and 1/1=1.0 returns double
  • Im new to visual studio (For c++ im using qt creator) where can i debug a special line of code? PS: Right now its working again i dont get it why this appear only sometimes without changing anything to this fucntion
  • for example in the quick watch window. But look at my edited comment, you see that you need double because that handles all calculations