?
Solved

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

Posted on 2007-07-23
9
Medium Priority
?
196 Views
Last Modified: 2013-12-17
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);
                  }
            }
0
Comment
Question by:soumare
  • 5
  • 4
9 Comments
 
LVL 53

Expert Comment

by:Dhaest
ID: 19546357
How did you declare lobjTextBox  ?
0
 

Author Comment

by:soumare
ID: 19546949
I declared it as a local object of type TextBox
0
 
LVL 53

Expert Comment

by:Dhaest
ID: 19547091
Can you post the declaration of your datagrid....
0
NFR key for Veeam Agent for Linux

Veeam is happy to provide a free NFR license for one year.  It allows for the non‑production use and valid for five workstations and two servers. Veeam Agent for Linux is a simple backup tool for your Linux installations, both on‑premises and in the public cloud.

 

Author Comment

by:soumare
ID: 19547261
<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
 
LVL 53

Expert Comment

by:Dhaest
ID: 19562958
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
 

Author Comment

by:soumare
ID: 19567341

?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
 
LVL 53

Accepted Solution

by:
Dhaest earned 100 total points
ID: 19571969
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
 
LVL 53

Expert Comment

by:Dhaest
ID: 19572287
Is your problems solved ? (if so, why only a C-grade ?)
0
 

Author Comment

by:soumare
ID: 19576223
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

Featured Post

Get your Conversational Ransomware Defense e‑book

This e-book gives you an insight into the ransomware threat and reviews the fundamentals of top-notch ransomware preparedness and recovery. To help you protect yourself and your organization. The initial infection may be inevitable, so the best protection is to be fully prepared.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Loops Section Overview
When cloud platforms entered the scene, users and companies jumped on board to take advantage of the many benefits, like the ability to work and connect with company information from various locations. What many didn't foresee was the increased risk…
Suggested Courses
Course of the Month16 days, 3 hours left to enroll

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question