Using a DataGrid Web Control to Read and Write Data: I get error message Specified Cast is not valid on line lobjTextBox = (TextBox)(e.Item.Cells[1].Controls[0]);. I am using ASP.NET 1.1

private void grdMessages_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
            {
                  DataGridItem item = grdMessages.Items[grdMessages.EditItemIndex];

                  RequiredFieldValidator lobjEditSubject = (RequiredFieldValidator) item.FindControl("rfvEditSubject");
                  RequiredFieldValidator lobjEditMessage = (RequiredFieldValidator) item.FindControl("rfvEditMessage");
                  
                  
                  // Check for validation, if all valid, update the object to data entered and save it.
                  if (lobjEditSubject.IsValid && lobjEditMessage.IsValid)
                  {      
                        // Fill in properties for Message object.
                        fobjMessage.MessageID = Convert.ToInt32(grdMessages.DataKeys[(int)e.Item.ItemIndex]);
                         

                        string lsSubject;
                        string lsMessage;
                        TextBox lobjTextBox;
                        lobjTextBox = (TextBox)(e.Item.Cells[1].Controls[0]);
                        lsSubject = lobjTextBox.Text;
                        lobjTextBox = (TextBox)(e.Item.Cells[2].Controls[0]);
                        lsMessage = lobjTextBox.Text;

                        fobjMessage.EntryDate = Convert.ToDateTime(DateTime.Today);
                        fobjMessage.UserID = fobjUser.UserID;

                        // Save the Message object.
                        fobjMessage.Save();

                        // Quit in-line-editing mode.
                        grdMessages.EditItemIndex = -1;
                        BindMessages(fobjUser.UserID);
                  }
            }
soumareAsked:
Who is Participating?
 
DhaestCommented:
Well, you said it yorself, Response.Write(e.Item.Cells[4].Controls[0]) just returns: System.Web.UI.LiteralControl,

This means you are looking at a literal control, not a text box.
You are probaly trying to access this while you are in view mode, and not edit mode.
In anycase, i wouldnt do it like this.
I would add an ID to all your text boxes, and elements and then do e.Item.FindControl("") and cast what you know you are finding.

lobjTextBox = DirectCast(e.Item.FindControl("txtEditMessage"), TextBox )
0
 
DhaestCommented:
How did you declare lobjTextBox  ?
0
 
soumareAuthor Commented:
I declared it as a local object of type TextBox
0
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
DhaestCommented:
Can you post the declaration of your datagrid....
0
 
soumareAuthor Commented:
<asp:datagrid id="grdMessages" runat="server" CssClass="BB_General" Width="650px" AllowPaging="True"
                                                AutoGenerateColumns="False" DataKeyField="MessageID">
                                                <HeaderStyle HorizontalAlign="Center" CssClass="BB_Header"></HeaderStyle>
                                                <Columns>
                                                      <asp:TemplateColumn Visible="False" HeaderText="Message ID">
                                                            <ItemTemplate>
                                                                  <asp:Label ID="lblEditMessageID" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.MessageID") %>'>
                                                                  </asp:Label>
                                                            </ItemTemplate>
                                                            <EditItemTemplate>
                                                                  <asp:TextBox ID="txtEditMessageID" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.MessageID") %>'>
                                                                  </asp:TextBox>
                                                            </EditItemTemplate>
                                                      </asp:TemplateColumn>
                                                      <asp:TemplateColumn HeaderText="Subject">
                                                            <ItemTemplate>
                                                                  <asp:Label ID="lblEditSubject" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Subject") %>' Width="150">
                                                                  </asp:Label>
                                                            </ItemTemplate>
                                                            <EditItemTemplate>
                                                                  <asp:TextBox runat="server" ID="txtEditSubject" Text='<%# DataBinder.Eval(Container, "DataItem.Subject") %>' Width="150">
                                                                  </asp:TextBox>
                                                                  <asp:requiredfieldvalidator ID="rfvEditSubject" runat="server" ErrorMessage="Subject is required." ControlToValidate="txtEditSubject"
                                                                        Display="Dynamic"></asp:requiredfieldvalidator>
                                                            </EditItemTemplate>
                                                      </asp:TemplateColumn>
                                                      <asp:TemplateColumn HeaderText="Message">
                                                            <ItemTemplate>
                                                                  <asp:Label ID="lblEditMessage" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Message") %>' Width="355">
                                                                  </asp:Label>
                                                            </ItemTemplate>
                                                            <EditItemTemplate>
                                                                  <asp:TextBox runat="server" ID="txtEditMessage" Text='<%# DataBinder.Eval(Container, "DataItem.Message") %>' Width="355">
                                                                  </asp:TextBox>
                                                                  <asp:requiredfieldvalidator ID="rfvEditMessage" runat="server" ErrorMessage="Message is required." ControlToValidate="txtEditMessage"
                                                                        Display="Dynamic"></asp:requiredfieldvalidator>
                                                            </EditItemTemplate>
                                                      </asp:TemplateColumn>
                                                      <asp:TemplateColumn HeaderText="Manage">
                                                            <HeaderStyle HorizontalAlign="Center" Width="110px" CssClass="grid-header" VerticalAlign="Middle"></HeaderStyle>
                                                            <ItemStyle HorizontalAlign="Right" Width="110px" CssClass="grid-item"></ItemStyle>
                                                            <ItemTemplate>
                                                                  <asp:LinkButton runat="server" Text="Edit" CommandName="Edit" CausesValidation="False"></asp:LinkButton>
                                                                  <img src="Images/spacer.gif" width="3">
                                                                  <asp:LinkButton runat="server" Text="Delete" CommandName="Delete" CausesValidation="False"></asp:LinkButton>
                                                            </ItemTemplate>
                                                            <EditItemTemplate>
                                                                  <asp:LinkButton runat="server" Text="Update" CommandName="Update" CausesValidation="False"></asp:LinkButton>&nbsp;
                                                                  <img src="Images/spacer.gif" width="3">
                                                                  <asp:LinkButton runat="server" Text="Cancel" CommandName="Cancel" CausesValidation="False"></asp:LinkButton>
                                                            </EditItemTemplate>
                                                      </asp:TemplateColumn>
                                                </Columns>
                                          </asp:datagrid>
0
 
DhaestCommented:
If you break your code on
lobjTextBox = (TextBox)(e.Item.Cells[1].Controls[0]);

What do you get if you try this ?
e.Item.Cells[1].Controls[0].GetType()
0
 
soumareAuthor Commented:

?e.Item.Cells[1].Controls[0].GetType()
{System.RuntimeType}
    System.Type: {"System.Web.UI.LiteralControl"}
    _pData: 197075488
    Assembly: {System.Reflection.Assembly}
    AssemblyQualifiedName: "System.Web.UI.LiteralControl, System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
    BaseType: {"System.Web.UI.Control"}
    BinderAccessMask: 65280
    BinderGetSetField: 3072
    BinderGetSetProperty: 12288
    BinderNonCreateInstance: 15616
    BinderNonFieldGetSet: 16773888
    BinderSetInvokeField: 2304
    BinderSetInvokeProperty: 8448
    ClassicBindingMask: 61696
    DeclaringType: <undefined value>
    DISPIDName: "[DISPID"
    ForwardCallBinder: {System.OleAutBinder}
    FullName: "System.Web.UI.LiteralControl"
    GUID: {System.Guid}
    LookupMask: 255
    MemberType: TypeInfo
    Module: {System.Reflection.Module}
    Name: "LiteralControl"
    Namespace: "System.Web.UI"
    ReflectedType: <undefined value>
    s_ForwardCallBinder: {System.OleAutBinder}
    TypeHandle: {System.RuntimeTypeHandle}
    UnderlyingSystemType: {"System.Web.UI.LiteralControl"}
    valueType: {"System.ValueType"}
0
 
DhaestCommented:
Is your problems solved ? (if so, why only a C-grade ?)
0
 
soumareAuthor Commented:
No I did not take your solution.  The real problem was that the update I was doing was working but I was calling the databinding to the grid again on postback that's why the grid values were being overwritten by the old database values.  That was my main problem,  I had to google it to find the solution.  Plus it took you too long to answer to my questions.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.