Search code examples
c#asp.nethtmlhtmlgenericcontrol

unable to cast System.Web.UI.HtmlControls.HtmlInputText to System.Web.UI.HtmlControls.HtmlGenericControl


I am trying to cast a htmlinputtext to a htmlgenericcontrol

file.aspx :

<form runat="server" class="probootstrap-form">         
  <div class="form-group" style="margin-top: 20px">
    <label for="name">Markt Name:</label>
    <div class="form-field">
      <input type="text" id="name" runat="server" required="required" class="form-control" />
    </div>
  </div>
</form>

file.aspx.cs :

HtmlGenericControl name = (HtmlGenericControl)Form.FindControl("name");

Error: System.InvalidCastException: Can't cast an object of the typ "System.Web.UI.HtmlControls.HtmlInputText" into "System.Web.UI.HtmlControls.HtmlGenericControl"


Solution

  • In the documentation you can see that HtmlInputText does not inherit from HtmlGenericControl and thus is not able to cast to HtmlGenericControl

    HtmlInputText would be able to cast to HtmlInputControl, HtmlControl, Control or object of which Control is the most generic that still makes sense in aspnet programming.