Convert object to double when using GetValue method - c#

I want to perform a windows form which act as a unit conversion, like conversion from cm to m, etc.
Basically, my main codes are like this:
first binding data to drop down list
List<String> myList = new List<String>();
myList.Add("Inch");
DropDownList1.DataSource = myList;
DropDownList1.DataBind();
Int32 index1 = DropDownList1.SelectedIndex;
Int32 index2 = DropDownList2.SelectedIndex;
Double [,] key = new Double[7,7];
key.SetValue(1, 0, 0);
key.SetValue(1,1,2);
........
Double input_Number = Convert.ToDouble(input.Text);
Double ratio = Convert.ToDouble(key.GetValue(index1, index2));
Double ratio = key.GetValue(index1, index2);
Double result = input_Number*ratio ; //doesn't appear correct result
Comment.Text = Convert.ToString(result);
It runs ok, but it doesn't perform the function correctly. when i type sth in the inputbox and select cm to m, it doesn't work,always returns the same number. And when i am debugging, i try to see the ratio value, it still doesn't work.
is it a problem of my conversion from object to double? Because the getvalue method returns an object.

Firstly, you've got
Double ratio = Convert.ToDouble(key.GetValue(index1, index2));
Double ratio = key.GetValue(index1, index2);
not sure how this going to work. It will not run.
Secondly, i don't think you need do: Double ratio = Convert.ToDouble(key.GetValue(index1, index2));
it should come out with double
Finally, value assignment to your array looks like this:
key.SetValue(1, 0, 0);
key.SetValue(1,1,2);
which is assign value "1" to this 2-D array, so you will get everything times "1", is that what you want to do?

I have found out what's wrong with my code. It's because I wrote in my Dropdown list data bind in page_load. Everytime when I refresh my website, it automatically reset to default, which is the dropdown list item index=0; So it won't appear correctly

Related

How to multiply the number of two labels in C#

so i have 2 labels. one of them is a fixed number and doesn't change but the other one changes every 5 seconds. Now i want to multiply them automatically and show them in another label as Results.
what should i do? what am i doing wrong?
i tried this code but it says "operator * cannot be applied to string and string".
label1.Text = BTC_A.Text * BTCPrice_Label.Text;
then i tried
double txt1 = Convert.ToDouble(BTC_A.Text);
double txt2 = Convert.ToDouble(BTCPrice_Label.Text);
double sum = txt1 * txt2;
label1.Text = sum.ToString();
but it says "Input string was not in a correct format"
Think it through step by step.
You have labels with a Text property. That property is of type string. C# is a strongly typed language: strings can not be multiplied like that. In the end, a label can be empty, or the user could input any random string. What would be the result of "foo" * "bar"?
Also, when you do have a double as a result of some multiplication, you want to show it to the user in another label.Text. Here you have the inverse issue: C#/.Net does not convert the variable of type double implicitly to a string.
So you will have to
check if the strings entered by the user is actually a valid double
if they are, convert those strings to double and multiply them
convert the result to a string, and assign it to the labels Text property
if the strings are not valid numbers, leave the label empty, or show some other message
The logic to achieve this would be something like this:
var validPrice = int.TryParse(BTCPrice_Label.Text, out double price);
var validAmount = int.TryParse(BTCA_Label.Text, out double amount);
if (validPrice && validAmount)
{
var result = price * amount;
label1.Text = result.ToString();
}
else
{
label1.Text = "something is wrong";
}
so the problem was a dollar sign ( $ ) that i put before the numbers.
i just deleted the sign and this is what the code looks like now:
double AA;
if (!double.TryParse(BTC_A.Text, out AA))
{
MessageBox.Show($"Unable to convert the BTC_A \"{BTC_A.Text}\" to a floating point number");
return;
}
double btcA;
if (!double.TryParse(BTCPrice_Label.Text, out btcA))
{
MessageBox.Show($"Unable to convert the price \"{BTCPrice_Label.Text}\" to a floating point number");
return;
}
label1.Text = (AA * btcA).ToString();

How to sum only one textbox value and show result in label in c# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
The question could be duplicate but my problem is totally different.
I have a one textbox and one label.
Example: label text is already exist with number like 450 Now I want to add number in textbox and the textbox value should be sum in 450 + 30 = 480 where 30 is textbox value.
what I have tried:
lbl_TotalAmount.Text = lbl_TotalAmount.Text + txt_DeliveryCharges.Text;
The above Result is: 45030
Another Code I Have tried:
double total = Convert.ToDouble(lbl_TotalAmount.Text);
double charges = Convert.ToDouble(txt_DeliveryCharges.Text);
double sum = total + charges;
lbl_TotalAmount.Text = String.Format(sum.ToString("0.00"));
The above code is going to sum every value that I put in the textbox and also when I remove one word the number is sum every time.
Please give me best solution I tried many solution to solve this but unable to do this.
Sorry for bad English.
The above code is going to sum every value that I put in the textbox and also when I remove one word the number is sum every time.
That's most likely because you're calling your code inside the TextChanged or the KeyPress events of the textbox; this means that every time you modify anything in your textbox, your code will fire and make the sum.
Instead, add a button and put your code inside its Click event, or if you want the sum to respond to every keypress while respecting your original value, save your value in a variable and use it to calculate the sum.
'Declare a variable at form level
Dim originalValue as Double
'Code where you put your value in a label, put it also in a variable
lbl_TotalAmount.text = 450
originalValue = 450
'Modify your code to use the original value instead of the label
double charges = Convert.ToDouble(txt_DeliveryCharges.Text);
double sum = originalValue + charges;
lbl_TotalAmount.Text = String.Format(sum.ToString("0.00"));
Your strings need to be converted (parsed) to doubles (since they are representing monetary values), but you need to be sure that you're not trying to parse something that can't be converted. TryParse() evaluates to true (or false if the parse fails), so you can avoid a possible exception.
Additionally, you've stated in comments that you want this to update as the text box is updated, so you'll need a variable that is out of scope to keep the total separated from the calculation. I'm going to work from the assumption that this is a shopping cart, or something like that. In that case, a List<> would be an obvious way to store the values of the items in the cart.
Try this:
using System;
using System.Collections.Generic; //required for List<>
namespace WidowsFormsApplication
{
public class ShoppingCart
{
List<double> shoppingCart = new List<double>();
protected void AddItemToCart()
{
shoppingCart.Add(450);
}
protected void UpdateShoppingCart()
{
double total = 0;
foreach (double item in shoppingCart) //calculate total of shoppingCart
{
total += item;
}
if (Double.TryParse(txt_DeliveryCharges.Text, out double charges))
{
total += charges; //add charges without altering shoppingCart
lbl_TotalAmount.Text = String.Format("{0:0.00}", total);
}
}
}
}
lbl_TotalAmount.Text = lbl_TotalAmount.Text + txt_DeliveryCharges.Text;
lbl_TotalAmount.Text and txt_DeliveryCharges.Text are text fields. You cannot do arithmetic on text fields. You have to convert to number, do the arithmetic then convert back
var charge = Int32.Parse(txt_DeliveryCharges.Text);
var total = Int32.Parse(lbl_TotalAmount.Text);
var newTotal = charge + total;
lbl_TotalAmount.Text = newTotal.ToString();
what you are doing is string concatenation
Not a sum of two numbers, You have to convert your strings to int first
here is how you can do that
int x = 0, y = 0;
if (Int32.TryParse(lbl_TotalAmount.Text out x) && Int32.TryParse(txt_DeliveryCharges.Text, out y))
{
// you know that the parsing attempt
// was successful
lbl_TotalAmount.Text = x + y;
}
yourlabel.Text = ""+ (Int32.Parse(yourlabel.Text)+Int.Parse(your textbox.Text));
or
yourlabel.Text = ""+(Double.Parse(yourlabel.Text)+Double.Parse(yourtextbox.Text));
are you using a double? only need that for decimal numbers that are super precise. whole numbers, use int... if you're using it to do money you want to use Decimal, but it depends on the situation.

Unable to cast object of type 'system.windows.forms.textbox' to type 'System.IConvertible' error for c# form

I have this code here but I keep getting the same error. Can someone tell me what I did wrong?
private void button1_Click(object sender, EventArgs e)
{
double gallonsToBuy;//for equation
double WALL_LENGTH; //holds wall length
double WALL_HEIGHT; //holds wall height
int NUM_DOORS; //holds number of doors
int NUM_WINDOWS; //holds number of windows
int NUM_COATS; //holds number of coats of paint
const double GALLON_SF = 350; //one gallon covers 350 square feet
//allows user to input their numbers
WALL_LENGTH = Convert.ToDouble(textBox1);
WALL_HEIGHT = Convert.ToDouble(textBox2);
NUM_DOORS = Convert.ToInt32(textBox3);
NUM_WINDOWS = Convert.ToInt32(textBox4);
NUM_COATS = Convert.ToInt32(textBox5);
//Equation
gallonsToBuy = ((((WALL_LENGTH * WALL_HEIGHT) - (20 * NUM_DOORS) - (15 * NUM_WINDOWS)) * NUM_COATS) /350);
label7.Text = "Gallons to buy =" +gallonsToBuy;
}
Your error comes from trying to convert a TextBox to a double.
WALL_LENGTH = Convert.ToDouble(textBox1);
TextBox is a .NET object type, and you cannot do a meaningful conversion to a double. What you must do is convert the value of TextBox.Text property to a double.
WALL_LENGTH = Convert.ToDouble(textBox1.Text);
But this alone would still be problematic and error prone, if the user enters text that cannot be converted to a double.
So you should, in addition, use proper methods for conversion such as int.TryParse() and double.TryParse().
For instance,
double WALL_LENGTH;
double.TryParse(textBox1.Text, out WALL_LENGTH);
If all such conversions succeed, then proceed with the calculation.
Looking at your code I believe textBox1,textBox1 etc. are TextBox control. You cannot covert control type to data type. you need to use the property .text to access the value within the control.
WALL_LENGTH = Convert.ToDouble(textBox1.Text);
WALL_HEIGHT = Convert.ToDouble(textBox2.Text);
NUM_DOORS = Convert.ToInt32(textBox3.Text);
NUM_WINDOWS = Convert.ToInt32(textBox4.Text);
NUM_COATS = Convert.ToInt32(textBox5.Text);
Make sure you have a value to the input fields otherwise it will through cast error trying to convert it from string.empty.

Convert delimited record to seperate strings?

On my web form I have a token box where the user can select multiple answers and it compiles them using a ~ to separate them. I am trying to add up a score on this page and I need to split those values. I tried using this and it says cannot explicitly convert char to string. Lets say the fields answer is 3~4~5
How would I convert that to 3 4 5 in a manner that would allow me to perform a calculation.
string List1 = threeriskfactors.Text.ToString();
string[] Vals1 = List1.Split('~');
String name1 = List1[0];
String name2 = List1[1];
I have had no problems adding up single values from a drop down list but this is stumping me. For my other calculations my code looks like this:
int a1 = Convert.ToInt32(cancerisabnormalcells.SelectedValue.ToString());
int b1 = Convert.ToInt32(cancerissecondcause.SelectedValue.ToString());
int d1 = Convert.ToInt32(americancancersociety.SelectedValue.ToString());
int final1 = a1 + b1 + d1;
How do I split the token boxes value so I can add it to this calculation?
If you want the Sum of them then it is as simple as:
int final = List1.Split('~').Select(s => int.Parse(s)).Sum();
To Validate each value to see if it is parseable before parsing, you can use ForEach method of List:
List1.Split('~').ToList().ForEach(s => { int a =0; int.TryParse(s, out a); final +=a; });
IEnumerable<int> vals1 = list1.Select(e=> Convert.ToInt32(e));
int final1=0;
foreach(int val in vals1)
{
final1 = final1 + val;
}
This should do it.
var total = 0;
foreach (var item in list1.Split('~'))
total += Int32.Parse(item);
By the way, I'm not sure how you're concatenating the values to get the tilde-delimited string. But, it's worth noting that HTML forms will automatically create semicolon-delimited list of values from HTML form elements that share the same name.

How to get max value of List<> in double datatype

I am trying to get Max value from List<>, but it's returning rounded value to integer. Is there some special way how to proceed this?
private List<double> dataX = new List<double>();
double maxVal = dataX.Max<double>();
Debug.WriteLine("max: " + maxVal);
Edit:
As requested here is feeding data:
for (int i = 0; i < 10; i++)
{
data.Add(new ChartData(i, rand.NextDouble() * 10));
Debug.WriteLine(data.Last<ChartData>().Y);
}
My debug window shows this:
5,9358753151893
7,87125875608588
3,77212246589927
9,36056426230844
2,27154730924943
9,80201833872218
5,7350595275569
3,04650606729393
5,81677517658881
0,0514464220271662
max: 8
So I don't think the feeding side is wrong. And for whole picture, here you can see ChartData type:
public class ChartData
{
public double X { get; set; }
public double Y { get; set; }
public ChartData(double X, double Y)
{
this.X = X;
this.Y = Y;
}
}
And how I'm getting simple List from my ChartData class:
private List<ChartData> data = new List<ChartData>();
private List<double> dataX = new List<double>();
void updateMaxMin()
{
dataX.Clear();
dataY.Clear();
for (int i = 0; i < data.Count - 1; i++)
{
dataX.Add(data[i].X);
dataY.Add(data[i].Y);
}
}
There are two likely scenarios here.
You are rounding the values as you enter them into the list (as #sam mentioned in his comment).
You are expecting a double value ending in 0 to show these decimal places. A double will always drop off the insignificant digits. So for example, 1.500 will be truncated to 1.5. This is how doubles were intended to work. Another article that briefly talks about this is Double Skips last decimal if zero. If you are looking for a different Visual output, I would recommend converting the result to a string and then using string formatting. An example would be the following (using 2 decimal places):
Console.WriteLine(string.Format("max: {0:0.00}", maxVal));
Most likely the problem is in the way you insert into the list as some had suggested in here (you mentioned about rounded to an integer, so I'm assuming it is probably not visual display related).
Try debug your data in the list:
private List<double> dataX = new List<double>();
...
foreach(var data in dataX)
{
Debug.WriteLine("data: " + data);
}
double maxVal = dataX.Max<double>();
Debug.WriteLine("max: " + maxVal);
A possible issue with the way you populate the list could be something like:
var myNum = new[] { 1, 2, 3, 4, 5, 6 };
foreach (var num in myNum)
{
dataX.Add(num / 2);
}
The data that was added into the dataX is actually an integer (as the division by 2 returns an integer).
double doesn't keep insignificant digits. - there's no difference between 9 and 9.0 and 9.0000
If you want just display purpose use refer this link C# Double - ToString() formatting with two decimal places but no rounding for convert the double to string with decimal places. but,if you using calculation it's no need for keeping with decimal places.
Ok I found mistake. I have been calculating max value from different array. So i got correct max value anyway. There should be:
double maxVal = dataY.Max<double>();
instead of
double maxVal = dataX.Max<double>();
So I guess, this isn't much helping, so I will delete this question after you realized I did basic fault.
Thank you all anyway.

Categories

Resources