简体   繁体   中英

Why I am getting an error when trying to edit this field using checkbox?

I am a new C# and ASP.NET developer. I am developing a simple events management system. I want the admin to be able to edit the information of the events. The events will be listed in a GridView which is bound to the following table in the database:

Events Table: ID, Title, Description, Location, NumberOfSeats, StartDateTime, EndDateTime, IsActive

(IsActive is a bit the indicates the active or inactive events)

Everything works fine except when I tried to edit the IsActive field, it gave me the following error:

Input string was not in a correct format.

because of the following code line:

int ID = Convert.ToInt32(gvrow.Cells[0].Text);

Could you please help me in fixing it?

ASP.NET code:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID"
            width="500px" DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound">
            <Columns>
                <asp:CommandField ButtonType="Image" ShowEditButton="true" ShowCancelButton="true"
                                EditImageUrl="Images/icons/edit24.png" UpdateImageUrl="Images/icons/update24.png" 
                                CancelImageUrl="Images/icons/cancel324.png" />

                <asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" Visible="false" />

                <asp:TemplateField HeaderText="Title">
                    <ItemTemplate>
                        <%# Eval("Title") %>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtTitle"  runat="server" 
                                        Text='<%# Bind("Title") %>'></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField HeaderText="Description">
                    <ItemTemplate>
                        <%# Eval("Description") %>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtDescription" TextMode="MultiLine"  Rows="4" cols="30"
                            runat="server" Text='<%# Bind("Description") %>'></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField HeaderText="Location">
                    <ItemTemplate>
                        <%# Eval("Location") %>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtLocation" runat="server"
                                        Text='<%# Bind("Location") %>'></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField HeaderText="Number of Seats">
                    <ItemTemplate>
                        <%# Eval("NumberOfSeats") %>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtNumberOfSeats"  runat="server"
                                        Text='<%# Bind("NumberOfSeats") %>'></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField HeaderText="Start Date & Time">
                    <ItemTemplate>
                        <%# Eval("StartDateTime")%>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="start_DateTime"  runat="server"
                                        Text='<%# Bind("StartDateTime") %>'></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>


                <asp:TemplateField HeaderText="End Date & Time">
                    <ItemTemplate>
                        <%# Eval("EndDateTime")%>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="end_DateTime" runat="server"
                                        Text='<%# Bind("EndDateTime") %>'></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>


                <asp:TemplateField HeaderText="Is Active?">
                    <ItemTemplate>
                        <asp:Label ID="lblIsActive" runat="server" Text='<%# Eval("IsActive") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:CheckBox ID="isActive" runat="server" AutoPostBack="true"
                                        OnCheckedChanged="isActive_OnCheckedChanged" 
                                        Checked='<%# Convert.ToBoolean(Eval("IsActive")) %>' />
                    </EditItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField HeaderText="Delete?">
                    <ItemTemplate>
                        <span onclick="return confirm('Are you sure to Delete the record?')">
                            <asp:ImageButton ID="lnkB" runat="server" ImageUrl="Images/icons/delete24.png" CommandName="Delete" />
                        </span>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:PM_RegistrationSysDBConnectionString %>" 
            SelectCommand="SELECT ID, Title, Description, Location, StartDateTime, EndDateTime, 
                            NumberOfSeats, IsActive 
                            FROM Events 
                            WHERE (IsActive = 1) 
                            ORDER BY ID DESC"
            UpdateCommand="UPDATE [Events] SET [Title] = @Title, [Description] = @Description, 
                                                [Location] = @Location, [NumberOfSeats] = @NumberOfSeats, 
                                                [StartDateTime]= @StartDateTime, [EndDateTime] = @EndDateTime
                                                WHERE [ID] = @ID"
            DeleteCommand="DELETE FROM [Events] WHERE [ID] = @ID">
            <UpdateParameters>
                <asp:Parameter Name="Title" Type="String" />
                <asp:Parameter Name="Description" Type="String" />
                <asp:Parameter Name="Location" Type="String" />
                <asp:Parameter Name="NumberOfSeats" Type="Int32" />
                <asp:Parameter Name="StartDateTime" Type="DateTime" />
                <asp:Parameter Name="EndDateTime" Type="DateTime" />
            </UpdateParameters>
            <DeleteParameters>
                <asp:Parameter Name="ID" Type="Int32" />
            </DeleteParameters>
        </asp:SqlDataSource>

C# code:

 //for updating the (IsActive) column using checkbox inside the GridView
    protected void isActive_OnCheckedChanged(object sender, EventArgs e)
    {
        CheckBox chkStatus = (CheckBox)sender;
        GridViewRow gvrow = (GridViewRow)chkStatus.NamingContainer;

        //Get the ID which is the ID of the Event
        int ID = Convert.ToInt32(gvrow.Cells[0].Text);
        bool status = chkStatus.Checked;


        string connString = ConfigurationManager.ConnectionStrings["PM_RegistrationSysDBConnectionString"].ConnectionString;
        SqlConnection conn = new SqlConnection(connString);

        string updateIsActive = "UPDATE Events SET IsActive = @IsActive WHERE ID = @ID";

        SqlCommand cmd = new SqlCommand(updateIsActive, conn);

        cmd.Parameters.AddWithValue("@IsActive", status);
        cmd.Parameters.AddWithValue("@ID", ID);

        try
        {
            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();
        }
        catch (SqlException se)
        {
            throw se;
        }
        finally
        {
            cmd.Dispose();
            conn.Close();
            conn.Dispose();
        }

        //this is checkbox is unchecked then set backcolor to Gray
        if (!status)
        {
            gvrow.BackColor = Color.Black;
        }
    }

gvrow.Cells[0] will refer to your button.

It does not refer to your id.

You have put id in the second column.

Access code should be like

gvrow.Cells[1]

its better to add label and make it visible false , bind the ID to it and find the control using the FindControl method and then cast it to Label and access the Text property of the label.

  <asp:TemplateField HeaderText="Title">
       <ItemTemplate>
          <%# Eval("Title") %>

           <asp:Label ID="lblID"  runat="server" Visible="false" 
              Text='<%# Bind("ID") %>'></asp:Label>
        </ItemTemplate>
     <EditItemTemplate>
         <asp:TextBox ID="txtTitle"  runat="server" Text='<%# Bind("Title") %>'>         </asp:TextBox>

     </EditItemTemplate>
  </asp:TemplateField>

and in the code behind.

Label lblID = (Label)gvrow.FindControl("lblID");
int ID = Convert.ToInt32(lblID.Text); 

and then use this ID to update the status..

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM