locked
Need help with inserting checked record from Gridview RRS feed

  • Question

  • User126014556 posted

    I am unable to insert the checked record from the GridView using checkbox control.

    When I debuged code, it skips the logic, like as it does not exists, not sure what is happening but I appreciate any help.

            For Each gr As GridViewRow In grvPos.Rows
                Dim cb As CheckBox = CType(gr.FindControl("chkCheck"), CheckBox)
                If cb IsNot Nothing AndAlso cb.Checked Then

    here is my ASP page.

    <%@ Page Title="Period A" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="default.aspx.vb" Inherits="PositionUpdate._default" %>
    
    <asp:Content ID="Header1" ContentPlaceHolderID="header" runat="server">
        <script type="text/javascript" language="javascript">
    
            function HeaderCheckBoxClick(checkbox) {
                var gridView = document.getElementById("<%= grvPos.ClientID %>");
                for (i = 1; i < gridView.rows.length; i++) {
                    gridView.rows[i].cells[0].getElementsByTagName("INPUT")[0].checked
                        = checkbox.checked;
                }
            }
    
            function ChildCheckBoxClick(checkbox) {
                var atleastOneCheckBoxUnchecked = false;
                var gridView = document.getElementById("<%= grvPos.ClientID %>");
    
                for (i = 1; i < gridView.rows.length; i++) {
                    if (gridView.rows[i].cells[0].getElementsByTagName("INPUT")[0].checked == false)
                    {
                        atleastOneCheckBoxUnchecked = true;
                        break;
                    }
                    else 
                    {
                        gridView.rows[0].cells[0].getElementsByTagName("INPUT")[0].checked = !atleastOneCheckBoxUnchecked;
                    }
                }
                gridView.rows[0].cells[0].getElementsByTagName("INPUT")[0].checked = !atleastOneCheckBoxUnchecked;
            }
        </script>
    </asp:Content>
    
    <asp:Content ID="ContentHeader" ContentPlaceHolderID="contentHeader" runat="server">
        <h3 style="color: Navy; font-family: Verdana, Geneva, Tahoma, sans-serif; text-align: center">Security Position
        </h3>
    
            <asp:FormView ID="FormView1" runat="server" DataSourceID="sqlPrd" Font-Bold="True" HorizontalAlign ="Center" ForeColor="Navy">
            <ItemTemplate>
                Period
                <asp:Label ID="Label1" runat="server" Text='<%# Eval("PRD") %>'></asp:Label>
            </ItemTemplate>
        </asp:FormView>
        <asp:SqlDataSource ID="sqlPrd" runat="server" ConnectionString="<%$ ConnectionStrings:InterfaceConnectionString %>" SelectCommand="SELECT DISTINCT PRD FROM [OPTR_POS]">    
        </asp:SqlDataSource>
        </asp:Content>
    
    <asp:Content ID="Content2" ContentPlaceHolderID="Content" runat="server">
    
                <table>
                    <tr>
                        <td>
                           Value Date : <asp:TextBox ID="valueDate" runat="server"></asp:TextBox>
                        </td>
                         <td>
                           Portfolio Code : <asp:TextBox ID="portCode" runat="server"></asp:TextBox>
                        </td>
                                             <td>
                           Security Code : <asp:TextBox ID="secCode" runat="server"></asp:TextBox>
                        </td>
                        <td>
                            <asp:Button ID="searchBtn" runat="server" Text="Search" ToolTip="All three fields must be filled" />
                        </td>
                    </tr>
                </table>
    
        <asp:GridView ID="grvPos" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" PageSize="20" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Vertical" DataKeyNames="VALN_DATE,PORT_CODE,SEC_CODE">
            <AlternatingRowStyle BackColor="Gainsboro" />
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        &nbsp;&nbsp;<asp:CheckBox ID="chkCheck" runat="server" onclick="ChildCheckBoxClick(this);" />&nbsp;&nbsp;
                    </ItemTemplate>
                    <HeaderTemplate>
                        &nbsp&nbsp;<asp:CheckBox ID="chkCheckAll" runat="server" onclick="HeaderCheckBoxClick(this);" />&nbsp;&nbsp;
                    </HeaderTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="VALN_DATE" HeaderText="VALN_DATE" ReadOnly="True" SortExpression="VALN_DATE" >
                <ItemStyle HorizontalAlign="Center" />
                </asp:BoundField>
                <asp:BoundField DataField="VAL_TYPE" HeaderText="VAL_TYPE" SortExpression="VAL_TYPE" >
                <ItemStyle HorizontalAlign="Center" />
                </asp:BoundField>
                <asp:BoundField DataField="PORT_CODE" HeaderText="PORT_CODE" ReadOnly="True" SortExpression="PORT_CODE" >
                <ItemStyle HorizontalAlign="Center" />
                </asp:BoundField>
                <asp:BoundField DataField="PORT_SNAME" HeaderText="PORT_SNAME" SortExpression="PORT_SNAME" />
                <asp:BoundField DataField="SEC_CODE" HeaderText="SEC_CODE" ReadOnly="True" SortExpression="SEC_CODE" />
                <asp:BoundField DataField="ISIN_NO" HeaderText="ISIN_NO" SortExpression="ISIN_NO" />
                <asp:BoundField DataField="SEC_SNAME" HeaderText="SEC_SNAME" SortExpression="SEC_SNAME" />
                <asp:BoundField DataField="SEC_CCY_ABBR" HeaderText="SEC_CCY_ABBR" SortExpression="SEC_CCY_ABBR" >
                <ItemStyle HorizontalAlign="Center" />
                </asp:BoundField>
                <asp:BoundField DataField="BASE_CCY" HeaderText="BASE_CCY" SortExpression="BASE_CCY" >
                <ItemStyle HorizontalAlign="Center" />
                </asp:BoundField>
                <asp:BoundField DataField="TRX_BCCY_EX_RATE" HeaderText="EX_RATE" SortExpression="TRX_BCCY_EX_RATE" DataFormatString="{0:N9}" >
                <ItemStyle HorizontalAlign="Right" Width="100%" Wrap="False" />
                </asp:BoundField>
                <asp:BoundField DataField="QUANTITY" HeaderText="QUANTITY" SortExpression="QUANTITY" DataFormatString="{0:N3}" >
                <ItemStyle HorizontalAlign="Right" Width="100%" Wrap="False" />
                </asp:BoundField>
                <asp:BoundField DataField="MKT_PRICE" HeaderText="MKT_PRICE" SortExpression="MKT_PRICE" DataFormatString="{0:N8}" >
                <ItemStyle HorizontalAlign="Right" Width="100%" Wrap="False" />
                </asp:BoundField>
                <asp:BoundField DataField="AVG_COST" HeaderText="AVG_COST" SortExpression="AVG_COST" DataFormatString="{0:N3}" >
                <ItemStyle HorizontalAlign="Right" Width="100%" Wrap="False" />
                </asp:BoundField>
                <asp:BoundField DataField="MVAL_AMT_SC" HeaderText="MVAL_AMT_SC" SortExpression="MVAL_AMT_SC" DataFormatString="{0:N3}" >
                <ItemStyle HorizontalAlign="Right" Width="100%" Wrap="False" />
                </asp:BoundField>
                <asp:BoundField DataField="MVAL_AMT_BC" HeaderText="MVAL_AMT_BC" SortExpression="MVAL_AMT_BC" DataFormatString="{0:N3}" >
                <ItemStyle HorizontalAlign="Right" Width="100%" Wrap="False" />
                </asp:BoundField>
                <asp:BoundField DataField="AVG_BVAL_SC" HeaderText="AVG_BVAL_SC" SortExpression="AVG_BVAL_SC" DataFormatString="{0:N3}" >
                <ItemStyle HorizontalAlign="Right" Width="100%" Wrap="False" />
                </asp:BoundField>
                <asp:BoundField DataField="AVG_BVAL_BC" HeaderText="AVG_BVAL_BC" SortExpression="AVG_BVAL_BC" DataFormatString="{0:N3}" >
                <ItemStyle HorizontalAlign="Right" Width="100%" Wrap="False" />
                </asp:BoundField>
                <asp:BoundField DataField="INT_AMT_SC" HeaderText="INT_AMT_SC" SortExpression="INT_AMT_SC" DataFormatString="{0:N3}" >
                <ItemStyle HorizontalAlign="Right" Width="100%" Wrap="False" />
                </asp:BoundField>
                <asp:BoundField DataField="INT_AMT_BC" HeaderText="INT_AMT_BC" SortExpression="INT_AMT_BC" DataFormatString="{0:N3}" >
                <ItemStyle HorizontalAlign="Right" Width="100%" Wrap="False" />
                </asp:BoundField>
            </Columns>
            <EditRowStyle Wrap="False" />
            <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
            <HeaderStyle Wrap="False" BackColor="#000084" Font-Bold="True" ForeColor="White" />
            <PagerSettings Mode="NumericFirstLast" />
            <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Left" />
            <RowStyle Wrap="False" BackColor="#EEEEEE" ForeColor="Black" />
            <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#F1F1F1" />
            <SortedAscendingHeaderStyle BackColor="#0000A9" />
            <SortedDescendingCellStyle BackColor="#CAC9C9" />
            <SortedDescendingHeaderStyle BackColor="#000065" />
        </asp:GridView>
        <br />
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
    
    </asp:Content>
    

    Here is the code page:

    Imports System.Data.SqlClient
    
    Public Class _default
        Inherits System.Web.UI.Page
    
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    
            Dim cs As String
            Dim con As SqlConnection
            Dim sql As String
            Dim cmd As SqlCommand
    
            cs = ConfigurationManager.ConnectionStrings("InterfaceConnectionString").ConnectionString
            con = New SqlConnection(cs)
            sql = "SELECT * " &
                  "FROM OPTR_POS WHERE (VALN_DATE like @valDate) AND (PORT_CODE like @portCode) AND (SEC_CODE like @secCode)"
            cmd = New SqlCommand(sql, con)
            cmd.Parameters.AddWithValue("@valDate", "%" + valueDate.Text + "%")
            cmd.Parameters.AddWithValue("@portCode", "%" + portCode.Text + "%")
            cmd.Parameters.AddWithValue("@secCode", "%" + secCode.Text + "%")
    
            Try
                Using sda As SqlDataAdapter = New SqlDataAdapter()
                    cmd.Connection = con
                    sda.SelectCommand = cmd
                    Using dt As DataTable = New DataTable()
                        sda.Fill(dt)
                        grvPos.DataSource = dt
                        grvPos.DataBind()
                    End Using
                End Using
    
            Catch ex As Exception
    
            End Try
    
    
        End Sub
    
    
        Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
            Dim cs As String
            Dim con As SqlConnection
            Dim sql As String
            Dim cmd As SqlCommand
            Dim valDate As Integer
            Dim portCode As String
            Dim secCode As String
    
            For Each gr As GridViewRow In grvPos.Rows
                Dim cb As CheckBox = CType(gr.FindControl("chkCheck"), CheckBox)
                If cb IsNot Nothing AndAlso cb.Checked Then
    
                    valDate = grvPos.DataKeys(gr.RowIndex).Values("VALN_DATE")
                    portCode = grvPos.DataKeys(gr.RowIndex).Values("PORT_CODE").ToString()
                    secCode = grvPos.DataKeys(gr.RowIndex).Values("SEC_CODE").ToString()
    
                    cs = ConfigurationManager.ConnectionStrings("InterfaceCS_Test").ConnectionString
                    con = New SqlConnection(cs)
                    sql = "INSERT INTO OPTR_POS_FIXTEST " &
                          "(VALN_DATE, VAL_TYPE, PORT_CODE, PORT_SNAME, PORT_NAME, PORT_GROUP_CD, PORT_GROUP_NAME, CENTRE, CENTRE_NAME, SEC_CODE, ISIN_NO, SEC_SNAME, SEC_NAME, SEC_CCY, SEC_CCY_ABBR, SC_BC_EX_RATE, BASE_CCY, TRX_BCCY_EX_RATE, QUANTITY, MKT_PRICE, AVG_COST, MVAL_AMT_SC, MVAL_AMT_BC, AVG_BVAL_SC, AVG_BVAL_BC, INT_AMT_SC, INT_AMT_BC, PRD) " &
                          "SELECT VALN_DATE, VAL_TYPE, PORT_CODE, PORT_SNAME, PORT_NAME, PORT_GROUP_CD, PORT_GROUP_NAME, CENTRE, CENTRE_NAME, SEC_CODE, ISIN_NO, SEC_SNAME, SEC_NAME, SEC_CCY, SEC_CCY_ABBR, SC_BC_EX_RATE, BASE_CCY, TRX_BCCY_EX_RATE, QUANTITY, MKT_PRICE, AVG_COST, MVAL_AMT_SC, MVAL_AMT_BC, AVG_BVAL_SC, AVG_BVAL_BC, INT_AMT_SC, INT_AMT_BC, PRD " &
                          "FROM OPTR_POS WHERE (VALN_DATE = @valDate) AND (PORT_CODE = @portCode) AND (SEC_CODE = @secCode)"
                    cmd = New SqlCommand(sql, con)
                    cmd.Parameters.AddWithValue("@valDate", valDate)
                    cmd.Parameters.AddWithValue("@portCode", portCode)
                    cmd.Parameters.AddWithValue("@secCode", secCode)
    
                    '  Try
                    Using con
                        con.Open()
                        cmd.ExecuteNonQuery()
                        grvPos.DataBind()
                    End Using
                    '    Catch ex As Exception
    
                    ' End Try
                End If
            Next
    
        End Sub
    
        Protected Sub searchBtn_Click(sender As Object, e As EventArgs) Handles searchBtn.Click
    
            Dim cs As String
            Dim con As SqlConnection
            Dim sql As String
            Dim cmd As SqlCommand
    
            cs = ConfigurationManager.ConnectionStrings("InterfaceConnectionString").ConnectionString
            con = New SqlConnection(cs)
            sql = "SELECT * " &
                  "FROM OPTR_POS WHERE (VALN_DATE like @valDate) AND (PORT_CODE like @portCode) AND (SEC_CODE like @secCode)"
            cmd = New SqlCommand(sql, con)
            cmd.Parameters.AddWithValue("@valDate", "%" + valueDate.Text + "%")
            cmd.Parameters.AddWithValue("@portCode", "%" + portCode.Text + "%")
            cmd.Parameters.AddWithValue("@secCode", "%" + secCode.Text + "%")
    
            Try
                Using sda As SqlDataAdapter = New SqlDataAdapter()
                    cmd.Connection = con
                    sda.SelectCommand = cmd
                    Using dt As DataTable = New DataTable()
                        sda.Fill(dt)
                        grvPos.DataSource = dt
                        grvPos.DataBind()
                    End Using
                End Using
    
            Catch ex As Exception
    
            End Try
    
        End Sub
    
        Protected Sub grvPos_PageIndexChanging(sender As Object, e As GridViewPageEventArgs) Handles grvPos.PageIndexChanging
            Try
                grvPos.PageIndex = e.NewPageIndex
                grvPos.DataBind()
    
            Catch ex As Exception
    
            End Try
    
        End Sub
    End Class

    Thanks in advance.

    Tuesday, May 1, 2018 8:18 AM

Answers

  • User475983607 posted

    there are two obvious construct and logical errors.  Page_Load event rebinds the GridView on each request so you're basically resetting the checkboxes on every post.  Wrap the GridView initialization in...

    If Not Page.IsPostBack Then
       ' Initialize the grid on first HTTP GET
    End If

    This is a basic construct in Web Forms.  Initialize the server controls if the current request is not a PostBack,

    There are empty catch blocks throughout the code.

            Catch ex As Exception
    
            End Try

    The code could throw exception but you'll never know.  At the very least retrow the exception; https://msdn.microsoft.com/en-us/library/ms182363.aspx

            Catch ex As Exception
                 Throw
            End Try

    You should decide on an exception handling design and implement it, IMHO.

    Fix, these design bugs then retry.  It is likely that you'll find other errors after rethrowing exceptions.  You'll need debug each issue and fix it.  Use the Visual Studio debugger for this task.

    https://msdn.microsoft.com/en-us/library/y740d9d3.aspx

    Perhaps take a moment to go through Getting Started tutorials if you are new to programming Web Forms.

    https://www.asp.net/web-forms

    Lastly, consider learning how to build unit tests.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, May 1, 2018 2:38 PM
  • User-1716253493 posted

    You must call grvPost.DataBind() inside if not ispostback block

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, May 1, 2018 3:04 PM

All replies

  • User475983607 posted

    there are two obvious construct and logical errors.  Page_Load event rebinds the GridView on each request so you're basically resetting the checkboxes on every post.  Wrap the GridView initialization in...

    If Not Page.IsPostBack Then
       ' Initialize the grid on first HTTP GET
    End If

    This is a basic construct in Web Forms.  Initialize the server controls if the current request is not a PostBack,

    There are empty catch blocks throughout the code.

            Catch ex As Exception
    
            End Try

    The code could throw exception but you'll never know.  At the very least retrow the exception; https://msdn.microsoft.com/en-us/library/ms182363.aspx

            Catch ex As Exception
                 Throw
            End Try

    You should decide on an exception handling design and implement it, IMHO.

    Fix, these design bugs then retry.  It is likely that you'll find other errors after rethrowing exceptions.  You'll need debug each issue and fix it.  Use the Visual Studio debugger for this task.

    https://msdn.microsoft.com/en-us/library/y740d9d3.aspx

    Perhaps take a moment to go through Getting Started tutorials if you are new to programming Web Forms.

    https://www.asp.net/web-forms

    Lastly, consider learning how to build unit tests.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, May 1, 2018 2:38 PM
  • User-1716253493 posted

    You must call grvPost.DataBind() inside if not ispostback block

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, May 1, 2018 3:04 PM
  • User126014556 posted

    Thanks for the great advice.

    How can I solve the paging issue?

    When I add a checkmark on the first page it clears out in the second page.

    Wednesday, May 2, 2018 4:37 AM