Is it possible to cast a command-line passed string object back to actual object?
I want to do the following, but throwing error can’t cast.
Button objPro = (Button) sender;
cProduct cp = (cProduct) objPro.CommandArgument;
If no, then why?
This is what the string holds.
cProduct cpObj = (cProduct)e.Row.DataItem;
Button btnAddProduct = (Button)e.Row.FindControl("btnAddProduct");
if (btnAddProduct != null)
{
btnAddProduct.CommandArgument = cpObj.ToString();
}
You probably can’t, because it’s a string. It’s not a
cProduct(whatever that is – consider following .NET naming conventions and naming itProductinstead).Now you could do this if you had a explicit conversion operator in
cProductto create an instance from a string.You haven’t really explained what’s in the string, or what’s in the type – but if your
cProducttype provides aToStringmethod which contains all the data in a reversible form, then you could easily write a method or a constructor to create the product again:or maybe:
You’ll have to write that constructor/method, of course.
I would strongly recommend using a constructor or method instead of an operator, just to keep your code clearer – it’s very rarely a good idea to write your own conversion operators.