I have a textbox called txtUprice which gets the value from a data-grid view, but when I tried get value of the txtUprice-textbox in a message box (with or without changing the text box value) I'm getting an error:
Input string was not in a correct format
I have tried changing the data type in sql where i get the value to the datagrid.
To get the value for textbox from datagrid i have used this:
txtUprice.Text = datagridview.SelectedRows[0].Cells[4].Value.ToString()
To take the textbox value to message-box i have used this:
int unitprice;
unitprice = int.Parse(txtUprice.Text);
MessageBox.Show(unitprice.ToString());
You are getting error beacuse of this line
unitprice = int.Parse(txtUprice.Text);
Reason is, you are trying to parse some string to integer which cannot. like 10%.
Instead of that use like this.
//int unitprice;
//unitprice = int.Parse(txtUprice.Text);
MessageBox.Show(txtUprice.Text);
Or still you want to convert that to int, use try parse
int num1;
bool res = int.TryParse(txtUprice.Text, out num1);
if (res == false)
{
MessageBox.Show("String is not a number");
}
else{
MessageBox.Show(num1.ToString());
}
Related
I am not inserting any value in VOUCHER_NO column and updating it.
But it is giving me error as
Input string was not in a correct format.Couldn't store <> in VOUCHER_NO Column. Expected type is Decimal.
Below is my code
drpayinfo[0]["VOUCHER_NO"] = e.Record["VOUCHER_NO"];
Update
I am using Oracle DB and its datatype is NUMBER (10)
Seems your e.Record["VOUCHER_NO"] have some unwanted content which is not convertible to decimal. Try this way checking before assignment or conversion
if(e.Record["VOUCHER_NO"] != "")
{
drpayinfo[0]["VOUCHER_NO"] = Convert.ToDecimal(e.Record["VOUCHER_NO"]);
}
But more safer way to detect and ignore bad content is
decimal result;
if (Decimal.TryParse(e.Record["VOUCHER_NO"], out result))
{
drpayinfo[0]["VOUCHER_NO"] = result;
}
else
{
// do stuff if failed to parese
}
Based on your comments on other answers, your value is an empty string. This cannot directly be converted to a decimal. You must decide some action to take instead.
They following code will try to convert it, and take an action if not. TryParse is your friend for conversions!
decimal num = 0;
if (!Decimal.TryParse(e.Record["VOUCHER_NO"], out num))
{
//Throw some error, maybe set num to some default and assign...
//The appropriate action in this situation depends on your needs.
}
else
{
//You can safely assign the value
drpayinfo[0]["VOUCHER_NO"] = num;
}
Im using the Mahapps.Metro framework for my C#, Wpf Application.
In the framework is the wpf element: NumericUpDown.
Now I used the element like this:
<Controls:NumericUpDown Name="numCreateArticleStock" Minimum="0"/>
Now I want to convert the entered value in the field into a int value.
Here is my try:
int articleStock = 0;
if(!Int32.TryParse(numCreateArticleStock.Value, out articleStock)
{
await this.ShowMessageAsync("Error", "Error - Message");
}
I get this error:
Cannot convert "double?" in "string"
Maybe someone of you have an Idea, Thanks!
The error you get is because the TryParse method expects as string value, but you have a double? value.
There is no need to parse the value, you can just convert it from double:
int articleStock = (int)numCreateArticleStock.Value.GetValueOrDefault();
The GetValueOrDefault method will turn a null value into 0, I assume that's what you want when there is no value to get from the control.
Since numCreateArticleStock.Value is a double? why not just check if it is null and then cast it to int if it is not null.
int articleStock = 0;
if(!numCreateArticleStock.Value.HasValue)
{
// value is null decide what to do in that case.
}
else
{
articleStock = (int)numCreateArticleStock.Value.Value;
}
I wrote a piece of simple code that I dont to find what the problem.
the code is:
var sortSecurities="SELECT * FROM securities";
int total=0;
var value="";
foreach(var row in db.Query(sortSecurities))
{
value=row.lastGate;
total=Convert.ToInt32(value)*100;// here the problem with compilation..
db.Execute("INSERT INTO holding(IDgrossPortfolio,IDSecurity,totalHolding,units,buyGate) "+"VALUES (#0,#1,#2,#3,#4)",row.category,row.number,total,"100",row.lastGate);
}
what the problem with the convert?
the error is:
Exception Details: System.FormatException: Input string was not in a correct format.
value does not hold a value that can be converted to Int32. If you could do some debugging and see what the value of it is from row.lastGate, you might see what the problem is.
Also, not sure what is returned by db.Query(sortSecurities) (or really what kind of object row.lastGate is), but you can also try to change value=row.lastGate; to value=row.lastGate.ToString();
you can use try parse to check if the value actually contains a number
int total;
bool result = Int32.TryParse(value, out total);
if (result)
{
db.Execute("INSERT INTO holding(IDgrossPortfolio,IDSecurity,totalHolding,units,buyGate) "+"VALUES (#0,#1,#2,#3,#4)",row.category,row.number,total,"100",row.lastGate);
}
Your value isn't successfully being parsed by Convert.ToInt32()
Alternatively, consider using Int32.TryParse() and validate if the data is indeed the type of data you're expecting.
int result;
if(Int32.TryParse(row.lastGate, out result))
{
//row.lastGate was a valid int
total = result * 100;
}
else
{
//row.lastGate wasn't a valid int
}
Thanks you for all... I try now and found elegant answer.
Like I wrote in the comments, becouse I know that the value of row.lastGate
represent a number I don't need to check it.
So I try this and it works:
var sortSecurities="SELECT * FROM securities";
int total=0;
double value=0;
foreach(var row in db.Query(sortSecurities))
{
value=Convert.ToDouble(row.lastGate);
total=Convert.ToInt32(value)*100;//100 is default
db.Execute("INSERT INTO holding(IDgrossPortfolio,IDSecurity,totalHolding,units,buyGate) "+"VALUES (#0,#1,#2,#3,#4)",row.category,row.number,total,"100",row.lastGate);
}
Probably I needed to change the value first of all to double and then to int
Becouse when I try to change it directly to int the Compiler did'nt interpret the
string right, becouse of the dot in the number (type double).
thanks about the the intention..
int a = Convert.ToInt32(subjectsLabel1.Text);
int b = int.Parse(internetLabel1.Text);
int total = a+b;
label1.Text = total.ToString();
the error "Input string was not in a correct format." keeps poping out.
I tried to convert using the "int.parse" and the "convert.toint32" syntax but the same error keeps showing up.
*the values in the subjectsLabel1 and internetlabel1 would be coming from the database (which was done in visual studio) w/ datatype varchar(10).
There is nothing wrong with the way you are parsing those string values to integers. It's just that their value doesn't represent a valid integer so it cannot be parsed and an exception is thrown. You could use the int.TryParse method to handle gracefully this case:
int a;
int b;
if (!int.TryParse(subjectsLabel1.Text, out a))
{
MessageBox.Show("please enter a valid integer in subjectsLabel1");
}
else if (!int.TryParse(internetLabel1.Text, out b))
{
MessageBox.Show("please enter a valid integer in internetLabel1");
}
else
{
// the parsing went fine => we could safely use the a and b variables here
int total = a + b;
label1.Text = total.ToString();
}
If you're not sure the user is giving you a legal Int32 value to convert you can use:
int result;
if (!int.TryParse(subjectsLabel.Text, out result))
{
ShowAMessageToTheUser();
}
else
{
UseResult();
}
Using TryParse won't trow an exception when you try to parse a string. Instead it will return false and the out parameter is not valid to use.
You Cannot convert to Int32 if the string contains a decimal pointor its not a valid integer .Check
string test = "15.00"
int testasint = Convert.ToInt32(test); //THIS WILL FAIL!!!
Because Int32 does not support decimals. If you need to use decimals, use Float or Double.
So in this situation you can use
int.TryParse
also
I am having an issue converting type. I was trying code like this (minimal, detailed code later):
string cityType = "City1";
int listingsToSearch = 42;
if (cityType = "City1") // <-- error on this line
{
listingsToSearch = 1;
}
But "if" statement to convert the cities but I keep getting:
cannot implicitly convert type 'string' to 'bool'
What I'm trying to achieve: I have a search engine that has a textbox for the search text and two radio buttons for the search location ( IE City1 or City2 )
When I receive the search text and radio buttons they are in the form of a string
string thesearchtext, thecitytype;
thesearchtext = HttpContext.Current.Request.QueryString["s"].ToString();
thecitytype = HttpContext.Current.Request.QueryString["bt"].ToString();
When I receive the cities radiobutton they will be in the format of "city1" or "city2".
What i need to do is convert the city radiobuttons into an int so that I can use them in my search dataset. I need to convert "city" to integer 1 and "city2" to integer 2.
I understand this is probably a simple type conversion however I just cannot figure it out. So far code with if gives me error above:
int listingsToSearch;
if (thecitytype = "City1")
{
listingsToSearch = Convert.ToInt32(1);
}
else
{
listingsToSearch = Convert.ToInt32(2);
}
c# equality operator is == and not =:
if (thecitytype == "City1")
Here is some code in you can use with NUnit that demonstrates another technique for calculating listingToSearch - You will also notice that with this technique, you won't need to add extract if/else, etc as you add more cities - the test below demonstrates that the code will just try to read integer starting after "City" in the radio button label. Also, see the very bottom for what you could write in your main code
[Test]
public void testGetCityToSearch()
{
// if thecitytype = "City1", listingToSearch = 1
// if thecitytype = "City2", listingToSearch = 2
doParseCity(1, "City1");
doParseCity(2, "City2");
doParseCity(20, "City20");
}
public void doParseCity(int expected, string input )
{
int listingsToSearch;
string cityNum = input.Substring(4);
bool parseResult = Int32.TryParse(cityNum, out listingsToSearch);
Assert.IsTrue(parseResult);
Assert.AreEqual(expected, listingsToSearch);
}
In your regular code you can just write:
string thecitytype20 = "City20";
string cityNum20 = thecitytype20.Substring(4);
bool parseResult20 = Int32.TryParse(cityNum20, out listingsToSearch);
// parseResult20 tells you whether parse succeeded, listingsToSearch will give you 20