Sunday 12 February 2012

Select All in Multiple Page Grid View (Normal)


Previously I had blogged on Select All in Multiple Page Grid View, which was given advanced functionalities including selecting the whole page, unselecting the records when all page selected etc. But considering the implementation, we might not use that much functionalities in all our projects.

So this post provides an example of selecting multiple records by navigating multiple pages in the Grid View. The use case for this implementation is follows.
  1. Required a Grid View to show list of Products in a Grid View and enabled the records to show in Multiple Page.
  2. The Grid View should contain a Select column for selecting and un-selecting records.
  3. The Grid View can be selected by default by providing the selected records id from the code behind.
  4. The user can select any record in any page using the select check box and can unselect the same.
  5. The user can navigate to other page by the pagination and select/unselect in the same way.
  6. When user navigate the old page, the records must be selected which are selected already.
  7. The developer can able to get the selected records Id from the code behind at any time.
The implementation follows –

The ASPX script
<asp:GridView ID="grdViewProducts" runat="server"
    AllowPaging="True" AutoGenerateColumns="False" TabIndex="1"
    DataKeyNames="ProductID" Width="100%"
    CellPadding="4" ForeColor="#333333" 
    onpageindexchanging="grdViewProducts_PageIndexChanging">
    <Columns>
        <asp:BoundField DataField="ProductName" HeaderText="Product Name" />
        <asp:BoundField DataField="CompanyName" HeaderText="Supplier" />
        <asp:BoundField DataField="CategoryName" HeaderText="Category Name" />
        <asp:BoundField DataField="CategoryName" HeaderText="Category" />
        <asp:BoundField DataField="QuantityPerUnit" HeaderText="Quantity Per Unit"/>
        <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" DataFormatString="{0:#0.00}" />
        <asp:TemplateField HeaderText="Select">
            <ItemTemplate>
                <asp:CheckBox runat="server" ID="chkSelect" onclick="SelectRow(this.id)" />
                <asp:Label runat="server" ID="lblProductId" Text='<%# Eval("ProductID") %>' CssClass="InvisibleControl"></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Right" />
    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
</asp:GridView>
<asp:Button ID="btnProcess" runat="server" Text="Process" Width="100px" OnClick="btnProcess_Click" />
<asp:Label runat="server" ID="lblMessage" ></asp:Label>
<asp:HiddenField ID="hndSelectedRowId" runat="server" Value="" />
Here, the select (last) column contains a template column which has two controls.
chkSelect – This control is used for selecting record for each row.
lblProductId – This control is used for holding the Product Id. This Ids are for identifying which records selected.

The JavaScript
var Const_LastCol_Index = 6;
var vGridViewClientId = '<%= grdViewProducts.ClientID %>';
var vhndSelectedRowId = '<%= hndSelectedRowId.ClientID %>';
var vIsFooterExist = 1; //(0 - No, 1 - Yes)
var vUniqueControlId = 'lblProductId';
var vSelectCheckBoxId = 'chkSelect';

// I am calling a Javascript function to change the selected row color on page load
var browserName = navigator.appName;
if (browserName == "Microsoft Internet Explorer") {
    window.onload = SelectGridOnLoad;
}
else {
    if (browserName == "Netscape") //google chrome app.Name
    {
        setTimeout("SelectGridOnLoad()", 500);
    }
    else {
        window.onload = SelectGridOnLoad; // helps with Opera
    }
}

function SelectGridOnLoad() {
    var varDataRowStartIndex = 1;
    var NoofRowSelected = 0;

    // Looping all the row (Here - 1 is used as I have footer in the Grid View and starting from 1 Row (0 is Header)
    // So if you dont have Footer required to loop till end of the row (ie., no -1).
    for (var intRow = varDataRowStartIndex; intRow < document.getElementById(vGridViewClientId).rows.length - vIsFooterExist; intRow++) {

        // Declaring variable for Holding Values
        var vCheckById = 0;
        var vProductId = '';

        // Getting the GridView Row
        var gridRow = document.getElementById(vGridViewClientId).rows[intRow];

        for (var intCell = 0; intCell < gridRow.cells[Const_LastCol_Index].childNodes.length; intCell++) // Looping the Row cell
        {
            if (gridRow.cells[Const_LastCol_Index].childNodes[intCell].id != null) {

                // Getting Check box Id (to know the check box selected)
                if (gridRow.cells[Const_LastCol_Index].childNodes[intCell].id.indexOf(vSelectCheckBoxId) != -1)
                    vCheckById = gridRow.cells[Const_LastCol_Index].childNodes[intCell].id;

                // Getting the label value
                if (gridRow.cells[Const_LastCol_Index].childNodes[intCell].id.indexOf(vUniqueControlId) != -1) {
                    if (browserName == "Microsoft Internet Explorer")  //Getting the ProductId
                        vProductId = gridRow.cells[Const_LastCol_Index].childNodes[intCell].innerText;
                    else
                        vProductId = gridRow.cells[Const_LastCol_Index].childNodes[intCell].textContent;
                }
            }
        }
        var vSelecteIds = "," + document.getElementById(vhndSelectedRowId).value + ",";
        if (vSelecteIds.indexOf("," + vProductId + ",") != -1) { // Means Selected
            document.getElementById(vCheckById).checked = true;
            gridRow.className = "SelectedRowStyle";
            NoofRowSelected = parseInt(NoofRowSelected) + 1;
        }
        else { // For normal row
            document.getElementById(vCheckById).checked = false;
            gridRow.className = "NormalRowStyle";
        }
    }
}
function SelectRow(Id) {

    var vProductId = 0;

    var gridRow = document.getElementById(Id).parentNode.parentNode;

    // Getting the Product Id
    for (var intCell = 0; intCell < gridRow.cells[Const_LastCol_Index].childNodes.length; intCell++) // Looping the last Row controls
    {
        if (gridRow.cells[Const_LastCol_Index].childNodes[intCell].id != null) {

            if (gridRow.cells[Const_LastCol_Index].childNodes[intCell].id.indexOf(vUniqueControlId) != -1) {
                if (browserName == "Microsoft Internet Explorer")  //Getting the ProductId
                    vProductId = gridRow.cells[Const_LastCol_Index].childNodes[intCell].innerText;
                else
                    vProductId = gridRow.cells[Const_LastCol_Index].childNodes[intCell].textContent;
            }
        }
    }

    if (document.getElementById(Id).checked == true) // If Selected
    {
        AddSelectedId(vProductId, 1);
        gridRow.className = "SelectedRowStyle";
    }
    else // If unselected - Replace the style to normal row
    {
        RemoveSelectedId(vProductId, 1);
        document.getElementById(Id).parentNode.parentNode.className = "NormalRowStyle";
    }
}

function RemoveSelectedId(vProductId, vUpdateConfig) {
    var vSelectedId = "," + document.getElementById(vhndSelectedRowId).value + ",";
    vSelectedId = vSelectedId.replace("," + vProductId + ",", ","); // Removing the Id

    vSelectedId = vSelectedId.replace(/,,/g, ","); // Replacing all ,, ,,, ,,,, etc., to ,
    vSelectedId = vSelectedId.substr(1, vSelectedId.length - 2); // Removing , both the end and assigning
    document.getElementById(vhndSelectedRowId).value = vSelectedId;
}
function AddSelectedId(vProductId, vUpdateConfig) {
    var vSelectedId = "," + document.getElementById(vhndSelectedRowId).value + ",";
    if (vSelectedId.indexOf("," + vProductId + ",") == -1) {
        var vSelectedId = document.getElementById(vhndSelectedRowId).value;
        vSelectedId += "," + vProductId;

        vSelectedId = vSelectedId.replace(/,,/g, ","); // Replacing all ,, ,,, ,,,, etc., to ,
        while (vSelectedId.substring(0, 1) == ",") vSelectedId = vSelectedId.substring(1);

        document.getElementById(vhndSelectedRowId).value = vSelectedId;
    }
}
We have defined some variables which are very much useful for achieving our goal.
Const_LastCol_Index - This variable contains the value of the last column.
vGridViewClientId – This variable contains the client Id of Grid View.
vhndSelectedRowId – This variable contains the unique column value (in this example Product Id)
vIsFooterExist – This variable contains whether the footer exist or not.
vUniqueControlId – This variable contains the control Id of the label which hold the unique column (under TemplateField).
vSelectCheckBoxId – This variable contains the check box Id.

The Style Sheet
body
{
 
}

.NormalRowStyle
{
 background-color:#F7F6F3;
 color:#333333;
}

.SelectedRowStyle
{
 background-color:#F7BE81;
 color:#333333;
}

.InvisibleControl
{
 display:none;
}

.InsertedRowStyle
{
 background-color:#D0F5A9;
 height:20px;
}
The Code behind
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        BindGrid();
        //Assigning the Selected records Ids
        hndSelectedRowId.Value = "2,16,20";
    }
}
/// <summary>
/// Method which binds the data to the Grid
/// </summary>
private void BindGrid()
{
    using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnection"].ConnectionString))
    {

        SqlCommand command = new SqlCommand(
                "SELECT ProductID, ProductName, CompanyName, CategoryName, " +
                "QuantityPerUnit, UnitPrice FROM Products " +
                "JOIN Suppliers ON Products.SupplierID = Suppliers.SupplierID " +
                "JOIN Categories ON Products.CategoryID = Categories.CategoryID ", connection);

        connection.Open();
        SqlDataReader dr = command.ExecuteReader(CommandBehavior.CloseConnection);

        IList<ProductView> productViewList = new List<ProductView>();
        while (dr.Read())
        {
            ProductView productView = new ProductView();
            productView.ProductID = Convert.ToInt32(dr["ProductID"].ToString());
            productView.ProductName = dr["ProductName"].ToString();
            productView.CompanyName = dr["CompanyName"].ToString();
            productView.CategoryName = dr["CategoryName"].ToString();
            productView.QuantityPerUnit = dr["QuantityPerUnit"].ToString();
            productView.UnitPrice = Convert.ToDouble(dr["UnitPrice"].ToString());
            productViewList.Add(productView);
        }
        grdViewProducts.DataSource = productViewList;
        grdViewProducts.DataBind();            }
}

protected void btnProcess_Click(object sender, EventArgs e)
{
    if (grdViewProducts.Rows.Count > 0)
    {
        string strMessage = "<br />Selected Row Id : " + hndSelectedRowId.Value +
                            "<br />The Selected Products Query : <b>Select * From Products Where ProductID IN (" + hndSelectedRowId.Value + ")";
        lblMessage.Text = strMessage;
    }
}

protected void grdViewProducts_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    grdViewProducts.PageIndex = e.NewPageIndex;
    BindGrid();
}

download the working example of the source code in C# here and in VB here.

The screen output of the implementation would be -








0 Responses to “Select All in Multiple Page Grid View (Normal)”

Post a Comment