Solved

Add checkbox to every items in datagrid

Posted on 2006-11-20
4
311 Views
Last Modified: 2008-02-01
how do i add checkbox to every items in datagrid.

And execute a sql statement on every checked items??

i using asp.net 2.0 , vs.net 2005
0
Comment
Question by:kengkit
4 Comments
 
LVL 9

Accepted Solution

by:
kraffay earned 20 total points
ID: 17981073
I did this on a recent project, and I'll just post the C# code and hopefully there's enough info their to help you get a solution.  Basically, I use an ItemTemplate with a checkbox.  The user check the selected items and clicks the submit button, and then I loop through the grid server-side and run some data base code.

I wouldn't worry about the app-specific code in my sample, just try to understand the render of the checkbox and the capture of the checkbox values in th postback:

<%@ Page Language="C#" MasterPageFile="~/MasterUser.master" Title="My Dealers" AutoEventWireup="true"
    CodeFile="AuctionHouseDealers.aspx.cs" Inherits="AuctionHouseDealers" Theme="Auction" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">

    <script type="text/javascript">

        function ChangeCheckBoxState(id, checkState)
        {
            var cb = document.getElementById(id);
            if (cb != null)
               cb.checked = checkState;
        }
       
        function ChangeAllCheckBoxStates(checkState)
        {
       
            // Toggles through all of the checkboxes defined in the CheckBoxIDs array
            // and updates their value to the checkState input parameter

            var link = document.getElementById('ctl00_ContentPlaceHolder1_btnCheckAll');
            if(link.innerHTML == 'Check All')
            {
                link.innerHTML = 'Uncheck All'
            }
           
            else
            {
                link.innerHTML = 'Check All'
                checkState=false;
            }

            if (CheckBoxIDs != null)
            {
                for (var i = 0; i < CheckBoxIDs.length; i++)
                   ChangeCheckBoxState(CheckBoxIDs[i], checkState);
            }
               
           
            return false;
        }
    </script>

    <table style="width: 95%;">
        <tr>
            <td style="width: 100%;">
                <table style="width: 100%;">
                    <tr>
                        <td class="header" colspan="4">
                            My Dealers
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
    <table style="width: 95%;">
        <tr class="commands">
            <td style="width: 100%" align="right">
                <asp:LinkButton CssClass="topNav" ID="btnCheckAll" Visible="false" runat="server" Text="Check All" />
            </td>
        </tr>
        <tr>
            <td style="width: 100%;">
                <asp:GridView CssClass="panel" ID="grdResults" runat="server" AutoGenerateColumns="False"
                    DataSourceID="AuctionHouseDealersDAL" OnRowCommand="grdResults_RowCommand" OnRowDataBound="grdResults_RowDataBound"
                    DataKeyNames="DealerID, ExpirationDate" ShowFooter="True" >
                    <Columns>
                        <asp:ButtonField Text="remove" />
                        <asp:TemplateField HeaderText="Dealer" SortExpression="DLR_NME">
                            <ItemTemplate>
                                <asp:Label ID="Label1" runat="server" Text='<%# Bind("DLR_NME") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Address" SortExpression="CITY_NME">
                            <ItemTemplate>
                                <asp:Label ID="Label2" runat="server" Text='<%# Bind("Address") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField SortExpression="CRD_AVLB_AMT">
                            <HeaderTemplate>
                            Credit Available
                            </HeaderTemplate>
                            <ItemStyle CssClass="inputnumber" />
                            <ItemTemplate>

                                <asp:Label Width="100px" ID="lblReservedAmount" runat="server" Text='<%# Bind("ReservedAmount", "{0:c}") %>'></asp:Label>
                                <asp:CheckBox ID="chkCheckCredit" runat="server" Text="Check Credit" />
                                <asp:Panel ID="pnlBuyers" runat="server" Visible="false"  >
                                <tr>
                                    <td>
                                    &nbsp;
                                    </td>
                                    <td >
                                        <table cellpadding="0", cellspacing="2">
                                            <tr >
                                                <td style="width:100px;">&nbsp;</td>
                                                    <td class="label">Buyers:</td>
                                                    <asp:repeater ID="rptBuyers" runat="server" DataSourceID="DealerBuyersDAL">
                                                        <ItemTemplate>
                                                            <td><a title="Click to Add a New Loan" href='AuctionHouseSale.aspx?DealerID=<%# Eval("DealerID")%>&BuyerID=<%# Eval("BuyerID")%>'>
                                                            <%# Eval("BuyerName")%></a></td>
                                                        </ItemTemplate>
                                                        <SeparatorTemplate>
                                                        <td>,</td>
                                                        </SeparatorTemplate>
                                                    </asp:repeater>
                                                </tr>
                                        </table>
                                    </td>
                                </tr>
                                </asp:Panel>
                               
                                <asp:Panel ID="pnlNoBuyers" runat="server" Visible="false"  >
                                <tr>
                                    <td>
                                    &nbsp;
                                    </td>
                                    <td >
                                        <table cellpadding="0", cellspacing="2">
                                            <tr >
                                                <td style="width:100px;">&nbsp;</td>
                                                    <td class="label">This dealer has no buyers</td>
                                                </tr>
                                        </table>
                                    </td>
                                </tr>
                                </asp:Panel>
                               
                               
                                <asp:ObjectDataSource ID="DealerBuyersDAL" runat="server" OldValuesParameterFormatString="original_{0}"
                                    SelectMethod="GetDataByDealerID" TypeName="BuyerTableAdapters.BuyerTableAdapter"
                                    DeleteMethod="Delete" InsertMethod="Insert" UpdateMethod="Update">
                                    <DeleteParameters>
                                        <asp:Parameter Name="Original_BuyerID" Type="Int32" />
                                    </DeleteParameters>
                                    <UpdateParameters>
                                        <asp:Parameter Name="DealerID" Type="Int32" />
                                        <asp:Parameter Name="BuyerName" Type="String" />
                                        <asp:Parameter Name="Original_BuyerID" Type="Int32" />
                                    </UpdateParameters>
                                    <SelectParameters>
                                        <asp:Parameter Name="DealerID" DefaultValue="2" Type="Int32" />
                                    </SelectParameters>
                                    <InsertParameters>
                                        <asp:Parameter Name="DealerID" Type="Int32" />
                                        <asp:Parameter Name="BuyerName" Type="String" />
                                    </InsertParameters>
                                </asp:ObjectDataSource>
                            </ItemTemplate>
                            <FooterStyle HorizontalAlign="Right" />
                            <FooterTemplate>
                            <asp:Label CssClass="inputnumber" ID="lblTotalCredit" runat="server" />
                            </FooterTemplate>
                            <HeaderStyle HorizontalAlign="Right" />
                           
                        </asp:TemplateField>
                       
                    </Columns>
                    <EmptyDataTemplate>
                        <td>No Dealers found.  Click <a href="AuctionHouseDealerSearch.aspx">here</a> to add Dealers</td>
                    </EmptyDataTemplate>
                    <FooterStyle CssClass="footer" />
                    <EmptyDataRowStyle CssClass="empty" />
                    <RowStyle CssClass="display" />
                    <EditRowStyle CssClass="editing" />
                    <PagerStyle CssClass="pager" />
                    <HeaderStyle CssClass="header" />
                    <AlternatingRowStyle  CssClass="alternate" />
                   
                </asp:GridView>
                &nbsp; &nbsp;
            </td>
        </tr>
        <tr>
            <td align="right">
                <asp:Button runat="server" Width="95px" ID="btnCheckCredit" Visible="false" Text="Check Credit" OnClick="btnCheckCredit_Click" CssClass="commands" />
            </td>
        </tr>
    </table>
    <asp:ObjectDataSource ID="AuctionHouseDealersDAL" runat="server" OldValuesParameterFormatString="original_{0}"
        SelectMethod="GetDataByReservedAmount" TypeName="AuctionHouseDealersTableAdapters.AuctionHouseDealersTableAdapter">
        <SelectParameters>
            <asp:Parameter Name="AuctionHouseID" Type="Int32" />
        </SelectParameters>
    </asp:ObjectDataSource>
</asp:Content>

-------------------------------------------------------------------------------------------------------------------------------------------------------------------

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using FlexFund.LoanPro;
using System.Collections.Generic;

public partial class AuctionHouseDealers : UserPageBase
{
    private decimal _grandTotal;
    private int _auctionHouseID;
    private int _validDealerCount;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            this.AuctionHouseDealersDAL.Selecting += new ObjectDataSourceSelectingEventHandler(AuctionHouseDealersDAL_Selecting);
            this.btnCheckAll.Attributes.Add("onclick", "ChangeAllCheckBoxStates(true);return false");

            if (this.Request.QueryString["mode"] != null)
            {
                this.RegisterClientScriptBlock("confirm", "<script>alert('Record Saved!');</script>");
            }
        }
    }
   
    /// <summary>
    /// format the input params for the DAL
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void AuctionHouseDealersDAL_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
    {

        this._auctionHouseID = this.SecurityUser.AuctionHouseID;

        // filter dealer results on the logged in user auction house ID
        e.InputParameters["AuctionHouseID"] = this._auctionHouseID;

       
    }


    #region "Grid Events"

    /// <summary>
    /// As the grid is being generated, figure out whether to show the check credit box and the buyers
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void grdResults_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //-- get reference the Remove Dealer LinkButton and add client side code
            LinkButton btnRemoveDealer = (LinkButton)e.Row.Cells[0].Controls[0];
            btnRemoveDealer.OnClientClick = "return confirm('Are you certain you want to remove this dealer?');";

            //-- show the buyers repeater if there are any
            int rowIndex = e.Row.RowIndex;

            //-- grab a handle to the repeater that is nested in the grid
            Repeater rptBuyers = (Repeater)e.Row.FindControl("rptBuyers");
            Panel pnlBuyers = (Panel)e.Row.FindControl("pnlBuyers");
            Panel pnlNoBuyers = (Panel)e.Row.FindControl("pnlNoBuyers");

            bool hasBuyers=false;

            if (rptBuyers != null)
            {

                ObjectDataSource DealerBuyersDAL = (ObjectDataSource)e.Row.FindControl("DealerBuyersDAL");
                DealerBuyersDAL.SelectParameters["DealerID"].DefaultValue = grdResults.DataKeys[rowIndex][0].ToString();
                rptBuyers.DataBind();

                //-- set the flag
                hasBuyers = (rptBuyers.Items.Count > 0);

                //-- if we have records, show the buyers repeater
                pnlBuyers.Visible = hasBuyers;
                pnlNoBuyers.Visible = !hasBuyers;
            }

            //-- render ReservedAmount or Check Credit
            CheckBox chkCheckCredit = (System.Web.UI.WebControls.CheckBox)(e.Row.FindControl("chkCheckCredit"));
            Label lblReservedAmount = (System.Web.UI.WebControls.Label)(e.Row.FindControl("lblReservedAmount"));

            //-- check for Avail Credit and display check box if Credit Avail is 0 or if the record is expired
            Decimal CreditAvail=0;
            if (lblReservedAmount.Text.Length > 0)
            {
                CreditAvail = Decimal.Parse(lblReservedAmount.Text.ToString(), System.Globalization.NumberStyles.Any);
            }

            bool CheckCredit = (CreditAvail == 0);

            //-- we need to know if the credit reserved has expired
            DateTime expirationDate = this.getExpirationDate(e.Row.RowIndex);

            //-- only show check credit or credit reserved if there are buyers
            if (hasBuyers)
            {
                if (CheckCredit || expirationDate <= DateTime.Now)
                {
                    //-- no credit reserved, show the check box
                    lblReservedAmount.Visible = false;
                    chkCheckCredit.Visible = true;

                    //-- add the check all code
                    ClientScript.RegisterArrayDeclaration("CheckBoxIDs",
                        string.Concat("'", chkCheckCredit.ClientID, "'"));

                    _validDealerCount++;

                }
                else
                {
                    //-- credit has been reserved
                    lblReservedAmount.Visible = true;
                    chkCheckCredit.Visible = false;
                    _grandTotal += CreditAvail;

                }
            }
            else
            {
                //-- no buyers, show nada
                lblReservedAmount.Visible = false;
                chkCheckCredit.Visible = false;
            }

           
        }
        else if (e.Row.RowType == DataControlRowType.Footer)
        {

            //-- if we got here, we have rows, so show the check credit links
            //-- only if there are any dealers that can have credit checked (they have buyers and no credit reserved)
            if (_validDealerCount > 0)
            {
                this.btnCheckAll.Visible = true;
                this.btnCheckCredit.Visible = true;
            }

            //-- render the grand total in the grid footer
            Label lblTotalCredit = (System.Web.UI.WebControls.Label)(e.Row.FindControl("lblTotalCredit"));
            lblTotalCredit.Text = this._grandTotal.ToString("C2");
            lblTotalCredit.Text = "Total:   " + lblTotalCredit.Text;

        }

    }


    protected void grdResults_RowCommand(Object sender, GridViewCommandEventArgs e)
    {

        int index = Convert.ToInt32(e.CommandArgument);

        GridViewRow row = grdResults.Rows[index];

        //TODO - render confirmation and refresh
        if (deleteDealerAuctionHouseRow(index))
        {

            //refresh the grid
            this.AuctionHouseDealersDAL.Selecting += new ObjectDataSourceSelectingEventHandler(AuctionHouseDealersDAL_Selecting);
            this.AuctionHouseDealersDAL.Select();
            this.grdResults.DataBind();
        }

    }

    #endregion
    /// <summary>
    /// inserts a row into the DealerAuctionHouse Table
    /// </summary>
    /// <returns>true if update succeeds</returns>
    bool deleteDealerAuctionHouseRow(int rowIndex)
    {
        try
        {

            //pick up the dealerID from the DataKeys Selection
            int dealerID = getDealerID(rowIndex);
            this._auctionHouseID = this.SecurityUser.AuctionHouseID;

            DealerTableAdapters.DealerAuctionHouseTableAdapter
                dealerAuctionHouseTA = new DealerTableAdapters.DealerAuctionHouseTableAdapter();

            //delete a record for this dealerID/auctionHouseID combo
            dealerAuctionHouseTA.Delete(dealerID, this._auctionHouseID);

            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }

    /// <summary>
    /// loop though the grid rows and run a credit check for each check box selected
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnCheckCredit_Click(object sender, EventArgs e)
    {
       
        this._auctionHouseID = this.SecurityUser.AuctionHouseID;
       
        foreach (GridViewRow gvr in this.grdResults.Rows)
        {
            if (gvr.RowType == DataControlRowType.DataRow)
            {
                CheckBox chkCheckCredit = (System.Web.UI.WebControls.CheckBox)
                                            (gvr.FindControl("chkCheckCredit"));

                if (chkCheckCredit.Checked)
                {
                    int dealerID = getDealerID(gvr.RowIndex);
                    checkCredit(dealerID);
                }
            }
        }

        this.AuctionHouseDealersDAL.SelectParameters["AuctionHouseID"].DefaultValue = this._auctionHouseID.ToString();
        this.AuctionHouseDealersDAL.Select();
        this.grdResults.DataBind();

       
    }

    /// <summary>
    /// run credit check for a dealer id
    /// </summary>
    /// <param name="dealerId"></param>
    /// <returns></returns>
    bool checkCredit(int dealerId)
    {
        //TODO - figure out what happens here
        try
        {

            Credit objCredit = new Credit(dealerId, this._auctionHouseID);
            objCredit.ReserveCredit();

            return true;

        }
        catch (Exception ex)
        {
            return false;
        }
    }

    /// <summary>
    /// extract the dealer ID from the row data source
    /// </summary>
    /// <param name="?"></param>
    /// <returns></returns>
    int getDealerID(int rowIndex)
    {

        DataKey data = this.grdResults.DataKeys[rowIndex];
        int dealerID = (int)data.Values["DealerID"];
        return dealerID;

    }

    /// <summary>
    /// extract the expiration date from the row data source
    /// </summary>
    /// <param name="?"></param>
    /// <returns></returns>
    DateTime getExpirationDate(int rowIndex)
    {

        DataKey data = this.grdResults.DataKeys[rowIndex];

        DateTime expirationDate;

        if (data.Values["ExpirationDate"].ToString() == string.Empty)
        {
            expirationDate = DateTime.Now.AddDays(-1);
        }
        // -- send back an expired date if no record exists in DealerAuctionReserve
        else
        {
            expirationDate = (DateTime)data.Values["ExpirationDate"];
        }

        return expirationDate;

    }
}
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I recently went through the process of creating a Calendar Control of events with the basis of using a database to keep track of the dates that are selectable, one requirement was to have the selected date pop-up in a simple lightbox.  At first this…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

825 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