I have a table that I fill with one Repeater and one SQL query. Then, I want to color one of the columns depend of the result of one operation. But the problem is that I want to compare one column with another(more specific, intColumn1 <= intColumn2), but I cannot convert the Label into Int (both columns are ints)
I have this code:
Label lblStock = (Label)rptItem.FindControl("lblStockOLD");
int intStock = Convert.ToInt32(lblStock.Text);
And I try to lblStock without ".Text" in the convertion. The display error is this:
Input string was not in a correct format.
What can I do?
I would prefer to approach this problem by calculating the difference in int BEFORE you bind the data to the repeater. However if you have to get the string out of the label and convert it back to int, and the field is nullable, you must do null checking first.
Label lblStock = (Label)rptItem.FindControl("lblStockOLD");
//assume intStock is null and make sure you check for intStock.HasValue later.
int? intStock = null;
if (!string.IsNullOrWhiteSpace(lblStock.Text)) {
intStock = Convert.ToInt32(lblStock.Text);
}
"Input string was not in a correct format." means that what your trying to convert to an int is not a correct int. You could use Int.TryParse for better error handling. if the .Text contains a correct integer value it should be able to convert it. Also keep in mind that if you run the code before filling up the label it will also give errors .
Related
I'm trying to display a list of all Deliveries with the status Dispatched. However, its only returning the number value of the status as opposed to the actual string value. I think this is because I have used Enum to store my status values?
I wish to display the word Dispatched instead of the number value that it represents in the Enum.
I'm developing in ASP.Net MVC and I'm using the query builder in VS2013.
I'm not sure how to approach this, can anyone please suggest an easy to understand solution using SQL.
Let me know if any additional code is required, and thank you in advance!
Here's the Query I want but it doesn't work:
SELECT Delivery.[Status],
COUNT(Delivery.DeliveryID) AS Dispatched_Status
FROM Delivery
WHERE Delivery.[Status] = 'Dispatched'
GROUP BY Delivery.[Status];
Here's the Query that does work but returns a number value. I tried it this way because Enum stores the string value as a number:
SELECT Delivery.[Status],
COUNT(Delivery.DeliveryID) AS Dispatched_Status
FROM Delivery
WHERE Delivery.[Status] = '1'
GROUP BY Delivery.[Status];
P.S I'm aware that status is a reserved word - will be following the correct naming conventions in future.
Delivery Table Definion
It sounds like you just need to add a lookup table in you DB. Something like
CREATE TABLE [dbo].[StatusLookup](
[StatusID] [int] NOT NULL,
[StatusName] [varchar](64) NOT NULL,
[StatusDescription] [varchar](max),
)
INSERT INTO [dbo].[StatusLookup]([StatusID],[StatusName],[StatusDescription]
VALUES(1, 'Dispatched', 'A dispatched record')
...
Note you'll have to manually do this and make sure to populate it with values that match up with your enum.
Then your query would be
SELECT StatusLookup.[StatusName],
COUNT(Delivery.DeliveryID) AS Dispatched_Status
FROM Delivery
JOIN StatusLookup ON Delivery.Status = StatusLookup.StatusID
WHERE StatusLookup.[StatusName] = 'Dispatched'
GROUP BY StatusLookup.[StatusName];
Enums are stored as integers by default.
You can add a separate varchar or nvarchar field to your database table to hold the description of the enum, and populate it using something like the below:
string selectedEnumDescription = Enum.GetName(typeof(DeliveryStatusEnum), Delivery.Status)
The exact implementation depends on how you are saving your records, and what the actual properties and enum names are.
You can then just select the description column in your SQL query.
Either that or you could store the actual enum values and descriptions within a separate table and do a join.
You can store enum in database as a number, usually a small number - the exact type depends on your database. When you read it - you convert a number to enum and work in your code with the enum. When you need to display it, you can call a ToString() method on that enum, for example
public enum Foo
{
A,
B
}
public class Program
{
public static void Main()
{
Console.WriteLine(Foo.A.ToString()); // Prints A
}
}
See it working
You can also use description attribute and print that, see examples here and here
I just wrote a simple method to get some data from an SQL server and store it in a DataTable.
Specifically the value is an integer : 666
It is an int datatype on the database and I made a variable called Credits in C# which is also an integer.
The datatable shows the value 666 in the first row so it got added without any problems.
The problem happens when I try to assign Credits = dt.Rows[0] saying
the inputstring was an incorrect format
Ive tried parsing it to an int and adding .ToString() but no matter what it gives the same error.
the latest line I tried was
Credits = Convert.ToInt32(dt.Rows[0].ToString());
But still no luck. I have looked everywhere online for a solution but I cannot find the problem.
Any help would be greatly appreciated.
You are missing column name while selecting data from Data Table. You can either use column name or column index.
int Credits = Convert.ToInt32(dt.Rows[0]["columnname"].ToString());
Please make sure that value of that column value should not be null or empty.If thats the case you have to check that before assigning to int variable.
Or You can use, TryParse
int Credits = int.TryParse(dt.Rows[0]["columnname"].ToString());
You can't assign a entire row inside a variable
string Credits = Convert.ToInt32(dt.Rows[0]["columname"].ToString());
I have a C# List with one particular column as of DateTime.
I have to bind this column to CategoryAxis of Silverlight Chart - hence looking for converting this DateTime column to String type with formatting as .ToString("dd-MMM-yy") without altering any sort order.
Any inputs?
Add one more field in list and store the string date in it using for each loop.
add one more read-only wrapper property to it, something like:
public string StrDT
{
Get
{
return myDateTime.ToString("dd-MMM-yy");
}
}
then bind this field to wherever you like...
I have a column on an asp.net Gridview whose type is an enumeration. I display the description of the enum on the UI, and save the int value in the database. This is my enum definition
public enum ItemStatus : int
{
[DescriptionAttribute("New Item")]
New = 0,
[DescriptionAttribute("Closed")]
Closed = 1,
[DescriptionAttribute("Not Assigned")]
Unassigned = 2,
[DescriptionAttribute("Assigned")]
Assigned = 3
}
I save this ItemStatus as an Int in the database and users see the enum string value (like Not Assigned) on the UI. Users should be able to do a sorting (Asc,Desc) on this column in the Grid.
Since I save this as an int in the Database, after I "hydrate" the object, the ItemStatus column on the UI is not sorted alphabetically. Users expect this to be sorted alphabetically on the UI.
I cant think of a way to do that.I use Asp.net and C#
Thanks in advance
I think you've got two options here:
Create a view that contains the Text value, and use that to populate the Grid. That way, you can sort on the text value, rather than attempting to sort on the numeric key value.
Pull back all your results, and sort in memory.
Beyond that, I can't really see any option you have. If you attempt to sort on the key column, it's always going to sort numerically - because that's the data in the column.
I have a class Cust_Result that accepts an integer parameter.
So on my main page when it loads I bind a formview to display the data that I retrieved. Now I would like to extract the value of my "id" label and assign it to a variable which I can than pass to my Cust_Result class but I keep receiving this error
"Unable to cast object of type 'System.Web.UI.WebControls.Label' to
type 'System.IConvertible'."
I am assuming it is because I am trying to send a string value to a parameter that is wanting an integer value but I am unsure on how to do the conversion.
My code
int cust;
cust = (Convert.ToInt32(FormView1.Row.FindControl("ID")));
You need a string to convert and that's the Label.Text property (not just the Label).
I'll split it into 2 steps:
Label lbl = FormView1.Row.FindControl("ID") as Label;
// option to bail out when lbl == null
cust = Convert.ToInt32(lbl.Text);
First convert the control to a Label
var label = (Label)FormView1.Row.FindControl("ID");
Then you can get the value in the label:
var cust = int.Parse(label.Text);
Look at the compiler error closely - it doesn't say anything about string and int - it's talking about IConvertible and Label - although the fact that it mentions Label instead of Control suggests that's not the code you've actually posted. Convert.ToInt32 doesn't konw what to do with a Control or a Label - in this case, I believe you want the text of the label, so I'd write this:
Label label = (Label) FormView1.Row.FindControl("ID");
// Potentially check for "label" being null here, i.e. the control wasn't found
int cust = Convert.ToInt32(label.Text);
It's not entirely clear where this value came from, but you may want to consider using int.TryParse instead of Convert.ToInt32, too.
I'd also note that Cust_Result is an unconventional name - try to:
Avoid abbreviations (Cust means Customer, I assume?)
Don't use underscores
Try to give more meaningful names - even CustomerResult doesn't really explain what it's the result of.