I am trying to convert a field from a string to an int, then pass it to a query using tableadapters.
I have the following function:
protected String countResponses(String value)
{
String input = value.ToString();
int fordb = Int32.Parse(input);
FrontendTableAdapters.ForumTableAdapter ta = new FrontendTableAdapters.ForumTableAdapter();
DataTable table = ta.CountPosts(value);
if (table.Rows.Count > 0)
{
return table.Rows[0].ItemArray[1].ToString();
}
else
{
return "Unknown";
}
}
It is working greate up to putting it in CountPosts() where I get the following error:
Error 4
Cannot implicitly convert type 'object' to 'System.Data.DataTable'. An explicit conversion exists (are you missing a cast?) C:\Users\Dave\Desktop\WebApps\Figmentville\Figmentville\yoursay\Default.aspx.cs 49 31
I think this is because it is looking for an int. But haven't I already converted it to an int?
Thanks
Dave.
Since we don't know what ForumTableAdapter is, it isn't clear what CountPosts returns, but if this is actually returning a DataTable (but typed as object) it sounds like you just want:
DataTable table = (DataTable)ta.CountPosts(value);
but then, I also expect Count... to return an int...
Also; minor point: the line String input = value.ToString(); is both unnecessary and potentially a cause of a null bug (but not in this case) - you should be able to just use:
int fordb = int.Parse(value);
(and remove the input variable completely)
you are passing in value which is the string parameter, you have parsed it into the variable fordb, thats the int you should pass in
edit
also, why do you ToString value when that pararameter is already a string (when you pass the output into the variable input)
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;
}
Good Day Everyone,
As of now im stuck with this error
Error Converting data type 'Numeric' to Decimal
this is my code
AddManualItems AddReconItem = new AddManualItems();
UserAccess user = new UserAccess();
AddReconItem.BranchCode = BranchCodeTextBox.Text;
AddReconItem.ForLoanMonth = YearDropDownList.SelectedValue + "/" + MonthDropDownList.SelectedValue;
AddReconItem.ItemWeight = Convert.ToDecimal(WeightTextBox.Text);
AddReconItem.PrincipalAmount = Convert.ToDecimal(PrincipalTexAmTextBox.Text);
AddReconItem.PawnTicket = PwnTicketTextBox.Text;
AddReconItem.ItemStorageGroup = Convert.ToInt16(StorageNameDropDownList.SelectedValue);
AddReconItem.ReconID = Convert.ToInt16(ReconTypeDropDownList.SelectedValue);
user.UserID = Session["UserID"].ToString();
string a = servs.AddItemRecon(user, AddReconItem); // this is where the error appears in debug mode
the code inside of the ADDitemRecon(User,AddReconItem) is this
using (SqlConnection reportsConn = new SqlConnection(sqlConnWriter))
{
reportsConn.Open();
SqlCommand AddReconItem = new SqlCommand();
AddReconItem.Connection = reportsConn;
AddReconItem.CommandType = CommandType.StoredProcedure;
AddReconItem.CommandText = "Updater.usp_AddReconcileItems";
AddReconItem.Parameters.AddWithValue("#ITEMWEIGHT", Convert.ToDecimal( items.ItemWeight));
AddReconItem.Parameters.AddWithValue("#ITEMPRINCIPALAMT", Convert.ToDecimal(items.PrincipalAmount));
AddReconItem.Parameters.AddWithValue("#FORLOANMONTH", Convert.ToDateTime(items.ForLoanMonth));
AddReconItem.Parameters.AddWithValue("#STORAGEGROUPID", items.ItemStorageGroup);
AddReconItem.Parameters.AddWithValue("#BRANCHCODE", items.BranchCode);
AddReconItem.Parameters.AddWithValue("RECONID", items.ReconID);
AddReconItem.Parameters.AddWithValue("#PAWNTIX",items.PawnTicket);
AddReconItem.Parameters.AddWithValue("#CREATEDBY", user.UserID.ToString());
AddReconItem.ExecuteNonQuery();
}
my property for ItemWeight is
private decimal itemWeight;
public decimal ItemWeight
{
get { return itemWeight; }
set { itemWeight = value; }
}
i bet the error is in the item weight because when i input in the item weight
12345.12 it works fine, but when i input 1234 instead of treating it as 1234.00 it treats it as 1234 only making it numeric..
any help? i do not know if my conversions are wrong
By the way my field in database is
fld_ItemWeight (decimal (38,6), not null
EDIT**
Is there any bugs known in Decimal?? im using VS 2005 as of now.
Found The answer! my stored Procedure is wrong i have decimal(9,6) in my stored procedured making it accept 3 digits or less !changed it to (18,2)\
Although the original poster has found his solution, for the benefit of other people, I thought I would post what caused it for me.
System.Data.SqlClient.SqlException : Error converting data type numeric to decimal.
Sadly the message doesn't say which parameter it is having the problem with. So I changed all of the parameters that I was passing through to have a value of 0 (which is a suitable value for most SQL types, you may need to use other values), this made the error go away. I could then put them back to normal, one by one, and each time, I re-tested. That's how I worked out which parameter had the problem.
It turned out that for one of the parameters the value that I had in my code (a C# decimal) was too large to go in the decimal(7,2) stored procedure parameter.
I don't know what the proper solution for this issue , But i have one idea. Like
Change your ItemWeight property DataType decimal to string
decimal xxxyyy = Convert.ToDecimal(WeightTextBox.Text);
if(!xxxyyy .ToString().Contains(".00))
{
AddReconItem.ItemWeight=xxxyyy.ToString() +".00";
}
else
{
AddReconItem.ItemWeight=xxxyyy.ToString() ;
}
Edit :
Try this another way for use math.Round()
AddReconItem.ItemWeight = Convert.ToDecimal(WeightTextBox.Text);
AddReconItem.ItemWeight=Math.Round(AddReconItem.ItemWeight,2);
Try to round your value in set.
private decimal itemWeight;
public decimal ItemWeight
{
get { return itemWeight; }
set { itemWeight = Math.Round(value,yourPrecisionHere); }
}
Change Sql column to Decimal(18,2), Same in store procedure and take SqlDbType.Decimal at ado.net end
My problem was that the column had the right precision and scale(16,2) but the variable I was using as a parameter in the procedure hadn't(14,2).
So, when trying to insert something like 99999999999999 using the procedure, I was getting the error Error converting data type numeric to numeric.
when you are calling a procedure and it has a parameter with a decimal datatype then you can pass only in fractions. For more details please refer Error converting data type numeric to decimal
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..
Inside a c# UDF for excel 2007, I need to evaluate the value of Excel function parameters (don't ask why, long story).
Let's say we have this Excel function to evaluate :
=afunctionname("2009-01-01" ; "B4" ; "foo" ; concatenate("a";"b") )
My goal is to get a string with :
=afunctionname("2009-01-01" ; "value of B4 cell" ; "foo" ; "ab" )
I evaluate the value of the params thank to this snippet :
Object comObject = app.Evaluate(param); //app = Microsoft.Office.Interop.Excel.Application
String value = getValueFromComObject(comObject);
getValueFromComObject detail :
private static String getValueFromComObject(Object comObject) {
if ((comObject as Range) != null)
{
Range rge = ((Range)comObject);
switch (Type.GetTypeCode(rge.Value.GetType()))
{
case TypeCode.DateTime:
return ((DateTime)rge.Value).ToShortDateString();
default:
return rge.Value.ToString().Trim();
}
}
else
{
return comObject.ToString();
}
}
The fist and third params of our example directly return as String by application.Evaluate . The second param is return as a range and correctly managed thank to the type casting.
The problem is for the fourth param, I dont know witch cast type I have to apply on the evaluation of the concatenation function, it's obviously not a range and the toString() gives me the reference : -2146826273
Any idea?
Ok I found the problem :) !
First of all the return type is an Int32 and the return value correspond to the error code #value according to this page : How to know if a cell has an error in the formula in C#
Actually, the lengh of the Strings were too long for the concatenate function in eval mode, I have try in Excel it works but with eval it gives me an error. So I just had to reduce the lengh of each string in concatenate method (add more params) and it works.
Thank you all for your help.
In C Sharp, to evaluate a formula we set in string "," to separate the arguments. In the native excel application we put ";". To evaluate static values (e.g.: CONCATENATE("a","b") ), we use "Application.Evaluate" method. To evaluate values in cells (e.g.: CONCATENATE(A1,B1) ) we use Application._Evaluate.