How to access integer data from a DataTable?
I do this to get a string:
tbEvent.Text = dt.Rows[0].Field<String>(0);
But this doesn't work:
int numb = dt.Rows[0].Field<Int>(0);
Regards,
Tea
int i = Convert.ToInt32(dt.Rows[0]["field_name"]);
Try this :-
tbEvent.Text = dt.Rows[0].Field<Int>(0).ToString();
I'm assuming your trying to pass the value to a Textbox.
Use strongly type access !
if your type is int ,
this
string g = dt.Rows[0].Field<String>(0);
will fail !
Unable to cast object of type 'System.Int32' to type 'System.String'
However if you know its int and you want to show its string represenation : ( or just ToString())
string t= dt.Rows[0].Field<int>(0).ToString();
or just : dt.Rows[0][0].ToString();
The Field extension method does not convert the type appropriate. It just simulates a strongly typed DataTable. So if you know that the type of the DataColumn is int it works this way:
int result = dt.Rows[0].Field<int>(0);
But if it actually comes as string you need to convert/parse it accordingly.
For example:
int result = int.Parse(dt.Rows[0].Field<String>(0));
or even more loosely typed (f.e. because it's a double or you don't know what it is)
int result = int.Parse(dt.Rows[0][0].ToString());
Related
i have column in database with Int data type, but textbox don't allows null. it gives error "Input string was not in a correct format".
objinsert.VehGrpID = Convert.ToInt32(txtVehGroupID.Text);
Use TryParse instead.
int GrpID = 0;
int.TryParse(txtVehGroupID.Text, out GrpID)
if(GrpID > 0)
objinsert.VehGrpID = GrpID;
You can just special-case out empty values. I am, of course, assuming here that an empty value should map to null.
objinsert.VehGrpID = string.IsNullOrWhiteSpace(txtVehGroupID.Text) ? null : (int?)Convert.ToInt32(txtVehGroupID.Text);
You'll also want to adjust your code to set the textbox's text accordingly.
Your question is also a bit unclear, because you say the textbox won't allow nulls, but you haven't shown us any code that adjusts the textbox text.
You can also use DBNull.Value Field. If a database field has missing data, you can use the DBNull.Value property.
check this link http://msdn.microsoft.com/en-us/library/system.dbnull.value%28v=vs.110%29.aspx
try this
int VehGrpID = Convert.ToInt32(txtVehGroupID.Text);
OR
int VehGrpIDtxtVehGroupID.Text = int.Parse(txtVehGroupID.Text);
The Text property of your textbox is a String type, so you have to perform the conversion in the code.
I am using Simple.Data and want to know if I can Select a single column and then cast it to a list of string values. For example using the query below I get the error:
Cannot implicitly convert type 'Simple.Data.SimpleRecord' to 'string'
var result = _database.ParentRegionList.All()
.Select(_database.ParentRegionList.RegionName)
.Where(_database.ParentRegionList.RegionName.Like(startsWith + "%"))
.Distinct()
.ToList<string>();
However if I create a class LocationAutoComplete that has a single public property "RegionName" of type string then the cast works fine.
var result = _database.ParentRegionList.All()
.Select(_database.ParentRegionList.RegionName)
.Where(_database.ParentRegionList.RegionName.Like(startsWith + "%"))
.Distinct()
.ToList<LocationAutoComplete>();
The ToList<T> Simple.Data method expects you to be casting the contents of a SimpleRecord to an object, which is why it works with your LocationAutoComplete class. Full details can be found here.
If you are returning only one field which you wish to return as a scalar value or a list of scalar values, use the ToScalar<T> or ToScalarList<T> method instead. Full details can be found here
If RegionName is a varchar then all you need is
var result = _database.ParentRegionList.All()
.Where(_database.ParentRegionList.RegionName.Like(startsWith + "%"))
.Select(_database.ParentRegionList.RegionName)
.Distinct()
.ToList();
You don't need the <string>
I have an asp.net 4 textbox control that has it's text being dynamically populated by some java script. A Google Maps call to be exact. It's giving me mileage from 1 point to another. When the text displays, it shows " 234 mi" I need to get rid of the "mi" part of this text because the text is being converted to an Int32 Updating a table in my DB.
Basically I can only have an INT. Nothing else in the text box. How do I get rid of the "mi" at the end of the text?
Thanks
C#
EB
On the postback, before you save it you could:
var saveValue = Int32.Parse(tbTarget.Text.Replace("mi", string.Empty).Trim());
If your working with a variable length of chars (say someone enters miles instead) then your must do a foreach against the string (an array of char) and check isnumeric on each char.
A simple String.Substring works also:
String leftPart = TxtMileAge.Text.Substring(0, txt.IndexOf(' '));
int mileAge = int.Parse(leftPart);
This retrieves the part of the String in the range of 0 - indexOfWhiteSpace and converts it to an int
Edit: Since the value can have decimal places (as you've commented), you need to parse it to double, round it and then cast it to int:
var txtEstDistance = new TextBox() { Text = "40.2 mi" };
String leftPart = txtEstDistance.Text.Substring(0, txtEstDistance.Text.IndexOf(' '));
double distanceMiles = double.Parse(leftPart, System.Globalization.CultureInfo.InvariantCulture);
int oDdstanceMiles = (int)Math.Round(distanceMiles, MidpointRounding.AwayFromZero);
I'm trying to add comma separators to a number. I've tried the advice here: add commas using String.Format for number and and here: .NET String.Format() to add commas in thousands place for a number but I can't get it to work - they just return the number without commas. The code I'm using is here:
public static string addCommas(string cash) {
return string.Format("{0:n0}", cash).ToString();
}
Where am I going wrong?
Thanks.
Update: Hi all, thanks for your help, but all of those methods are returning the same error: "error CS1502: The best overloaded method match for 'BishopFlemingFunctions.addCommas(int)' has some invalid arguments" (or variations therof depending on what number type I'm using.) Any ideas?
Well, you are sending in a string. it looks like you want a currency back
Why are you passing in a string to the method if it is a numeric value?
String.Format will return a string so there is not need to .ToString() it again.
{0:c} = Currency format if you do not want the $ then use {0:n}
Not sure you have to but you may need to do an explicit conversion if you pass it in as a string to (decimal)cash
return String.Format("{0:c}", (decimal)cash);
or
return String.Format("{0:n}", (decimal)cash);
but i think it should be something like:
public static string addCommas(decimal cash)
{
return String.Format("{0:c}", cash);
}
but this is such a simple statement i do not see the logic in making it a method, if you method is one line, in most cases, its not a method.
In order to apply number formatting you have to pass cash as a number type (int, double, float etc)
Note the cash parameter is of type double and the .## at the end of the formatted string for cents.
EDIT
Here is the code in its entirety:
static class Program {
static void Main() {
double d = 123456789.7845;
string s = addCommas(d);
System.Console.WriteLine(s);
}
public static string addCommas(double cash) {
return string.Format("${0:#,###0.##}", cash);
}
}
This prints "$123,456,789.78" to console. If you're getting
error CS1502: The best overloaded
method match for 'addCommas(double)'
has some invalid arguments
check to make sure that you're calling the function properly and that you're actually passing in the correct data type. I encourage you to copy/paste the code I have above and run it - BY ITSELF.
i have a method on my custom class to convert any numbers
public static string ConvertToThosandSepratedNumber(object number)
{
string retValue = "";
retValue = string.Format("{0:N0}", Convert.ToDecimal(number));
return retValue;
}
Here is a fairly efficient way to Add commas for thousands place, etc.
It is written in VB.net.
It does not work for negative numbers.
Public Function AddCommas(number As Integer) As String
Dim s As String = number.ToString()
Dim sb As New StringBuilder(16)
Dim countHead As Integer = s.Length Mod 3
If countHead = 0 Then countHead = 3
sb.Append(s.Substring(0, countHead))
For I As Integer = countHead To s.Length - 1 Step 3
sb.Append(","c)
sb.Append(s.Substring(I, 3))
Next
Return sb.ToString()
End Function
In asp classic and vbscript, you can declare a Const with a hexidecial value, and a date type value:
Const C_LIGHTCYAN = &hCCFFEE
Const C_STARTDATE = #1 JAN 2000#
But how can I declare currency, single or doubles data types?
Const C_LONG = 1024 '# I want this to be a LONG, not an INT!
I'm sure I've seen something like Const C_LNG = L12345 or some other prefix/suffix combination for longs or doubles but can't find the source now
You can't declare variables with data types in ASP just set the value in decleration, that should work fingers crossed.
I don't think there is currency type anyway. For double you can 1.00 etc.
Here is the CLng function for VBScript. But since you can't declare use a function for a constant declaration, and you can't re-assign to a constant, do you really have to use constants here?
While you can't declare data types in Windows Scripting (VBScript, ASP), you can assign a variable to become a type, then verify that variable's type. VBScript provides no type protections, so you're allowed to reassign a declared variable to a different type. This loose typing strategy is one root of problems.
Dim textVariable : textVariable = "Hello World!"
WScript.Echo TypeName(textVariable)
' Returns Text
Dim integerVariable : integerVariable = 6
WScript.Echo TypeName(integerVariable)
' Returns Integer
Dim objectVariable : set objectVariable = CreateObject("Scripting.Dictionary")
WScript.Echo TypeName(objectVariable)
' Returns Object
Some types require some brute force and trickery. The binary datatype is one example.
Dim generateData(1) : generateData(0) = &HFF
Dim mem : Set mem = CreateObject("System.IO.MemoryStream")
mem.SetLength(0)
mem.WriteByte (generateData(0))
Dim byteArray : byteArray = mem.ToArray()
'Returns a VB Style, "Byte()" [Byte Array]