Calculate percentage on ASP.Net GridView RowUpdating event using C# and VB.Net

Last Reply 4 months ago By pandeyism

Posted 4 months ago

Hi All, I am Vasudev, Presently I am stuck with an issue with Gridview.

1. I have few Databound fields namely [Name, Age, Gender]

2. I have made the Databound fields as ReadOnly as they should not be Editable.

3. I have few Template fields, After clicking Edit User is supposed to Enter the values forCorrect and Incorrect Answers Manually.

4. Depending on The Entries Entered in the Columns remaining columns [Correct and Incorrect] The values [ Un Attended, Result should be calculated automatically]

5. Could you please suggest whether gridview is the right choice for this If Yes, Please help me out.

6. Please let me know, if you need any further details from my end.

7. I am adding sample coding along with this.

Regards,

Vasudev.

<asp:GridView ID="dgCptResult" runat="server" AutoGenerateColumns="False" Width="100%" OnRowEditing="dgCptResult_RowEditing" OnPageIndexChanging="dgCptResult_PageIndexChanging1" AllowPaging="True" OnRowCancelingEdit="dgCptResult_RowCancelingEdit1" OnRowUpdating="dgCptResult_RowUpdating1" DataKeyNames="HQPHTBSYSID" HorizontalAlign="Center" AutoGenerateEditButton="True">
    <Columns>
        <asp:BoundField DataField="HQPHTBSYSID" HeaderText="HQPID" ReadOnly="True"/>
        <asp:BoundField DataField="CNDSYSID" HeaderText="ID" ReadOnly="True" Visible="False" />
        <asp:BoundField DataField="NAME" HeaderText="NAME" ReadOnly="True" />
        <asp:BoundField DataField="CNDAGE" HeaderText="AGE" ReadOnly="True"/>
        <asp:BoundField DataField="CNDGENDER" HeaderText="GENDER" ReadOnly="True" />
                                                                                                   
        <asp:TemplateField HeaderText="CORRECT">
            <EditItemTemplate>
                <asp:TextBox ID="txtcorrect" Width="100%" runat="server"></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="lblcorrect" Width="100%" runat="server" ></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
                                                        
        <asp:TemplateField HeaderText="INCORRECT">
            <EditItemTemplate>
                <asp:TextBox ID="txtincorrect" Width="100%" runat="server"></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="lblincorrect" Width="100%" runat="server" ></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>                           
            <asp:TemplateField HeaderText="ATTENDED">
            <EditItemTemplate>
                <asp:TextBox ID="txtAtended" Width="100%" runat="server"></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="lblAtended" Width="100%" runat="server" ></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>                          
                                                        
        <asp:TemplateField HeaderText="UNATTENDED">
            <EditItemTemplate>
                <asp:TextBox ID="txtUnAtended" Width="100%" runat="server"></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="lblUnAtended" Width="100%" runat="server" ></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>                         
                                                        
            <asp:TemplateField HeaderText="RESULT">
            <EditItemTemplate>
                <asp:TextBox ID="txtresult" Width="100%" runat="server"></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="lblresult" Width="100%" runat="server" ></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>                                                        
    </Columns>
    <HeaderStyle BackColor="#C0C0FF" />
    <AlternatingRowStyle BackColor="#C0FFC0" HorizontalAlign="Center" VerticalAlign="Middle" />
    <PagerSettings FirstPageText="" LastPageText="" NextPageText="" PreviousPageText="" />
    <RowStyle HorizontalAlign="Center" VerticalAlign="Middle" />
    <SelectedRowStyle Wrap="False" />
</asp:GridView>

 

    Sub LoadResults()
        Try
            'UAT 3 sogy CHECKING lOGIN EXPIRY PUT SESSION VALUE TO A HIIDEN VARIABLE
            'Dim ds As New DataSet
            str_Query = "  SELECT DISTINCT HQQP.HQPHTBSYSID,CDTS.CNDSYSID,CDTS.CNDSURNAME ||'-'|| CDTS.CNDFIRSTNAME AS NAME,CDTS.CNDAGE,CDTS.CNDGENDER,HQQP.HQPCORRECTANS AS CORRECT,HQQP.HQPWRONGANS AS INCORRECT,HQQP.HQPRESULT AS RESULT  FROM CANDIDATES CDTS "
            str_Query += " INNER JOIN HQTESTBOOKINGS HBS ON CDTS.CNDSYSID=HBS.HTBCNDSYSID"
            str_Query += " INNER JOIN HQQUESTIONPAPERS	HQQP ON HQQP.HQPHTBSYSID = HBS.HTBSYSID"
            str_Query += " INNER JOIN TESTLOCATIONS TLC ON TLC.TLSYSID = HBS.HTBTLSYSID WHERE HQQP.HQPRESULT IS NULL "

            If (txt_TestDate.Text <> "") Then
                str_Query &= " AND HBS.HTBDATE='" + txt_TestDate.Text + "' "

                str_Query &= " ORDER BY NAME ASC "

                l_ws_DTTS = New wsDTTS(ClsGenFun.gf_str_GetDBType, ClsGenFun.gf_str_GetConnStr(ClsGenFun.gf_str_GetDBType))
                ds = l_ws_DTTS.gf_ds_GetDataset(str_Query, 0, 0)

                If ds.Tables(0).Rows.Count > 0 Then
                    dgCptResult.DataSource = ds
                    dgCptResult.DataBind()

                Else
                    lblGridStatus.Visible = True
                End If
            End If
            
        Catch ex As Exception
        End Try
    End Sub

 

Posted 4 months ago

Hi VasuDev,

Refer below sample and link -

Step by Step Tutorial for performing Insert Edit Update and Delete in GridView in ASP.Net

HTML

<asp:GridView ID="dgCptResult" runat="server" AutoGenerateColumns="False" OnRowEditing="dgCptResult_RowEditing"
    OnPageIndexChanging="dgCptResult_PageIndexChanging1" AllowPaging="True" OnRowCancelingEdit="dgCptResult_RowCancelingEdit1"
    OnRowUpdating="dgCptResult_RowUpdating1" DataKeyNames="HQPHTBSYSID" AutoGenerateEditButton="True">
    <Columns>
        <asp:BoundField DataField="HQPHTBSYSID" HeaderText="HQPID" ReadOnly="True" />
        <asp:BoundField DataField="NAME" HeaderText="NAME" ReadOnly="True" />
        <asp:TemplateField HeaderText="CORRECT">
            <EditItemTemplate>
                <asp:TextBox ID="txtcorrect" runat="server"></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="lblcorrect" runat="server"></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="INCORRECT">
            <EditItemTemplate>
                <asp:TextBox ID="txtincorrect" runat="server"></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="lblincorrect" runat="server"></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="ATTENDED">
            <EditItemTemplate>
                <asp:TextBox ID="txtAtended" runat="server"></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="lblAtended" runat="server"></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="UNATTENDED">
            <EditItemTemplate>
                <asp:TextBox ID="txtUnAtended" runat="server"></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="lblUnAtended" runat="server"></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="RESULT">
            <EditItemTemplate>
                <asp:TextBox ID="txtresult" runat="server"></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="lblresult" runat="server"></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
    <HeaderStyle BackColor="#C0C0FF" />
</asp:GridView>

Namespaces

C#

using System.Data;

VB.Net

Imports System.Data

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        BindGrid();
    }
}

private void BindGrid()
{
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[] { 
                        new DataColumn("HQPHTBSYSID", typeof(int)),
                        new DataColumn("NAME", typeof(string)) });
    dt.Rows.Add(1, "Mudassar Khan");
    dt.Rows.Add(2, "John Hammond");
    dgCptResult.DataSource = dt;
    dgCptResult.DataBind();
}

protected void dgCptResult_PageIndexChanging1(object sender, GridViewPageEventArgs e)
{
    dgCptResult.PageIndex = e.NewPageIndex;
    dgCptResult.DataBind();
}

protected void dgCptResult_RowCancelingEdit1(object sender, GridViewCancelEditEventArgs e)
{
    dgCptResult.EditIndex = -1;
    this.BindGrid();
}

protected void dgCptResult_RowEditing(object sender, GridViewEditEventArgs e)
{
    dgCptResult.EditIndex = e.NewEditIndex;
    this.BindGrid();
}

protected void dgCptResult_RowUpdating1(object sender, GridViewUpdateEventArgs e)
{
    GridViewRow row = dgCptResult.Rows[e.RowIndex];
    int Id = Convert.ToInt32(dgCptResult.DataKeys[e.RowIndex].Values[0]);
    int correct = (Convert.ToInt32((row.FindControl("txtcorrect") as TextBox).Text));
    int inCorrect = (Convert.ToInt32((row.FindControl("txtincorrect") as TextBox).Text));
    int attend = (Convert.ToInt32((row.FindControl("txtAtended") as TextBox).Text));
    int unatttend = (Convert.ToInt32((row.FindControl("txtUnAtended") as TextBox).Text));
    int total = attend + unatttend;
    int result = (correct * 100) / total;
    (row.FindControl("txtresult") as TextBox).Text = result.ToString() + "%";
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        BindGrid()
    End If
End Sub

Private Sub BindGrid()
    Dim dt As DataTable = New DataTable()
    dt.Columns.AddRange(New DataColumn() {New DataColumn("HQPHTBSYSID", GetType(Integer)), New DataColumn("NAME", GetType(String))})
    dt.Rows.Add(1, "Mudassar Khan")
    dt.Rows.Add(2, "John Hammond")
    dgCptResult.DataSource = dt
    dgCptResult.DataBind()
End Sub

Protected Sub dgCptResult_PageIndexChanging1(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
    dgCptResult.PageIndex = e.NewPageIndex
    dgCptResult.DataBind()
End Sub

Protected Sub dgCptResult_RowCancelingEdit1(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
    dgCptResult.EditIndex = -1
    Me.BindGrid()
End Sub

Protected Sub dgCptResult_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
    dgCptResult.EditIndex = e.NewEditIndex
    Me.BindGrid()
End Sub

Protected Sub dgCptResult_RowUpdating1(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
    Dim row As GridViewRow = dgCptResult.Rows(e.RowIndex)
    Dim Id As Integer = Convert.ToInt32(dgCptResult.DataKeys(e.RowIndex).Values(0))
    Dim correct As Integer = (Convert.ToInt32((TryCast(row.FindControl("txtcorrect"), TextBox)).Text))
    Dim inCorrect As Integer = (Convert.ToInt32((TryCast(row.FindControl("txtincorrect"), TextBox)).Text))
    Dim attend As Integer = (Convert.ToInt32((TryCast(row.FindControl("txtAtended"), TextBox)).Text))
    Dim unatttend As Integer = (Convert.ToInt32((TryCast(row.FindControl("txtUnAtended"), TextBox)).Text))
    Dim total As Integer = attend + unatttend
    Dim result As Integer = (correct * 100) / total
    TryCast(row.FindControl("txtresult"), TextBox).Text = result.ToString() & "%"
End Sub

Screenshot