Code :
foreach (HtmlGenericControl div in panelCategorieGuida.Controls.OfType<HtmlGenericControl>())
{
HiddenField hf = div.Controls.OfType<HtmlGenericControl>().LastOrDefault();
}
it says "that I can't implicitly convert HtmlGenericControl to HiddenField". Also if I wrote (HiddenField)div.Controls.OfType<HtmlGenericControl>().LastOrDefault()
it doesnt works.
The last element of div (which is a HtmlGenericControl) is always a HiddenField element.
Why? Where am I wrong?
不应该像
HiddenField hf = div.Controls.OfType<HiddenField>().LastOrDefault();
foreach (var div in panelCategorieGuida.Controls.OfType<HtmlGenericControl>())
{
var hf = div.Controls.OfType<HiddenField>().LastOrDefault();
}
Your initial code just did the following:
HtmlGenericControl
HiddenField
(implicit and/or explicit) Now: Unless the last element, which is of type HtmlGenericControl
, isn't a real HiddenField
you'll get the invalid cast-exception. You might filter the elements to HiddenField
(as I did it), or rather take this code:
var hf = div.Controls.OfType<HtmlGenericControl>().LastOrDefault() as HiddenField;
Which is a "safe cast" ...
I think @Pranay Rana is right. If you explicit cast is also failed, I think you need check whether the element you want is a hidden field. Also, your code has some problems. You should always do some validation before you carry on. If not, maybe in test stage, your code running well. But it may encounter some errors later in production.
如果您知道这是一个HiddenField,则应该可以使用:
HiddenField hf = div.Controls.LastOrDefault() as HiddenField;
i think you should first check if it's a hidden field or not like this
if( div.Controls.OfType<HtmlGenericControl>().LastOrDefault() is HiddenField)
{
/// rest of the processing code
}
which might resolve your problem, because the element you are getting might not be hiddenfield element
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.