Thursday, December 22

Select rows using ctrl key and copy selected rows to another gridview

In this article we will explore how to copy rows from one gridview to another gridview by selecting rows using control key.

Copy Row From one GridView to another using ctrl key

Let's write some code to achive this.

Step 1: Add below gridview in aspx page.

<asp:GridView ID="gvDept" runat="server" AutoGenerateColumns="False" CellPadding="5" Font-Name="verdana" Font-Size="10pt" onselectstart="return false;" BorderStyle="Solid" OnRowDataBound="gvDept_RowDataBound" DataKeyNames="DepartmentId">      <RowStyle BackColor="#99CCFF" />
      
<Columns
>
            
<asp:BoundField DataField="DepartmentId" HeaderText="Department Id" ItemStyle-VerticalAlign="Top" ItemStyle-Width="120px"
/>
            
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-VerticalAlign="Top" ItemStyle-Width="120px"
/>
            
<asp:BoundField DataField="GroupName" HeaderText="Group Name" ItemStyle-VerticalAlign="Top" ItemStyle-Width="120px"
/>
            
<asp:BoundField DataField="ModifiedDate" HeaderText="Modified Date" ItemStyle-VerticalAlign="Top" ItemStyle-Width="120px"
/>
      
</Columns
>
      
<HeaderStyle HorizontalAlign="Left" BackColor="#003366" ForeColor="#ffffff" Font-Bold="true" Font-Size=".75em"
/></asp:GridView>

Step 2: Add three hiddenfields, hidCellId will be used to hold the gridview cell ids, hidSelectedRow will be used to hold the selcted row ids and hidIsSelected will be used to find out row is slected or not.

<asp:HiddenField ID="hidCellId" runat="server" /><asp:HiddenField ID="hidSelectedRow" runat="server" /><asp:HiddenField ID="hidIsSelected" runat="server" />

Step 3: Add another gridview with the previous gridview structure.

<asp:GridView ID="gvDestDept" runat="server" AutoGenerateColumns="False" CellPadding="5" Font-Name="verdana" Font-Size="10pt" onselectstart="return false;" BorderStyle="Solid">
      
<RowStyle BackColor="#99CCFF"
/>
            
<Columns
>
                  
<asp:BoundField DataField="DepartmentId" HeaderText="Department Id" ItemStyle-VerticalAlign="Top" ItemStyle-Width="120px"
/>
                  
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-VerticalAlign="Top" ItemStyle-Width="120px"
/>
                  
<asp:BoundField DataField="GroupName" HeaderText="Group Name" ItemStyle-VerticalAlign="Top" ItemStyle-Width="120px"
/>
                  
<asp:BoundField DataField="ModifiedDate" HeaderText="Modified Date" ItemStyle-VerticalAlign="Top" ItemStyle-Width="120px"
/>
            
</Columns
>            <HeaderStyle HorizontalAlign="Left" BackColor="#003366" ForeColor="#ffffff" Font-Bold="true" Font-Size=".75em" /></asp:GridView>

Step 4: Add a button and a label. Button to copy selcted row from one gridview to another gridview.

<asp:Button ID="btnCopy" runat="server" OnClientClick="return IsRowSelected();" Text="Copy" OnClick="btnCopy_Click" /><asp:Label ID="lbl" runat="server" Text="Ctrl + Click to select multiple rows." />

Step 5: Add FillColor javascript which be called on cell click.

<script language="javascript" type="text/javascript">

      
function
FillColor(cellid, id,evt) {
            var isSelected = document.getElementById('<%=hidSelectedRow.ClientID%>'
);
            if (!evt) var
evt = window.event;
            ctrlPressed = evt.ctrlKey;
            if
(!ctrlPressed) {
                  var clearCellColor = document.getElementById('hidCellId').value.split(','
);
                  for
(i = 0; i < clearCellColor.length; i++) {
                        document.getElementById(clearCellColor[i]).bgColor = "#99CCFF"
;
                        document.getElementById(clearCellColor[i]).style.color = "Black"
;
                  }
                  isSelected.value = '
;
            }

            var cellNo = cellid.split('_');
            var
selectcellNo;
            var clearCellColor = document.getElementById('hidCellId').value.split(','
);
            if (document.getElementById('<%=hidIsSelected.ClientID%>'
).value != cellNo[1]) {
                  for
(i = 0; i < clearCellColor.length; i++) {
                        selectcellNo = clearCellColor[i].split('_'
);
                        var
objCell = document.getElementById(clearCellColor[i]);
                        if
(cellNo[1] == selectcellNo[1]) {
                              objCell.bgColor = "Maroon"
;
                              objCell.style.color = "White"
;
                              if
(!isSelected.value.match(id)) {
                                    if (isSelected.value == '
) {
                                          isSelected.value = id;
                                    }
                                    else
{
                                          isSelected.value = isSelected.value + ','
+ id;
                                    }
                              }
                        }
                  }
                  document.getElementById('<%=hidIsSelected.ClientID%>'
).value = cellNo[1];
            }
            else
{
                  document.getElementById('<%=hidIsSelected.ClientID%>').value = '
;
                  isSelected.value = '
;
            }
      }

function IsRowSelected() {
      if (document.getElementById('<%=hidSelectedRow.ClientID%>').value == '
) {
            alert('Nothing to copy'
);
            return false
;
      }
}

</script>

Step 6: Get data from HumanResources.Department table and bind it to gridview.

protected void Page_Load(object sender, EventArgs e)
{
      string strQuery = "SELECT * FROM HumanResources.Department"
;
      gvDept.DataSource = GetData(strQuery);
      gvDept.DataBind();
}

private DataTable GetData(string strQuery){
      DataTable dtDept = null
;
      using (SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=SSPI"
))
      {
            con.Open();
            using (SqlDataAdapter sqlAdapter = new SqlDataAdapter
(strQuery, con))
            {
                  dtDept = new DataTable
();
                  sqlAdapter.Fill(dtDept);
            }
      }
      return
dtDept;
}

Step 7: gvDept_RowDataBound will bind FillColor to each of the cell in gridview.



protected void gvDept_RowDataBound(Object sender, GridViewRowEventArgs
e)
{
      StringBuilder sbRowCellIds = new StringBuilder
();
      if (e.Row.RowType == DataControlRowType
.DataRow)
      {
            for (int
i = 0; i < gvDept.Columns.Count; i++)
            {
                  DataKey
dk = gvDept.DataKeys[e.Row.RowIndex];
                  string id = dk.Values["DepartmentId"
].ToString();
                  e.Row.Cells[i].Attributes.Add("onclick", "FillColor('" + e.Row.Cells[i].ClientID + "','" + id + "',event)"
);
                  if
(hidCellId.Value.Length == 0)
                  {
                        hidCellId.Value = e.Row.Cells[i].ClientID;
                  }
                  
else
                  
{
                        hidCellId.Value = hidCellId.Value + ","
+ e.Row.Cells[i].ClientID;
                  }
                  if
(sbRowCellIds.ToString().Length == 0)
                  {
                        sbRowCellIds.Append(e.Row.Cells[i].ClientID);
                  }
                  
else
                  
{
                        sbRowCellIds.Append(","
);
                        sbRowCellIds.Append(e.Row.Cells[i].ClientID);
                  }
            }
      }
}


Step 8: btnCopy_Click will get the selected data from table and bind it to second gridview

protected void btnCopy_Click(object sender, EventArgs e)
{
      string strQuery = "SELECT * FROM HumanResources.Department WHERE DepartmentId IN(" + hidSelectedRow.Value + ")"
;
      gvDestDept.DataSource = GetData(strQuery);
      gvDestDept.DataBind();
}



Live Demo


Download Code 

This ends the article of copy rows from one gridview to another by selecting multiple gridview rows using ctrl key.
Like us if you find this post useful. Thanks! 
SHIBASHISH MOHANTY

No comments:

Post a Comment

Please don't spam, spam comments is not allowed here.

.

ShibashishMnty
shibashish mohanty