2014年7月13日 星期日

[RESOLVED] cannot implicitly convert type string to float


Hi All, I have a gridview control using templatefield CYQ2. I have formatted the field as curreny in html usign Text = '<%# Bind("CYQ2","{0:$#,##0.00}") %>' and it displays the field in currency format. But as soon as I added the currency format logic, it
is throwing an error that "cannot implicitly convert type string to float" at the line that is bold and italicized below.


Can anyone please help? Where am I declaring my field as string? thanks for the help.


protected bool IsRowModified(GridViewRow r)
{
float currentID;
float currentQ2;

currentID = Convert.ToInt32(GridView1.DataKeys[r.RowIndex].Value);

currentQ2 = ((TextBox)r.FindControl("CYQ2TextBox")).Text;
System.Data.DataRow row =
originalDataTable.Select(String.Format("ID = {0}", currentID))[0];


if (!currentQ1.Equals(row["CYQ2"].ToString())) { return true; }


return false;
}







currentQ2 = ((TextBox)r.FindControl("CYQ2TextBox")).Text;

.Text returns a string.  currentQ2 is a float. 



Take a look here at how to parse a string to a float:


http://msdn.microsoft.com/en-us/library/2thct5cb.aspx


 



This is because you are attempting to set the Text property of your TextBox which will return a string to your currentQ2 variable which stores a float (which would explain your issue).


You should consider using the
Convert.ToSingle()
or
Single.Parse() methods
to handle this as seen below : 


//The Convert.ToSingle() method will return a float if possible
currentQ2 = Convert.ToSingle(((TextBox)r.FindControl("CYQ2TextBox")).Text);

//Or you can use the Single.Parse() method
currentQ2 = Single.Parse(((TextBox)r.FindControl("CYQ2TextBox")).Text);

The "Single" in this context refers to a single-precision floating point number (which is a float).


沒有留言:

張貼留言