The problem when I try to read nullable value in c# - c#

I am trying to read my database. I have an column stores int values or null values. When I try to read this column i normally use this line of code;
int Score = Convert.ToInt32(reader["Score"]);
but it can be null. So i cant convert it to int. Then I tried ;
bool tryGetScore = int.TryParse(reader["Score"], out player1Score);
but i cant parse this value neither. It says "Cannot convert from 'Object' to 'System.ReadOnlySpan'"
How can i read this value. Whenever i face a null, my program crashes

You can try use isDbNull for example
int scoreIdx = reader.GetOrdinal("Score");
int score = reader.IsDbNull(scoreIdx) ?
0 : reader.GetInt32(scoreIdx);

Related

Can't read Excel cell value in Visual C#

I read How to read single Excel cell value and tried it myself. But when I gets to
string s = (myExcelWorkSheet.Cells[3, "E"] as Excel.Range).Value2.ToString();
Everything was terminated and the form was shown.
//Everything worked fine here.
string s = (myExcelWorkSheet.Cells[3, "E"] as Excel.Range).Value2.ToString();
//Everything after this was all skipped!
Why is this, and how can I fix it?
The problem with reading excel cell is that if there is nothing in it, the cell object is Null. Thus, it does not have .Value2 neither .Value.
To find a way how to avoid the check for Null, you may use Convert.ToString() which evaluates the Null to an empty string and thus does not return an error:
for (int i = 1; i < 5; i++)
{
string a = Convert.ToString(wk.Cells[i, 1].Value2);
Console.WriteLine(a);
}
When the cell has a value, you need the ToString().
And when the cell doesn't has a value, then you don't need the ToString()!
Otherwise the whole program will skip out and everything after that was NEVER executed!!!
So I guess it's just a problem of if the system was trying to cast a null value into a string or not!!!

C# convert .value to int

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;
}

How to read a decimal value of order 0.000e-6 from a SqlDataReader in C# double variable

I am trying to read some decimal values from my DB. These values are the order of 10-6. I am trying to read it into a double variable in C# using code like this: sqltype in database is "float". sample value to be read is "1.99999999495049E-06" –
Double [] rmseValues = null;
while (dataReader.Read())
{
// This shows my datatype is float (sql)
string temp = dataReader.GetDataTypeName(0);
// This returns a value of "0"
string temp1 = dataReader.GetOrdinal("RmseAll").ToString();
// This throws exception of invalid typecast
rmseValues[0] = dataReader.GetFloat(0);
}
Try to use GetDouble(0) instead of GetFloat(0)
I think you will also need to edit that line :
Double [] rmseValues = null;
In fact your are trying to put values inside a null object as solution you need to initialize your rmseValues array or just use a List of double
Double[] rmseValues = new Double[10];
Use GetInt64(0) instead of GetFloat(0)
In order not be dependent on RDBMS actual background type (say, NUMBER(10, 3) or alike) and its representation as .Net Type (e.g. Single) do a conversion:
// rmseValues[0] should be Double
rmseValues[0] = Convert.ToDouble(dataReader.GetValue(0));

convert variable in asp.net

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..

String won't convert to int ready for query

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)

Categories