Solved

Bulk Edit in GridView using DOTNET

Posted on 2014-10-14
6
403 Views
Last Modified: 2014-10-16
I need to help user in building them a editable gridview which acts like a excel where they can edit multiple rows and update on click of a submit button in the end. Tried a few online but no success so far.
0
Comment
Question by:welcome 123
  • 3
  • 2
6 Comments
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 40381918
0
 
LVL 28

Expert Comment

by:sammySeltzer
ID: 40382401
I have an editable gridview that allows you to edit one or multiple rows at same time but it does not look like an excel sheet.

See screenshot.

Will this work for you?
multichecks.jpg
0
 

Author Comment

by:welcome 123
ID: 40382597
I am not sure how far I can convince in buying something but can give it a try and sammySeltzer I really like the screenshot and I think that's enough for achieving the multi edit functionality though not like excel but I really like it can you share the source code too?
0
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
LVL 28

Accepted Solution

by:
sammySeltzer earned 500 total points
ID: 40382650
Here you go. Hope it helps you.

'///Markup

    <p style="height: 0px; margin-bottom: 50px; font-style: normal; font-size: large; top: auto;">
        Click to check one or more checkboxes, enter worker's Test scores and click the <b>Store the score</b> button to save scores to the database.
        When you are done storing the scores for a particular worker, click the <b>Return</b> link below to continue.
    </p> 
    <br /><br />
           <asp:label id="Message" forecolor="firebrick" runat="server"/>&nbsp;|&nbsp; <a href="yourpage.aspx">Return</a>
           <br /><br />
    <div style="display: block;">
       <fieldset style="margin-bottom: 20px;width:600px;">
         <legend style="font-weight: bold;">In-Person Training</legend>
           <asp:GridView ID="gvInPerson" 
            CssClass="tablestyle" 
            AllowSorting="True"
            runat="server" 
            AutoGenerateColumns="False" 
            DataKeyNames = "trainingId"  
            OnPageIndexChanging="gvInPerson_PageIndexChanging" 
            AllowPaging="true" PageSize="10" 
            ForeColor="#333333" CellPadding="4" GridLines="None"> 
               <EditRowStyle BackColor="#999999" />
               <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <HeaderStyle   
                BackColor="#5D7B9D"   
                ForeColor="White" 
                Font-Bold="True"
                /> 
                <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
        <Columns>
            <asp:TemplateField>
                <HeaderTemplate>
                    <asp:CheckBox ID = "chkAll" runat="server" AutoPostBack="true" OnCheckedChanged="OnCheckedChanged" />
                </HeaderTemplate>
                <ItemTemplate>
                    <asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="true" OnCheckedChanged="OnCheckedChanged" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Name" ItemStyle-Width = "250">
                <ItemTemplate>
                    <asp:Label ID="nameLB" runat="server" Text='<%# Eval("FullName") %>'></asp:Label>
                    <asp:TextBox ID="txtName" runat="server" Text='<%# Eval("FullName") %>' Width="200" Visible="false"></asp:TextBox>
                </ItemTemplate>

<ItemStyle Width="250px"></ItemStyle>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Training" ItemStyle-Width = "250">
                <ItemTemplate>
                    <asp:Label ID="courseLB" runat="server" Text='<%# Eval("CourseName") %>'></asp:Label>
                    <asp:TextBox ID="txtCourse" runat="server" Text='<%# Eval("CourseName") %>'  Width="200" Visible="false"></asp:TextBox>
                </ItemTemplate>

<ItemStyle Width="150px"></ItemStyle>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Test Scores" ItemStyle-Width = "250">
                <ItemTemplate>
                    <asp:Label ID="scoresLB" runat="server" Text='<%# Eval("Scores") %>'></asp:Label>
                    <asp:TextBox ID="txtScores" runat="server" Text='<%# Eval("Scores") %>' Visible="false"></asp:TextBox>
                </ItemTemplate>

<ItemStyle Width="150px"></ItemStyle>
            </asp:TemplateField>
        </Columns>
               <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
               <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
               <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
               <SortedAscendingCellStyle BackColor="#E9E7E2" />
               <SortedAscendingHeaderStyle BackColor="#506C8C" />
               <SortedDescendingCellStyle BackColor="#FFFDF8" />
               <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
    </asp:GridView>
    <br />
    <asp:Button ID="btnUpdate" runat="server" Text="Store the score" OnClick = "Update" Visible = "false"/>
            </fieldset>
       </div>
</div>

Open in new window


'///Codebehind

Imports System.Data
Imports System.Linq
Imports System.Configuration
Imports System.Data.SqlClient
Partial Class RecordInPersonAnswers
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        If Not IsPostBack Then
            If (Not (Request.QueryString("SelectedUser")) Is Nothing) Then
                Session("selectedworker") = Request.QueryString("SelectedUser")
            End If
            If (Not (Request.QueryString("SelectedDate")) Is Nothing) Then
                Session("DateSelected") = Request.QueryString("SelectedDate")
            End If

            'Dim dateNtime As String
            'dateNtime = Request.QueryString("SelectedUser")
            Message.Text = "Add scores for the following training date: " & Request.QueryString("SelectedDate")
            'Response.Write(Session("DateSelected") & " - " & Session("selectedworker"))
            'Response.End()

            Me.BindGrid()
        End If

    End Sub
    Private Sub BindGrid()
        Dim cmd As New SqlCommand("select....from yourTable where = " & Session("selectedworker") & _
                        " ORDER BY FullName ASC")
        gvInPerson.DataSource = Me.ExecuteQuery(cmd, "SELECT")
        gvInPerson.DataBind()
    End Sub
    Private Function ExecuteQuery(ByVal cmd As SqlCommand, ByVal action As String) As DataTable
        Dim conString As String = ConfigurationManager.ConnectionStrings("DBConnectionString").ConnectionString
        Using con As New SqlConnection(conString)
            cmd.Connection = con
            Select Case action
                Case "SELECT"
                    Using sda As New SqlDataAdapter()
                        sda.SelectCommand = cmd
                        Using dt As New DataTable()
                            sda.Fill(dt)
                            Return dt
                        End Using
                    End Using
                Case "UPDATE"
                    con.Open()
                    cmd.ExecuteNonQuery()
                    con.Close()
                    Exit Select
            End Select
            Return Nothing
        End Using
    End Function

    Protected Sub Update(ByVal sender As Object, ByVal e As EventArgs)
        For Each row As GridViewRow In gvInPerson.Rows
            If row.RowType = DataControlRowType.DataRow Then
                Dim isChecked As Boolean = row.Cells(0).Controls.OfType(Of CheckBox)().FirstOrDefault().Checked
                If isChecked Then
                    Dim cmd As New SqlCommand("UPDATE yourTable SET scores = @scores WHERE courseId = @cname and trainingId = @TrainId")
                    cmd.Parameters.AddWithValue("@scores", row.Cells(3).Controls.OfType(Of TextBox)().FirstOrDefault().Text)
                    cmd.Parameters.AddWithValue("@cname", Session("selectedworker"))
                    cmd.Parameters.AddWithValue("@TrainId", gvInPerson.DataKeys(row.RowIndex).Value)
                    Me.ExecuteQuery(cmd, "SELECT")
                End If
                Message.Text = "Score successfully stored in the database"
            End If
        Next
        btnUpdate.Visible = False
        Me.BindGrid()
    End Sub

    Protected Sub OnCheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim isUpdateVisible As Boolean = False
        Dim chk As CheckBox = TryCast(sender, CheckBox)
        If chk.ID = "chkAll" Then
            For Each row As GridViewRow In gvInPerson.Rows
                If row.RowType = DataControlRowType.DataRow Then
                    row.Cells(0).Controls.OfType(Of CheckBox)().FirstOrDefault().Checked = chk.Checked
                End If
            Next
        End If

        Dim chkAll As CheckBox = TryCast(gvInPerson.HeaderRow.FindControl("chkAll"), CheckBox)
        chkAll.Checked = True
        For Each row As GridViewRow In gvInPerson.Rows
            If row.RowType = DataControlRowType.DataRow Then
                Dim isChecked As Boolean = row.Cells(0).Controls.OfType(Of CheckBox)().FirstOrDefault().Checked
                For i As Integer = 1 To row.Cells.Count - 1
                    row.Cells(i).Controls.OfType(Of Label)().FirstOrDefault().Visible = Not isChecked
                    If row.Cells(i).Controls.OfType(Of TextBox)().ToList().Count > 0 Then
                        row.Cells(i).Controls.OfType(Of TextBox)().FirstOrDefault().Visible = isChecked
                    End If
                    If row.Cells(i).Controls.OfType(Of DropDownList)().ToList().Count > 0 Then
                        row.Cells(i).Controls.OfType(Of DropDownList)().FirstOrDefault().Visible = isChecked
                    End If
                    If isChecked AndAlso Not isUpdateVisible Then
                        isUpdateVisible = True
                    End If
                    If Not isChecked Then
                        chkAll.Checked = False
                    End If
                Next
            End If
        Next
        btnUpdate.Visible = isUpdateVisible
    End Sub
    Protected Sub gvInPerson_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs) Handles gvInPerson.PageIndexChanging
        gvInPerson.PageIndex = e.NewPageIndex
        Me.BindGrid()
        gvInPerson.DataBind()
    End Sub
End Class

Open in new window

0
 

Author Comment

by:welcome 123
ID: 40385008
U are a life saver
0
 
LVL 28

Expert Comment

by:sammySeltzer
ID: 40385074
You are very welcome!
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

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…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

809 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