Unable to cast object of type 'System.Web.UI.LiteralControl' to type 'System.Web.UI.WebControls.TextBox'

Hello,

Goal: enter a number in two fields HoursPerUnit and PeoplePerUnit and the value for the third field, TotalHoursPerUnit will populate after the the number in the two fields have been caculated.  Using the code below I receive the error message above.  Please tell me what am I doing wrong? Do I need to cast the text as a literal?  Please help?

Thank you in advance,

<%@ Page Language="VB" MasterPageFile="Default.master" AutoEventWireup="false" CodeFile="frmHR.aspx.vb" Inherits="frmHR" title="HR" %>
<asp:Content ID="Content1" ContentPlaceHolderID="Main" Runat="Server">
    HR<br />
<script language =javascript  type="text/javascript">
function Calculate(HoursPerUnit, PeoplePerUnit, TotalHoursPerUnit)
{
    TotalHoursPerUnit.value = HoursPerUnit.value * PeoplePerUnit.value;
}
  
</script>
    <br />
    <asp:LinkButton ID="CheckAll" runat="server">Check All</asp:LinkButton>
    <asp:LinkButton ID="UncheckAll" runat="server">Uncheck All</asp:LinkButton><br />
    &nbsp;<br />
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="HRID"
        DataSourceID="SqlDataSource1" AllowSorting="True" ShowFooter="True" AllowPaging="True" EmptyDataText="There is not any data.">
        <Columns>

 

-----------------------------------------------------

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound

Dim HoursPerUnit As System.Web.UI.WebControls.TextBox

Dim PeoplePerUnit As System.Web.UI.WebControls.TextBox

Dim TotalHoursPerUnit As System.Web.UI.WebControls.TextBox

If e.Row.RowType = DataControlRowType.DataRow And e.Row.Cells(2).Controls.Count > 0 Then

HoursPerUnit = CType(e.Row.Cells(2).Controls(1), System.Web.UI.WebControls.TextBox)

PeoplePerUnit = CType(e.Row.Cells(3).Controls(1), System.Web.UI.WebControls.TextBox)

TotalHoursPerUnit = CType(e.Row.Cells(4).Controls(1), System.Web.UI.WebControls.TextBox)

HoursPerUnit.Attributes.Add("onchange", "Calculate(" + HoursPerUnit.ClientID + "," + PeoplePerUnit.ClientID + "," + TotalHoursPerUnit.ClientID + ")")

PeoplePerUnit.Attributes.Add("onchange", "Calculate(" + HoursPerUnit.ClientID + "," + PeoplePerUnit.ClientID + "," + TotalHoursPerUnit.ClientID + ")")

End If

End Sub


ptown
0
ptown
3/4/2008 5:42:43 PM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

14 Replies
2638 Views

Similar Articles

[PageSpeed] 44

e.Row.Cells(3).Controls(1) for example gets a Literal control in this case, not a TextBox (there could be a Literal matching for a whitespace for example). Since you didn't show how the columns are defined, this is bit guessing, but if you have given asp:TextBox on the template you could use

e.Row.FindControl("TextBox1") to locate the TextBox (where TextBox1 is its ID) so that you wouldn't need to know its index position in Controls collection. Other way is to find the correct index with test & trial.


Thanks,

Teemu Keiski
Finland, EU
0
joteke
3/4/2008 6:01:55 PM

I have listed the columns below:

<asp:TemplateField HeaderText="HoursPerUnit" SortExpression="HoursPerUnit">

<EditItemTemplate>

<asp:TextBox ID="TextBox7" runat="server" Text='<%# Bind("HoursPerUnit") %>'></asp:TextBox>

</EditItemTemplate>

<ItemTemplate>

<asp:Label ID="Label7" runat="server" Text='<%# Bind("HoursPerUnit") %>'></asp:Label>

</ItemTemplate>

<FooterTemplate>

<asp:TextBox ID="NewHoursPerUnit" runat="server"></asp:TextBox>

</FooterTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="PeoplePerUnit" SortExpression="PeoplePerUnit">

<EditItemTemplate>

<asp:TextBox ID="Tbx7" runat="server" Text='<%# Bind("PeoplePerUnit") %>'></asp:TextBox>

</EditItemTemplate>

<ItemTemplate>

<asp:Label ID="Lbl7" runat="server" Text='<%# Bind("PeoplePerUnit") %>'></asp:Label>

</ItemTemplate>

<FooterTemplate>

<asp:TextBox ID="NewPeoplePerUnit" runat="server"></asp:TextBox>

</FooterTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="TotalHoursPerUnit" SortExpression="TotalHoursPerUnit">

<EditItemTemplate>

<asp:TextBox ID="Tbx8" runat="server" Text='<%# Bind("TotalHoursPerUnit") %>'></asp:TextBox>

</EditItemTemplate>

<ItemTemplate>

<asp:Label ID="Lbl8" runat="server" Text='<%# Bind("TotalHoursPerUnit") %>'></asp:Label>

</ItemTemplate>

<FooterTemplate>

<asp:TextBox ID="NewTotalHoursPerUnit" runat="server"></asp:TextBox>

</FooterTemplate>

</asp:TemplateField>

 

Thank you,


ptown
0
ptown
3/4/2008 6:12:06 PM

In that case for example:

HoursPerUnit = CType(e.Row.Cells(2).Controls(1), System.Web.UI.WebControls.TextBox)

would be

HoursPerUnit = CType(e.Row.FindControl("TextBox7"), System.Web.UI.WebControls.TextBox) 'this gets the TextBox7 on the row

BTW: I suggest you name the TextBoxes in better manner, to describe their meaning.


Thanks,

Teemu Keiski
Finland, EU
0
joteke
3/4/2008 7:54:37 PM

Thank you again,

I updated RowDataBound as you stated and now receive error: Object reference not set to an instance of an object.  Do you think I am receiving the message because the three field types are INT?

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound

Dim HoursPerUnit As System.Web.UI.WebControls.TextBox
Dim PeoplePerUnit As System.Web.UI.WebControls.TextBox
Dim TotalHoursPerUnit As System.Web.UI.WebControls.TextBox
HoursPerUnit = CType(e.Row.FindControl("tbxHrsPerUnit"), System.Web.UI.WebControls.TextBox)
PeoplePerUnit = CType(e.Row.FindControl("tbxPPerUnit"), System.Web.UI.WebControls.TextBox)
TotalHoursPerUnit = CType(e.Row.FindControl("tbxTHrsPerUnit"), System.Web.UI.WebControls.TextBox)

HoursPerUnit.Attributes.Add("onchange", "Calculate(" + HoursPerUnit.ClientID + "," + PeoplePerUnit.ClientID + "," + TotalHoursPerUnit.ClientID + ")")
PeoplePerUnit.Attributes.Add("onchange", "Calculate(" + HoursPerUnit.ClientID + "," + PeoplePerUnit.ClientID + "," + TotalHoursPerUnit.ClientID + ")")

End Sub


ptown
0
ptown
3/5/2008 1:08:48 AM

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.]
   frmHR.GridView1_RowDataBound(Object sender, GridViewRowEventArgs e) +161
   System.Web.UI.WebControls.GridView.OnRowDataBound(GridViewRowEventArgs e) +105
   System.Web.UI.WebControls.GridView.CreateRow(Int32 rowIndex, Int32 dataSourceIndex, DataControlRowType rowType, DataControlRowState rowState, Boolean dataBind, Object dataItem, DataControlField[] fields, TableRowCollection rows, PagedDataSource pagedDataSource) +233
   System.Web.UI.WebControls.GridView.CreateChildControls(IEnumerable dataSource, Boolean dataBinding) +2232
   System.Web.UI.WebControls.CompositeDataBoundControl.PerformDataBinding(IEnumerable data) +59
   System.Web.UI.WebControls.GridView.PerformDataBinding(IEnumerable data) +11
   System.Web.UI.WebControls.DataBoundControl.OnDataSourceViewSelectCallback(IEnumerable data) +111
   System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback) +29
   System.Web.UI.WebControls.DataBoundControl.PerformSelect() +149
   System.Web.UI.WebControls.BaseDataBoundControl.DataBind() +70
   System.Web.UI.WebControls.GridView.DataBind() +4
   System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound() +82
   System.Web.UI.WebControls.CompositeDataBoundControl.CreateChildControls() +69
   System.Web.UI.Control.EnsureChildControls() +87
   System.Web.UI.Control.PreRenderRecursiveInternal() +41
   System.Web.UI.Control.PreRenderRecursiveInternal() +161
   System.Web.UI.Control.PreRenderRecursiveInternal() +161
   System.Web.UI.Control.PreRenderRecursiveInternal() +161
   System.Web.UI.Control.PreRenderRecursiveInternal() +161
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1360


ptown
0
ptown
3/5/2008 1:15:14 AM

Hi:

  Try this please:

     If e.Row.RowType = DataControlRowType.DataRow Then

'Your code
   End If

Regards


Sincerely,
Allen Chen
Microsoft Online Community Support

Please remember to mark the replies as answers if they help and unmark them if they provide no help.
0
Allen
3/6/2008 2:47:53 AM

Hello and than k you again,

I made the modification and received the same [NullReferenceException: Object reference not set to an instance of an object.]. Please tell me what I am doing wrong?

 Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound

Dim HoursPerUnit As System.Web.UI.WebControls.TextBox
Dim PeoplePerUnit As System.Web.UI.WebControls.TextBox
Dim TotalHoursPerUnit As System.Web.UI.WebControls.TextBox

If e.Row.RowType = DataControlRowType.DataRow Then
HoursPerUnit = CType(e.Row.FindControl("tbxHrsPerUnit"), System.Web.UI.WebControls.TextBox)
PeoplePerUnit = CType(e.Row.FindControl("tbxPPerUnit"), System.Web.UI.WebControls.TextBox)
TotalHoursPerUnit = CType(e.Row.FindControl("tbxTHrsPerUnit"), System.Web.UI.WebControls.TextBox)

HoursPerUnit.Attributes.Add("onchange", "Calculate(" + HoursPerUnit.ClientID + "," + PeoplePerUnit.ClientID + "," + TotalHoursPerUnit.ClientID + ")")
PeoplePerUnit.Attributes.Add("onchange", "Calculate(" + HoursPerUnit.ClientID + "," + PeoplePerUnit.ClientID + "," + TotalHoursPerUnit.ClientID + ")")

End If 

End Sub


ptown
0
ptown
3/6/2008 3:38:44 AM

Hi:

  Are you sure ID is correct? I think it should be:

HoursPerUnit = CType(e.Row.FindControl("TextBox7"), System.Web.UI.WebControls.TextBox)

  The ID is what you set in aspx.

Regards


Sincerely,
Allen Chen
Microsoft Online Community Support

Please remember to mark the replies as answers if they help and unmark them if they provide no help.
0
Allen
3/6/2008 5:28:05 AM

Hello,

I changed the ID of the textboxes so the TextBoxes ID can describe their meaning.


ptown
0
ptown
3/6/2008 5:44:34 AM

It is interesting that I get this message when the page opens.  I do not even get ithe chance to see the gridview at all.  Its almost like it is trying to process on page load instead of opeing the page and allowing me to click the edit button to update the data.  Please tell me if I am thinking correctly? 

Thank you,


ptown
0
ptown
3/6/2008 5:49:56 AM

Hi:

 Please set breakpoints there to debug and tell us which line throws the exception. In addition please paste your current inline code here.

Thanks


Sincerely,
Allen Chen
Microsoft Online Community Support

Please remember to mark the replies as answers if they help and unmark them if they provide no help.
0
Allen
3/6/2008 7:31:55 AM

Hello,

I set breakpoints to see which line throws the exception, but as soon as the page gets ready to open I get the message:

1) Object reference not set to an instance of an object

2) When I start commenting out lines I start receiving the following messages. 

Warning 1 Variable 'HoursPerUnit' is used before it has been assigned a value. A null reference exception could result at runtime.

Warning 1 Unused local variable: 'HoursPerUnit

3) When I comment out all lines the page opens up normally.  Do you think the codding is not right, because the page should still open and if something is wrong, I should receive an error when I enter data in the fields?  

I put the code below

-----------------------------------------------------

aspx page

<%@ Page Language="VB" MasterPageFile="~/MembersDefault.master" AutoEventWireup="false" CodeFile="frmHR.aspx.vb" Inherits="Members_frmHRBuild" title="HRBuilder" %>
<asp:Content ID="Content1" ContentPlaceHolderID="Main" Runat="Server">
    HR Builder<br />

<script language =javascript  type="text/javascript">
function Calculate(HoursPerUnit, PeoplePerUnit, TotalHoursPerUnit)
{
   
    TotalHoursPerUnit.value = HoursPerUnit.value * PeoplePerUnit.value;
 
}
  
</script>

    <br />
    <asp:LinkButton ID="CheckAll" runat="server">Check All</asp:LinkButton>
    <asp:LinkButton ID="UncheckAll" runat="server">Uncheck All</asp:LinkButton><br />
    &nbsp;<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="DetailMUMID"
        DataSourceID="SqlDataSource1" AllowSorting="True" ShowFooter="True" AllowPaging="True" EmptyDataText="There is not any data.">
        <Columns>
            <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:CheckBox ID="RecordSelector" runat="server" />
                </ItemTemplate>
                <EditItemTemplate>
                    &nbsp;
                </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="DetailID" InsertVisible="False" SortExpression="DetailID">
                <EditItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Eval("DetailID") %>'></asp:Label>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label32" runat="server" Text='<%# Bind("DetailID") %>'></asp:Label>
                </ItemTemplate>
                <FooterTemplate>
                    <asp:LinkButton ID="AddRecord" runat="server" CommandName="Insert">Add</asp:LinkButton>
                </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="TemplateHRID" SortExpression="TemplateHRID" Visible="False">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox32" runat="server" Text='<%# Bind("TemplateHRID") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label33" runat="server" Text='<%# Bind("TemplateHRID") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="WorkOrderID" SortExpression="WorkOrderID">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox31" runat="server" Text='<%# Bind("WorkOrderID") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label31" runat="server" Text='<%# Bind("WorkOrderID") %>'></asp:Label>
                </ItemTemplate>
                <FooterTemplate>
                    <asp:TextBox ID="NewWorkOrderID" runat="server"></asp:TextBox>
                </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Loc" SortExpression="Loc">
                <EditItemTemplate>
                    <asp:DropDownList ID="DropDownList5" runat="server" DataSourceID="LocddlODS"
                        DataTextField="Loc" DataValueField="Loc">
                    </asp:DropDownList><asp:ObjectDataSource ID="LocddlODS" runat="server" OldValuesParameterFormatString="original_{0}"
                        SelectMethod="GettblLoc" TypeName="tblLocBLL"></asp:ObjectDataSource>
                    &nbsp;
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("Loc") %>'></asp:Label>
                </ItemTemplate>
                <FooterTemplate>
                    &nbsp;<asp:DropDownList ID="NewLoc" runat="server" DataSourceID="ddlLoc"
                        DataTextField="Loc" DataValueField="Loc">
                    </asp:DropDownList><asp:SqlDataSource ID="ddlLoc" runat="server" ConnectionString="<%$ ConnectionStrings:HRConnectionString %>"
                        SelectCommand="SELECT [LocID], [Loc] FROM [tblLoc]"></asp:SqlDataSource>
                    &nbsp;
                </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="SystemName" SortExpression="SystemName">
                <EditItemTemplate>
                    <asp:DropDownList ID="sysidddl" runat="server" DataSourceID="sysods1"
                        DataTextField="SystemName" DataValueField="SystemName">
                    </asp:DropDownList><asp:ObjectDataSource ID="sysods1" runat="server" OldValuesParameterFormatString="original_{0}"
                        SelectMethod="GettblTSystems" TypeName="tblTSystemsBLL"></asp:ObjectDataSource>
                    &nbsp;&nbsp;
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label2" runat="server" Text='<%# Bind("SystemName") %>'></asp:Label>
                </ItemTemplate>
                <FooterTemplate>
                    <asp:DropDownList ID="NewSystemName" runat="server" DataSourceID="sysODS2"
                        DataTextField="SystemName" DataValueField="SystemName">
                    </asp:DropDownList><asp:ObjectDataSource ID="sysODS2" runat="server" OldValuesParameterFormatString="original_{0}"
                        SelectMethod="GettblTSystems" TypeName="tblTSystemsBLL"></asp:ObjectDataSource>
                    &nbsp;
                </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="SubSystem" SortExpression="SubSystem">
                <EditItemTemplate>
                    &nbsp;<asp:DropDownList ID="subsysddl" runat="server" DataSourceID="SubSysODS"
                        DataTextField="SubSystem" DataValueField="SubSystem">
                    </asp:DropDownList><asp:ObjectDataSource ID="SubSysODS" runat="server" OldValuesParameterFormatString="original_{0}"
                        SelectMethod="GettblSubSystemBySystemID" TypeName="tblSubSystemBLL">
                        <SelectParameters>
                            <asp:Parameter Name="SystemID" Type="Int32" />
                        </SelectParameters>
                    </asp:ObjectDataSource>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label3" runat="server" Text='<%# Bind("SubSystem") %>'></asp:Label>
                </ItemTemplate>
                <FooterTemplate>
                    &nbsp;<asp:DropDownList ID="NewSubSystem" runat="server" DataSourceID="subsysddlODS2"
                        DataTextField="SubSystem" DataValueField="SubSystem">
                    </asp:DropDownList><asp:ObjectDataSource ID="subsysddlODS2" runat="server" OldValuesParameterFormatString="original_{0}"
                        SelectMethod="GettblSubSystem" TypeName="tblSubSystemBLL"></asp:ObjectDataSource>
                </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Component" SortExpression="Component">
                <EditItemTemplate>
                    &nbsp;<asp:DropDownList ID="DropDownList3" runat="server" DataSourceID="cpODS"
                        DataTextField="Component" DataValueField="Component">
                    </asp:DropDownList><asp:ObjectDataSource ID="cpODS" runat="server" OldValuesParameterFormatString="original_{0}"
                        SelectMethod="GettblComponent" TypeName="tblComponentBLL"></asp:ObjectDataSource>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label4" runat="server" Text='<%# Bind("Component") %>'></asp:Label>
                </ItemTemplate>
                <FooterTemplate>
                    <asp:DropDownList ID="NewComponent" runat="server" DataSourceID="CoddlODS2"
                        DataTextField="Component" DataValueField="Component">
                    </asp:DropDownList><asp:ObjectDataSource ID="CoddlODS2" runat="server" OldValuesParameterFormatString="original_{0}"
                        SelectMethod="GettblComponent" TypeName="tblComponentBLL"></asp:ObjectDataSource>
                    &nbsp;
                </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="LocType" SortExpression="LocType">
                <EditItemTemplate>
                    <asp:DropDownList ID="LocTypeddl" runat="server" DataSourceID="LocTddlODS"
                        DataTextField="LocType" DataValueField="LocType">
                    </asp:DropDownList><asp:ObjectDataSource ID="LocTddlODS" runat="server" OldValuesParameterFormatString="original_{0}"
                        SelectMethod="GettblLocType" TypeName="tblLocTypeBLL"></asp:ObjectDataSource>
                    &nbsp;
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label5" runat="server" Text='<%# Bind("LocType") %>'></asp:Label>
                </ItemTemplate>
                <FooterTemplate>
                    <asp:DropDownList ID="NewLocType" runat="server" DataSourceID="LocTddlODS2"
                        DataTextField="LocType" DataValueField="LocType">
                    </asp:DropDownList><asp:ObjectDataSource ID="LocTddlODS2" runat="server" OldValuesParameterFormatString="original_{0}"
                        SelectMethod="GettblLocType" TypeName="tblLocTypeBLL"></asp:ObjectDataSource>
                    &nbsp;
                </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="LevelI" SortExpression="LevelI">
                <EditItemTemplate>
                    <asp:CheckBox ID="NewLevelI" runat="server" Checked='<%# Bind("LevelI") %>' />
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:CheckBox ID="NewLevelI" runat="server" Checked='<%# Bind("LevelI") %>' Enabled="false" />
                </ItemTemplate>
                <FooterTemplate>
                    <asp:CheckBox ID="NewLevelI" runat="server" />
                </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="LevelII" SortExpression="LevelII">
                <EditItemTemplate>
                    <asp:CheckBox ID="NewLevelII" runat="server" Checked='<%# Bind("LevelII") %>' />
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:CheckBox ID="NewLevelII" runat="server" Checked='<%# Bind("LevelII") %>' Enabled="false" />
                </ItemTemplate>
                <FooterTemplate>
                    <asp:CheckBox ID="NewLevelII" runat="server" />
                </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="LevelIII" SortExpression="LevelIII">
                <EditItemTemplate>
                    <asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Bind("LevelIII") %>' />
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:CheckBox ID="NewLevelIII" runat="server" />
                </FooterTemplate>
                <ItemTemplate>
                    <asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Bind("LevelIII") %>' Enabled="false" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="IndexNumber" SortExpression="IndexNumber">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox6" runat="server" Text='<%# Bind("IndexNumber") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label6" runat="server" Text='<%# Bind("IndexNumber") %>'></asp:Label>
                </ItemTemplate>
                <FooterTemplate>
                    <asp:TextBox ID="NewIndexNumber" runat="server"></asp:TextBox>
                </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="HoursPerUnit" SortExpression="HoursPerUnit">
                <EditItemTemplate>
                    <asp:TextBox ID="tbxHrsPerUnit" runat="server" Text='<%# Bind("HoursPerUnit") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label7" runat="server" Text='<%# Bind("HoursPerUnit") %>'></asp:Label>
                </ItemTemplate>
                <FooterTemplate>
                    <asp:TextBox ID="NewHoursPerUnit" runat="server"></asp:TextBox>
                </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="PeoplePerUnit" SortExpression="PeoplePerUnit">
                <EditItemTemplate>
                    <asp:TextBox ID="tbxPPerUnit" runat="server" Text='<%# Bind("PeoplePerUnit") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Lbl7" runat="server" Text='<%# Bind("PeoplePerUnit") %>'></asp:Label>
                </ItemTemplate>
                <FooterTemplate>
                    <asp:TextBox ID="NewPeoplePerUnit" runat="server"></asp:TextBox>
                </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="TotalHoursPerUnit" SortExpression="TotalHoursPerUnit">
                <EditItemTemplate>
                    <asp:TextBox ID="tbxTHrsPerUnit" runat="server" Text='<%# Bind("TotalHoursPerUnit") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Lbl8" runat="server" Text='<%# Bind("TotalHoursPerUnit") %>'></asp:Label>
                </ItemTemplate>
                <FooterTemplate>
                    <asp:TextBox ID="NewTotalHoursPerUnit" runat="server"></asp:TextBox>
                </FooterTemplate>
            </asp:TemplateField>
 
Code Behind:
------------
    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
        Dim HoursPerUnit As System.Web.UI.WebControls.TextBox
        Dim PeoplePerUnit As System.Web.UI.WebControls.TextBox
        Dim TotalHoursPerUnit As System.Web.UI.WebControls.TextBox
     

        If e.Row.RowType = DataControlRowType.DataRow Then
            HoursPerUnit = CType(e.Row.FindControl("tbxHrsPerUnit"), System.Web.UI.WebControls.TextBox)
            PeoplePerUnit = CType(e.Row.FindControl("tbxPPerUnit"), System.Web.UI.WebControls.TextBox)
            TotalHoursPerUnit = CType(e.Row.FindControl("tbxTHrsPerUnit"), System.Web.UI.WebControls.TextBox)
 
            HoursPerUnit.Attributes.Add("onchange", "Calculate(" + HoursPerUnit.ClientID + "," + PeoplePerUnit.ClientID + "," + TotalHoursPerUnit.ClientID + ")")
            PeoplePerUnit.Attributes.Add("onchange", "Calculate(" + HoursPerUnit.ClientID + "," + PeoplePerUnit.ClientID + "," + TotalHoursPerUnit.ClientID + ")")
 
        End If
    End Sub
 
    Protected Sub SqlDataSource1_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs) Handles SqlDataSource1.Selecting
 
    End Sub
 
    Protected Sub GridView1_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GridView1.RowEditing
 
    End Sub
 
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
 
    End Sub
 


ptown
0
ptown
3/6/2008 8:25:04 AM

Hi:

  Since TextBox is in EditTemplate you should also add this:

If e.Row.RowType=DataControlRowType.DataRow AndAlso e.Row.RowState=DataControlRowState.Edit Then

Regards


Sincerely,
Allen Chen
Microsoft Online Community Support

Please remember to mark the replies as answers if they help and unmark them if they provide no help.
0
Allen
3/7/2008 10:12:11 AM

Thank you again for your guidance, patience, and time with this matter.  The reference to Edit resolve the issue.


ptown
0
ptown
3/7/2008 4:59:35 PM
Reply:

Similar Artilces:

Unable to cast object of type 'System.Web.UI.LiteralControl' to type 'System.Web.UI.WebControls.TextBox'.
Hi, any idea why I'm getting the following error?Line 45: protected void CartGrid_RowUpdating(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e) Line 46: { Line 47: TextBox QuantityTextBox = (TextBox)CartGrid.Rows[e.RowIndex].Cells[2].Controls[0]; Line 48: int Quantity = Convert.ToInt32(QuantityTextBox.Text); Line 49: Are you sure that the control at CartGrid.Rows[e.RowIndex].Cells[2].Controls[0] isn't a LiteralControl?  How are you creating code this in your code?Brent JenkinsASP.NET, C#, Web Developerwww.valewebdesign.co.uk  ...

Unable to cast object of type 'System.Web.UI.WebControls.Label' to type 'System.Web.UI.WebControls.TextBox'
I am attempting to "Update" a field in a Datagrid, but no matter what I do (Using either Label or Text Boxes)  I keep getting the same error: Unable to cast object of type 'System.Web.UI.WebControls.Label' to type 'System.Web.UI.WebControls.TextBox' The Error is highlighted below in the Sub... <==THE FIELD THAT CALLS THE ERROR  Any help would be greatly appreciated !!! Thanks !!   The code is as follows... <table border=0 height=210 bordercolor=olive ><tr valign=top><td> <asp:datagrid id="FacilityDataGrid" runat="server" Font-Names="Arial" Font-Size="11px" HorizontalAlign="Left" ItemStyle-Font-Size="x-small" HeaderStyle-Font-Bold="True"HeaderStyle-Font-Size="x-small" AlternatingItemStyle-BackColor="#FFFFFF" Cellpadding="0" BorderWidth="0"AutoGenerateColumns="False" BorderStyle="None" GridLines="None" BorderColor="#404040" Width="75%"DataKeyField="FacilityID"OnUpdateCommand="MyDataGrid_UpdateCommand"OnCancelCommand="MyDataGrid_CancelCommand"OnEditCommand="DG_Combo_Edit"> <AlternatingItemStyle BackColor="#FFFFFF"></AlternatingItemStyle><ItemStyle Font-Size="X-Small"></ItemStyle><HeaderStyle Font-Size="X-Small" Font-Bold="True" ForeCo...

Unable to cast object of type 'System.Web.UI.WebControls.FormView' to type 'System.Web.UI.WebControls.DropDownList'.
Hi,  I have a formview with a dropdownlist created dynamically. i want to determine whether the dropdownlist was clicked. the code is written in the FormView1_DataBound method. I get the following error in the line below that is in italics and underlined: Unable to cast object of type 'System.Web.UI.WebControls.FormView' to type 'System.Web.UI.WebControls.DropDownList'.   Here is my code: ddl_iFullname = New DropDownList ddl_iFullname.ID = "ddl_iFullname" ddl_iFullname.DataSource = ObjectDataSource3 ddl_iFullname.DataTextField = "fullname" ddl_iFullname.DataValueField = "...

Error showing up: Unable to cast object of type 'System.Web.UI.WebControls.TextBox' to type 'System.IConvertible'.
Hi, I am trying to pass date values from two textboxes in a stored procedure from ASP.net page. However, it seems it is not passing the date properly. I am getting the following error at the following line: cmd_r.Parameters("@initial_est_date").Value = Convert.ToDateTime(Textbox1)  and the error is as stated in the title. I would appreciate any help to resolve this. Thanks  CODE:<%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %><%@ Import Namespace="System.Data.Common" %> <%@ I...

Unable to cast object of type 'System.EventArgs' to type 'System.Web.UI.WebControls.GridViewRowEventArgs'
hi this is really really bugging me please help. I have a web appliction that uses a Master Page. On one of the content pages I am presenting a gridview control bound to a spreadsheet. The gridview is contained within an ajax update panel. I want to add attributes to the rows of the gridview control once databound (mouseover effect). However I am getting the following error:- Unable to cast object of type 'System.EventArgs' to type 'System.Web.UI.WebControls.GridViewRowEventArgs' Can anyone help please. Here is the aspx code:-  <%@ Page Language="v...

Unable to cast object of type 'System.String' to type 'System.Web.UI.WebControls.Parameter'.
I'm getting this error on a vb.net page the needs to execute two separate stored procedures.  The first one, is the main insert, and returns the identity value for the ClientID.  The second stored procedure inserts data, but needs to insert the ClientID returned in the first stored procedure.  What am I doing wrong with including the identity value "ClientID" in the second stored procedure?  Unable to cast object of type 'System.String' to type 'System.Web.UI.WebControls.Parameter'. Description: An unhandled exception occurred during t...

Unable to cast object of type 'System.Int32' to type 'System.Web.UI.WebControls.DataKey'
hi , i have a datalist with an itemtemplate section that contains an image and a delete button to delete the corresponding image . <asp:DataList ID="DataList1" CellSpacing="25" runat="server" DataSourceID="sqldatasource3" DataKeyField="ID" repeatColumns="4" repeatdirection="Horizontal" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="0px" CellPadding="3" > <ItemTemplate> <table border="0" cellpadding="0" cellspacing="0" > <tr> <a href='<%# DataBinder.Eval(Container.DataItem, "image", "ImageViewer.aspx?id={0}") %>' > <img a...

Unable to cast object of type 'System.Web.UI.LiteralControl' to type 'x_it.Controls.NewsDetail'.
I have dynamicly filled a Panel with my usercontrols, I have no problem. But when I try to get in a for loop to read the data of my usercontrol, I get an error. Can somebody explain me what I'am doing wrong ?   for (int i = 0; i < PnlNewsDetails.Controls.Count; i++) { x_it.Controls.NewsDetail nd = (x_it.Controls.NewsDetail)(PnlNewsDetails.Controls[i]); if (Request.RequestType == "POST" && !nd.ErrorInput) { tbNews tn = new tbNews(); tn.Date = nd.Date; tn.Title = nd.Title; tn.SeoUrl = nd.SeoUrl; ...

Error: Cannot convert type 'System.Web.UI.Control' to 'System.Web.UI.WebControls.ButtonField'
Hello, I am getting the following error during compiliation. Any suggestions to fix it. Thanks. Cannot convert type 'System.Web.UI.Control' to 'System.Web.UI.WebControls.ButtonField' protected void gvEvents_RowCommand(Object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Select") { int index = Convert.ToInt32(e.CommandArgument); GridViewRow selectedRow = gvEvents.Rows[index]; string sID; ButtonField btn; if (selectedRow.RowType == DataControlRowType.DataRow) { sID = ((ButtonField)selectedRow.FindControl("ID")).DataTextFi...

Unable to cast object of type 'System.Web.UI.WebControls.ContentPlaceHolder' to type 'CustomerDB._Default'.
If have  a problem regarding the error message: Unable to cast object of type 'System.Web.UI.WebControls.ContentPlaceHolder' to type 'CustomerDB._Default'. I am using MaterPages with two ContentPlaceHolders in my default.aspx In the fist ContentPlaceHolder I have added a ordinary placeholder where I loads a Usercontrol. So far so good.The usercontrols search for customers and creates a gridview with a link that  the user can click on. When the user clicks it runs a class (located in default.aspx) that should present data in the second ContentPlaceholder, ...

ASPNET2 HELP! CS0266: Cannot implicitly convert type 'System.Web.UI.Control' to 'System.Web.UI.WebControls.FileUpload'.
Server Error in '/start-movieposters' Application. Compilation Error Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. Compiler Error Message: CS0266: Cannot implicitly convert type 'System.Web.UI.Control' to 'System.Web.UI.WebControls.FileUpload'. An explicit conversion exists (are you missing a cast?) Source Error: ...

Error Serializing Value 'System.Web.UI.WebCOntrols.TreeNode' of type 'System.Web.UI.WebCOntrols.TreeNode'
Hi, I am  getting the error stated in the subject when i am storing a TreeNode in a ViewState and then using it as follows if (ViewState["ProductCounty"]!=null) { TreeNode _productCountyNode = DataTree.FindNode(((TreeNode)ViewState["ProductCounty"]).ValuePath); _productCountyNode.Expand(); } what could be causing this error? Hi, I believe TreeNode isn't serializable in a way its required for objects which can be put to ViewState - as reference - (TreeNode implements IStateManager and is meant to work together with TreeView itself saving it...

Unable to cast object of type 'System.Web.Configuration.ScriptingAuthenticationServiceSection' to type 'System.Web.Configuration.ScriptingAuthenticationServiceSection'.
I have tried to upgrade an existing application from VS2005 to VS2008.  I downloaded the latest AjaxControlToolkit and referenced it in my project.  I'm getting the below error when I try to deploy to our QA servers.  I'm NOT seeing the issue on our local development machines that have VS2008 installed.   Unable to cast object of type 'System.Web.Configuration.ScriptingAuthenticationServiceSection' to type 'System.Web.Configuration.ScriptingAuthenticationServiceSection'.  What piece am I missing in the deployment?  All the w...

Unable to cast object of type 'System.Web.Configuration.ScriptingScriptResourceHandlerSection' to type 'System.Web.Configuration.ScriptingScriptResourceHandlerSection'.
Hello, I get this lovely error whenever I attempt to load an AJAXToolKit ScriptManager. It is the only one I have on the page. If I use the regulare script manager, my extenders don't detect it. I'm placing the ScriptManager just after the <Form> tag. The frustrating part is that it works when I preview it in the browser from my development machine it works, but once I place it the live server, it crashes on me . I've installed all of the .dlls in the proper places. Also, I'm trying to attempt to do this when creating a new site with the AJAX ToolKit enabled templat...

Unable to cast object of type 'System.Web.Configuration.ScriptingScriptResourceHandlerSection' to type 'System.Web.Configuration.ScriptingScriptResourceHandlerSection'.
Hello, I get this lovely error whenever I attempt to load an AJAXToolKit ScriptManager. It is the only one I have on the page. If I use the regulare script manager, my extenders don't detect it. I'm placing the ScriptManager just after the <Form> tag. The frustrating part is that it works when I preview it in the browser from my development machine it works, but once I place it the live server, it crashes on me . I've installed all of the .dlls in the proper places. Also, I'm trying to attempt to do this when creating a new site with the AJAX ToolKit enabled templat...

Unable to cast object of type 'System.Web.Compilation.BuildResultCompiledAssembly' to type 'System.Web.Compilation.BuildResultCompiledGlobalAsaxType'
I always get the below exception if I make a configuration change to the web.config file then request a page without re-building the project. Exception: Unable to cast object of type 'System.Web.Compilation.BuildResultCompiledAssembly' to type 'System.Web.Compilation.BuildResultCompiledGlobalAsaxType'. Stack Trace: [InvalidCastException]: Unable to cast object of type 'System.Web.Compilation.BuildResultCompiledAssembly' to type 'System.Web.Compilation.BuildResultCompiledGlobalAsaxType'.   at System.Web.Compilation.ApplicationBuildProvider.GetGlobalAsaxBuildResult(Boolean isPrec...

The base class includes the field 'MyList', but its type (System.Web.UI.WebControls.DataList) is not compatible with the type of control (System.Web.UI.WebControls.DataGrid).
Hi guys,I am very new to asp.net and have been playing with the commerce starter kit at - http://asp.net/CommerceStarterKit/ one of the first pages that lists the catalogue items "ProductsList.aspx" uses a datalist, I need to use a datagrid as I need to use pagination as my catalogue is so huge, I have changed the necessary attributes in the ProductsList.aspx page to datagrid and also in the codebehind file ProductsList.aspx.vb, when I run the page I get the Error message below. Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately. Parser Error Message: The base class includes the field 'MyList', but its type (System.Web.UI.WebControls.DataList) is not compatible with the type of control (System.Web.UI.WebControls.DataGrid).Source Error: Line 30: <tr> Line 31: <td> Line 32: <asp:DataGrid id="MyList" runat="server"> Line 33: <Columns> Line 34: <asp:TemplateColumn> HERE IS THE PRODUCTSLIST.ASCX PAGE<%@ Page Language="vb" EnableViewState="false" CodeBehind="ProductsList.aspx.vb" AutoEventWireup="false" Inherits="ASPNET.StarterKit.Commerce.ProductsList"%><%@ Register TagPrefix="ASPNETCom...

The base class includes the field 'MyList', but its type (System.Web.UI.WebControls.DataList) is not compatible with the type of control (System.Web.UI.WebControls.DataGrid).
Hi guys,I am very new to asp.net and have been playing with the commerce starter kit at - http://asp.net/CommerceStarterKit/ one of the first pages that lists the catalogue items "ProductsList.aspx" uses a datalist, I need to use a datagrid as I need to use pagination as my catalogue is so huge, I have changed the necessary attributes in the ProductsList.aspx page to datagrid and also in the codebehind file ProductsList.aspx.vb, when I run the page I get the Error message below. Description: An error occurred during the parsing of a resource required to ser...

Unable to cast object of type 'System.Web.UI.Page' to type 'CareAlways.UserControls.PageBase'
I have a project that has custom controls developed under ASP.NET 1.1, andI've successfully migrated to ASP.NET 2.0.  The format of the folder structure is as follows: /Core    /Business    /UserControls       MyTextBox.cs       PageBase.cs/WebApps   /MyWebApp  I have resolved all the problems to get the project to compile and run. My problem is that there are a few of my user controls that throw an error in the design mode of VS.NET 2005.  I get the following mess...

Help Required
Server Error in '/' Application.--------------------------------------------------------------------------------Unable to cast object of type 'System.Web.Compilation.BuildResultCompiledAssembly' to type 'System.Web.Util.ITypedWebObjectFactory'. [InvalidCastException: Unable to cast object of type 'System.Web.Compilation.BuildResultCompiledAssembly' to type 'System.Web.Util.ITypedWebObjectFactory'.] System.Web.Compilation.BuildManager.GetVirtualPathObjectFactory(VirtualPath virtualPath, HttpContext context, Boolean allowCrossApp, Boolean noAssert) +123 System.Web.Compilation.BuildMa...

System.InvalidCastException: Unable to cast object of type 'System.Web.HttpInputStream' to type 'System.IO.FileStream'
I am trying to create a webpage that takes a file that someone want to upload and chop the file into smaller pieces, and then put back together again.  I have been trying to convert some code I found on Codeproject (FileSplitMerge).  They did it with VB which is what I want to use but it is a project not a web site so...  The problem that I am running into is I keep getting an error when I try to set: FileStream = HttpPostedFile.InputStream (I am using variables in my code) but I keep getting an error of: System.InvalidCastException: Unable to cast object of type 'Sys...

Value of type 'System.Web.UI.Control' cannot be converted to 'System.Web.SiteMap'.
 Hello,         I receive this error "System.Web.UI.Control' cannot be converted to 'System.Web.SiteMap" when I try to find the Sitemap control.  ...            <asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />            <asp:ListView ID="ListView1" runat="server">            <LayoutTemplate>    ...

Error 1 The type 'System.Web.UI.WebControls.LinqDataSource' exists in both 'c:\WINDOWS\assembly\GAC_MSIL\System.Web.Extensions\3.5.0.0__31bf3856ad364e35\System.Web.Extensions.dll' and 'c:\WINDOWS\asse
Once I build project. I encounter this error. Does someone experience this error?Error    1    The type 'System.Web.UI.WebControls.LinqDataSource' exists in both 'c:\WINDOWS\assembly\GAC_MSIL\System.Web.Extensions\3.5.0.0__31bf3856ad364e35\System.Web.Extensions.dll' and 'c:\WINDOWS\assembly\GAC_MSIL\System.Web.Extensions\3.6.0.0__31bf3856ad364e35\System.Web.Extensions.dll'    D:\Source Code\Linq_Lesson5\Default.aspx    1    1    D:\Source Code\Linq_Lesson5\  It appears tha...

Operator '&' is not defined for types 'String' and 'System.Web.UI.WebControls.TextBox'
Can anyone tell me what this error message means, and what to do to correct it.  Here is the code that has the error:  Dim sql As Stringsql = "INSERT INTO tblConnecting (Date, Member, Name, Company, Phone, Fax, Address, NamesofAttendees, PaymentType, Email) " _ & "Values('" & Today() & "', '" & blnMember & "', '" & Me.txtName.Text & "', '" & Me.txtCompany.Text & "', '" _& Me.txtPhone.Text & "', '" & Me.txtFax.Text &...

Web resources about - Unable to cast object of type 'System.Web.UI.LiteralControl' to type 'System.Web.UI.WebControls.TextBox' - asp.net.presentation-controls

Resources last updated: 3/1/2016 5:10:07 PM