Can not convert int to string - c#

I have this code:
int CityID= ((User)Session["LoggedInUser"]).CityID;
//When I debugg I get CityID = 7 here
ddlCity.Items.FindByValue(CityID).Selected = true;
And an error that I can not convert from int to string on the bottom line. How can I make it possibel?

FindByValue expects a string value so you have to convert CityID to a string.
Try this :
ddlCity.Items.FindByValue(CityID.ToString()).Selected = true

Parameter type should be string, not int, so just use built in ToString():
ddlCity.Items.FindByValue(CityID.ToString()).Selected = true;
MSDN: ListItemCollection.FindByValue() method
public ListItem FindByValue(
string value
)

Looks like FindByValue takes "String". Use CityId.ToString(CutureInfo.InvariantCulture) instead of CityId.

you will need to cast the integer to a string. This can be done in one of two ways
calling ToString() method
ddlCity.Items.FindByValue(CityID.ToString()).Selected = true;
This could raise a null reference exception if CityID is null.
Using ConvertToString()
ddlCity.Items.FindByValue(Convert.ToString(CityID)).Selected = true;
Also it is probably wise to check that the FindByValue method is not returning null as this will also cause a null reference exception when you attempt to set Selected = true

Related

String.IsNullOrEmpty check with Data Table cell

If I have a Data Table and I want to see if the value contained within a specific cell is empty I would use this.
foreach(DataRow row in DataTable.Rows)
{
bool isEmpty = String.IsNullOrEmpty(row["MyColumn"].ToString());
}
but what happens if the value in row["MyColumn"] is null. Wouldn't the .ToString() throw an exception? Yet when I try the following ..
bool isEmpty = String.IsNullOrEmpty(row["MyColumn"]);
I get an invalid argument exception because the IsNullOrEmpty() method is looking for a string object.
So what is the proper way to check if a specific cell in a Data Table is empty or null?
Change your statement to this,
bool isEmpty = String.IsNullOrEmpty(row["MyColumn"]?.ToString());
?. means run the process .ToString() only if row["MyColumn"] is not null.
Basically just adding this for the sake of completeness... but if for some reason you aren't using C# 6 or above, you can always do it the "old fashioned way":
bool isEmpty = row["MyColumn"] == null || string.IsNullOrEmpty(row["MyColumn"].ToString());
You could instead use the Field<T>() method of the DataRow:
bool isEmpty = String.IsNullOrEmpty(row.Field<string>("MyColumn"));
This provides strongly typed access to the row values.
You can use it with other types too, so no need to parse int or DataTime, for example.
var myDate = row.Field<DateTime>("MyDate"); // DateTime
var myInt = row.Field<int>("MyInt"); // int
It also works with nullable types:
var myDate = row.Field<DateTime?>("MyDate"); // DateTime? (Nullable)
if (myDate.HasValue)
{
...
}

Cannot implicitly convert type 'string' to 'int' errors

I want to save the information entered in ASP.NET to the database and display it in GridView but the information that needs to be entered is dropdownlist selected.
The IDs of the elections held are kept.
int birim =Convert.ToInt32(DDLbirim.SelectedValue);
and
int birim=(int)DDLbirim.SelectedValue;
I write but in the form of an error. How can I help you track a way?
There are several ways to convert a string to int.
Convert.ToInt32 is one of them, but like int.Parse, it raises an exception if your string is not a numeric
To avoid the exception, you can use TryParse
The TryParse method is like the Parse or Convert.ToInt32 method, except the TryParse method does not throw an exception if the conversion fails.
bool isSuccees= Int32.TryParse(DDLbirim.SelectedValue, out birim );
I think your DDLbirim.SelectedValue is not a valid int so it can not cast it to a int hence the exception.
I would do an int.TryParse to check if the value is a valid int.
bool successfullyParsed = int.TryParse(DDLbirim.SelectedValue, out birim);
if (successfullyParsed){
// ...
}
The selectedValue is null when the dropdown isn't selected as valid. Else, as long as each item in the dropdown have a valid value, it will return as proper
The value is of type object, as it can store any type available.
Make sure that the values being set in the designer or backend are indeed integer and not string. Good way to identify would be as
if (ddlBrim.SelectedIndex >=0) {
var value = ddlBrim.SelectedValue;
// Inspect value in debugger to validate at this point
int intValue = -1;
if (Int32.TryParse(ddlBrim.SelectedValue, out intValue) {
// use the result value here
}
}
If DDLbirim.SelectedValue is null or if contains non-integer value you have to use TyrParse. TryParse handles nulls and invalid strings
int birim=0;
if (int.TryParse(DDLbirim.SelectedValue, out birim)){
}
Please make sure that you correctly bind the dropdownlist i.e. with displayMember, ValueMember (field must be parsable to the integer value), and Datasource.
Once it's fine, you can try to parse it.

Handling Null values in GetSQLDateTime and GetSQLMoney

AS part of an import I'm writing I'm using parameterised values, however the database i'm exporting to cannot handle NULL values, so I need to find a way to handle NULL values.
The closest I've gotten is:
if (tenantexportReader.GetSqlMoney(8).ToDecimal().Equals(null))
{
tenantimportCommand.Parameters["PRICEFINAL"].Value = "0.00";
}
else
{
tenantimportCommand.Parameters["PRICEFINAL"].Value = tenantexportReader.GetSqlMoney(8).ToDecimal();
}
and A similar thing with SQLDateTime
if (tenantexportReader.GetDateTime(9).ToShortDateString().Equals(null))
{
tenantimportCommand.Parameters["TENSDATE"].Value = "0.00";
}
else
{
tenantimportCommand.Parameters["TENSDATE"].Value = tenantexportReader.GetDateTime(9).ToShortDateString();
}
However this does not appear to work, instead I receive the following:
Message=Data is Null. This method or property cannot be called on Null values.
Instead of
if (tenantexportReader.GetSqlMoney(8).ToDecimal().Equals(null))
you should probably use
if (tenantexportReader.IsDbNull(8))
Since the value in the database is NULL (which is DbNull.Value in c#), I assume that GetSqlMoney and GetSqlDateTime throw the exception you received. DbNull.Value cannot be converted to SqlMoney or DateTime.
Check if the value is null via IsDbNull before calling GetSqlMoney or GetSqlDateTime.
So your final if statements should look something like this:
if (tenantexportReader.IsDbNull(8))
{
tenantimportCommand.Parameters["PRICEASK"].Value = "0.00";
}
else
{
tenantimportCommand.Parameters["PRICEFINAL"].Value = tenantexportReader.GetSqlMoney(8).ToDecimal();
}
Why would you assign a string to a monetary value???
Probably what you would want to do is like this:
var priceFinal = tenantexportReader.GetSqlMoney(8);
tenantimportCommand.Parameters["PRICEFINAL"].Value = (decimal)(priceFinal.IsNull ? 0 : priceFinal);
I really don't understand why you set it to "0.00" (string) when it is null and to a decimal value when it is not null.
And also for date/datetime values, again, why do you ever use string conversions and invite errors? Simply pass a date as a datetime.

C# checking for undefined variable received via querystring from JQuery/Ajax call

There are many questions discussing this topic with ref to Javascript; but I could not get any with ref to C#.
Both the 'String........' statements below return false.
// foll querystring value from JQuery/Ajax call
var thisfieldvalue = Request.QueryString["fieldvalue"];
bool boola = String.IsNullOrWhiteSpace(thisfieldvalue );
bool boolb = String.IsNullOrEmpty(thisfieldvalue );
What is the best way to check for Undefined string variable in C#?
Note:
I get 'Undefined variable' values occasionally, via the JQuery/Ajax calls with the 'querystring'; and it ends up in the C# variable when I use the statement
var thisfieldvalue = Request.QueryString["fieldvalue"];
and the 'thisfieldvalue' variable passes both the 'String.IsNullOrWhiteSpace' as well as the 'String.IsNullOrEmpty' checks....
Note 2: I have edited the question again to make my question clearer... I am sorry that earlier it was not that clear....
you could use either
string Undefined_var = "[value to test goes here]"; //note that string must be assigned before it is used
bool boola = String.IsNullOrWhiteSpace(Undefined_var);
//or
bool boolb = String.IsNullOrEmpty(Undefined_var);
Difference being that IsNullOrWhiteSpace will check everything that IsNullOrEmpty does, plus the case when Undefined_var consists of only white space. But since a string consisting of only white space characters is not technically undefined, I would go with IsNullOrEmpty of the two.
But do note that since string is a reference type, the default value is null; so if you wanted to narrow down a step farther to eliminate the test for an empty string, you could do something like this-
string Undefined_var = null;
bool boola = Undefined_var == null;
There are no "undefined" string variables in C#.
String is a reference type, therefore if you don't define a value, it's default value is null.
There is no difference between a string not set to a value (default value null) and a string explicitely set to null.
In Visual Studio 2013 your code doesn't even compile. The first check gets flagged as use of unassigned local variable.
As C# is a strongly typed language, use it to your advantage, set the value explicitly:
string Undefined_var = null;
bool boola = String.IsNullOrWhiteSpace(Undefined_var);
bool boolb = String.IsNullOrEmpty(Undefined_var);
Then you will get two true values.
It question is not applicable to C# because C# does not allows a non-defined local variables. Members of classes are initialized by a member's default value (for reference types - initialized by null).
if (Request.QueryString["fieldvalue"] == "undefined")
It's a string, it will come across literally as a string.
If it is 5 it's a string of 5
If it is not there it's a string of undefined

To pass null values to float data type to add it into list

I am trying to pass the null value to float data type as follow,
float? period_final_value = null;
and getting the value in period_final_value from the parsing xml string as follows
var action = xmlAttributeCollection_for_period["value"];
xmlActionsone[j] = action.Value;
period_final_value = float.Parse(action.Value);
and then adding this obtained value to list as follows
serie_line.data.Add(period_final_value);
Defined my list as follows
var serie_line = new { name = series_name, data = new List<float?>() };
Now, My issue is when I am trying to pass value,it shold get add to the list, and moment when no value is recognized then it should add null has the value in the place of empty value in list but I don't know I am not able to get it work properly...my web service crashes moment it counters any blank value...any help will be greatly appreciated...
plz note...the var serie_line..I am going to serialize it into JSON format so that I can use those values to plot chart.
It sounds like you might be looking for TryParse instead of Parse.
When you call period_final_value = float.Parse(action.Value);, Parse will either parse the string into a float or throw an exception. It will never return null.
To get the behavior you want, try something like this:
float temp_value = 0;
float? period_final_value = null;
if (float.TryParse(action.Value, out temp_value)) {
period_final_value = temp_value;
}
serie_line.data.Add(period_final_value);
If action.Value is a string representation of a number, then period_final_value will be that number. Otherwise, it will be null. You can then add it to your list of float? values.
At this line
float? period_final_value = float.Parse(action.Value);
you are loosing the nullable float. When it fails to parse (there is no value or the value is not a valid float), it throws instead of returning null. period_final_value will never have null as a value.
See gleng's answer to be able to set null to period_final_value.

Categories

Resources