• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 314
  • Last Modified:

Evaluating a checkbox within a datagrid without using a " if(!IsPostBack)" block

Hello.

I am trying to find which rows in a datagrid, a user has selected. I'm using code sample from this page:
http://support.microsoft.com/default.aspx?scid=kb;en-us;Q320707

Step # 6 of the instructions indicate to put the database call in the PageLoad  " if(!IsPostBack)"  block. However,
I can not do that because I first display a form from with textboxes so the user can select some criteria to filter
the inital database lookup. The form sends parameters to a stored procedure and the filtered data
is put into the datagrid. The datagrid also contains a checkbox as the first column. I want to be
able to find out which checkboxes the user selected.

Since I didn't put the database code in the !IsPostback I can not check which checkboxes were selected.

The error I'm getting is:
--------------------------------------------------------------------------------------------------------------------------------
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

Line 144:      rowCount++;
Line 145:      gridSelections.AppendFormat("The checkbox for {0} was selected<br>",
Line 146:      dgCustomFindResults.DataKeys[DemoGridItem.ItemIndex].ToString());

Source File: c:\inetpub\wwwroot\mls2\index.aspx.cs    Line: 145
---------------------------------------------------------------------------------------------------------------------------------

How would one go about finding out which checkboxes were selected in a datagrid without using the IsPostBack block?

Any help would be greatly appreciated.


Here is some code:

//    index.aspx
//    =================================================================
<%@ Page language="c#" Codebehind="index.aspx.cs" AutoEventWireup="false" Inherits="MLS2.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
      <HEAD>
            <title>WebForm1</title>
            <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
            <meta name="CODE_LANGUAGE" Content="C#">
            <meta name="vs_defaultClientScript" content="JavaScript">
            <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
      </HEAD>
      <body>
            <form id="frmMLS" name="frmMLS" method="post" runat="server">
                  <div align="center">MLS Reports</div>
                  <table id="tblMain" style="MARGIN-LEFT: 8px" cellSpacing="0" cellPadding="0" width="100%"
                        border="0">
                        <tr>
                              <td style="WIDTH: 137px; HEIGHT: 19px">Street Number</td>
                              <td style="WIDTH: 143px; HEIGHT: 19px">Street Name</td>
                              <td style="WIDTH: 117px; HEIGHT: 19px">&nbsp;</td>
                              <td style="WIDTH: 114px; HEIGHT: 19px">&nbsp;</td>
                              <td style="WIDTH: 117px; HEIGHT: 19px">&nbsp;</td>
                              <td style="HEIGHT: 19px">&nbsp;</td>
                              <td style="HEIGHT: 19px">&nbsp;</td>
                              <td style="HEIGHT: 19px">&nbsp;</td>
                        </tr>
                        <tr>
                              <td style="WIDTH: 137px">
                                    <asp:TextBox id="txtStreetNumber" runat="server" Width="96px"></asp:TextBox></td>
                              <td style="WIDTH: 260px" colspan="2">
                                    <asp:TextBox id="txtStreetName" runat="server" Width="232px"></asp:TextBox></td>
                              <td style="WIDTH: 114px"></td>
                              <td style="WIDTH: 117px"></td>
                              <td>&nbsp;</td>
                              <td>&nbsp;</td>
                              <td>&nbsp;</td>
                        </tr>
                        <tr>
                              <td>Nhbrhood Code</td>
                              <td>Group</td>
                              <td style="WIDTH: 117px">Yr. Built</td>
                              <td style="WIDTH: 114px">Grade</td>
                              <td style="WIDTH: 117px">CDU</td>
                              <td>Gross Sale Price</td>
                              <td>Price PSF</td>
                              <td>&nbsp;</td>
                        </tr>
                        <tr>
                              <td style="HEIGHT: 23px">
                                    <asp:TextBox id="txtNeighborhoodCode" runat="server" Width="96px"></asp:TextBox></td>
                              <td style="HEIGHT: 23px">
                                    <asp:TextBox id="txtGroup" runat="server" Width="96px"></asp:TextBox></td>
                              <td style="WIDTH: 117px; HEIGHT: 23px">
                                    <asp:TextBox id="txtYearBuilt" runat="server" Width="96px"></asp:TextBox></td>
                              <td style="WIDTH: 114px; HEIGHT: 23px">
                                    <asp:TextBox id="txtGrade" runat="server" Width="96px"></asp:TextBox></td>
                              <td style="WIDTH: 117px; HEIGHT: 23px">
                                    <asp:TextBox id="txtCDU" runat="server" Width="96px"></asp:TextBox></td>
                              <td style="HEIGHT: 23px">
                                    <asp:TextBox id="txtGrossSalePrice" runat="server" Width="128px"></asp:TextBox></td>
                              <td style="HEIGHT: 23px">
                                    <asp:TextBox id="txtPricePSF" runat="server" Width="119px"></asp:TextBox></td>
                              <td style="HEIGHT: 23px">&nbsp;</td>
                        </tr>
                        <tr>
                              <td style="HEIGHT: 37px">Price PSF Imp</td>
                              <td style="HEIGHT: 37px">House SF</td>
                              <td style="WIDTH: 117px; HEIGHT: 37px">Year Remodled</td>
                              <td style="WIDTH: 114px; HEIGHT: 37px">Remodel Type</td>
                              <td style="WIDTH: 117px; HEIGHT: 37px">Sale Date</td>
                              <td style="HEIGHT: 37px">Key Map Page</td>
                              <td style="HEIGHT: 37px">Assessment Ratio</td>
                              <td style="HEIGHT: 37px">&nbsp;</td>
                        </tr>
                        <tr>
                              <td>
                                    <asp:TextBox id="txtPricePSFImp" runat="server" Width="120px"></asp:TextBox></td>
                              <td>
                                    <asp:TextBox id="txtHouseSF" runat="server" Width="96px"></asp:TextBox></td>
                              <td style="WIDTH: 117px">
                                    <asp:TextBox id="txtYearRemodled" runat="server" Width="96px"></asp:TextBox></td>
                              <td style="WIDTH: 114px">
                                    <asp:TextBox id="txtRemodelType" runat="server" Width="96px"></asp:TextBox></td>
                              <td style="WIDTH: 117px">
                                    <asp:TextBox id="txtSaleDate" runat="server" Width="96px"></asp:TextBox></td>
                              <td>
                                    <asp:TextBox id="txtKeyMapPage" runat="server" Width="96px"></asp:TextBox></td>
                              <td>
                                    <asp:TextBox id="txtAssessmentRatio" runat="server" Width="103px"></asp:TextBox></td>
                              <td></td>
                        </tr>
                        <tr>
                              <td colspan="8">
                                    <asp:Button id="cmdCustomFind" runat="server" Text="Custom Find"></asp:Button></td>
                        </tr>
                        <tr>
                              <td colspan="8"><br>
                                    <div style="VERTICAL-ALIGN: top; OVERFLOW: auto; WIDTH: 100%; HEIGHT: 300px">
                                          <asp:DataGrid id="dgCustomFindResults" AutoGenerateColumns="True" ShowHeader="True"
                                                Font-Name="Arial" Font-Size="8pt" HorizontalAlign="Left" runat="server">
                                                <Columns>
                                                      <asp:TemplateColumn HeaderText="">
                                                            <ItemTemplate>
                                                                  <asp:CheckBox ID="myCheckbox" Runat="server" />
                                                            </ItemTemplate>
                                                      </asp:TemplateColumn>
                                                </Columns>
                                          </asp:DataGrid>
                                    </div>
                              </td>
                        </tr>
                        <tr>
                              <td colspan="8">
                                    <asp:Label id="lblResultsInfo" runat="server"></asp:Label>
                              </td>
                        </tr>
                        <tr>
                              <td colspan="8">
                                    <asp:Button id="cmdPrintSales" runat="server" Text="Print Sales" Visible="False"></asp:Button>
                                    <asp:Button id="cmdPrintRatioStudy" runat="server" Text="Print Ratio Study" Visible="False"></asp:Button>
                                    <asp:Button id="cmdGetSelections" runat="server" Text="Get Selections"></asp:Button></td>
                        </tr>
                  </table>
            </form>
      </body>
</HTML>





//    index.aspx.cs
//    ===========================================================

using System.Data.SqlClient;
using System.Configuration;

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text;

namespace MLS2
{
      /// <summary>
      /// Summary description for WebForm1.
      /// </summary>
      public class WebForm1 : System.Web.UI.Page
      {
            protected System.Web.UI.WebControls.TextBox txtStreetNumber;
            protected System.Web.UI.WebControls.TextBox txtStreetName;
            protected System.Web.UI.WebControls.TextBox txtNeighborhoodCode;
            protected System.Web.UI.WebControls.TextBox txtGroup;
            protected System.Web.UI.WebControls.TextBox txtYearBuilt;
            protected System.Web.UI.WebControls.TextBox txtGrade;
            protected System.Web.UI.WebControls.TextBox txtCDU;
            protected System.Web.UI.WebControls.TextBox txtGrossSalePrice;
            protected System.Web.UI.WebControls.TextBox txtPricePSF;
            protected System.Web.UI.WebControls.TextBox txtPricePSFImp;
            protected System.Web.UI.WebControls.TextBox txtHouseSF;
            protected System.Web.UI.WebControls.TextBox txtYearRemodled;
            protected System.Web.UI.WebControls.TextBox txtRemodelType;
            protected System.Web.UI.WebControls.TextBox txtSaleDate;
            protected System.Web.UI.WebControls.TextBox txtKeyMapPage;
            protected System.Web.UI.WebControls.Button cmdCustomFind;
            protected System.Web.UI.WebControls.Button cmdPrintSales;
            protected System.Web.UI.WebControls.Button cmdPrintRatioStudy;
            protected System.Web.UI.WebControls.DataGrid dgCustomFindResults;
            protected System.Web.UI.WebControls.Button selBtn;
            protected System.Web.UI.WebControls.Label lblResultsInfo;
            protected System.Web.UI.WebControls.Button cmdGetSelections;
            protected System.Web.UI.WebControls.TextBox txtAssessmentRatio;


      
            private void Page_Load(object sender, System.EventArgs e)
            {

            }

            #region Web Form Designer generated code
            override protected void OnInit(EventArgs e)
            {
                  //
                  // CODEGEN: This call is required by the ASP.NET Web Form Designer.
                  //
                  InitializeComponent();
                  base.OnInit(e);
            }
            
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {    
                  this.txtNeighborhoodCode.TextChanged += new System.EventHandler(this.txtNeighborhoodCode_TextChanged);
                  this.cmdCustomFind.Click += new System.EventHandler(this.CustomFindEngage);
                  this.cmdGetSelections.Click += new System.EventHandler(this.GetSelectionsEngage);
                  this.Load += new System.EventHandler(this.Page_Load);

            }
            #endregion

            private void txtNeighborhoodCode_TextChanged(object sender, System.EventArgs e)
            {
            
            }



            private void CustomFindEngage(object sender, System.EventArgs e)
            {
            
                  
                        string strStreetNum = txtStreetNumber.Text.ToString();
                        string strStreetName = txtStreetName.Text.ToString();
                        string strKeymapPage = txtKeyMapPage.Text.ToString();
                        string strNeighborhoodCode = txtNeighborhoodCode.Text.ToString();
                        string intYearBuilt = txtYearBuilt.Text.ToString();
            

                        string CONN = ConfigurationSettings.AppSettings["DB_CONN"];
                        SqlConnection connObj = new SqlConnection(CONN);
                        SqlCommand cmdObj = new SqlCommand("MLS_GetData", connObj);
                        cmdObj.CommandType = CommandType.StoredProcedure;

                        if (txtStreetNumber.Text != "")
                        {
                              cmdObj.Parameters.Add(new SqlParameter("@strStreetNum", strStreetNum));
                        }
                        if (txtStreetName.Text != "")
                        {
                              cmdObj.Parameters.Add(new SqlParameter("@strStreetName", strStreetName));
                        }
                        if (txtKeyMapPage.Text != "")
                        {
                              cmdObj.Parameters.Add(new SqlParameter("@strKeymapPage", strKeymapPage));
                        }
                        if (txtNeighborhoodCode.Text != "")
                        {
                              cmdObj.Parameters.Add(new SqlParameter("@strNeighborhoodCode", strNeighborhoodCode));
                        }
                        if (txtYearBuilt.Text != "")
                        {
                              cmdObj.Parameters.Add(new SqlParameter("@intYearBuilt", intYearBuilt));
                        }
                              

                        SqlDataAdapter da = new SqlDataAdapter ( cmdObj ) ;
                        DataSet dsMLS = new DataSet("MLS");
                        da.SelectCommand.CommandTimeout = 0;
                        da.Fill(dsMLS, "MLS");
                        dgCustomFindResults.DataSource =  dsMLS.Tables["MLS"].DefaultView;
                        dgCustomFindResults.DataBind();

            
            }

            private void GetSelectionsEngage(object sender, System.EventArgs e)
            {
                  int rowCount = 0;
                  StringBuilder gridSelections = new StringBuilder();

                  //Loop through each DataGridItem, and determine which CheckBox controls have been selected.
                  foreach(DataGridItem DemoGridItem in dgCustomFindResults.Items)
                  {
                        CheckBox myCheckbox = (CheckBox)DemoGridItem.Cells[0].Controls[1];
                        if(myCheckbox.Checked == true)
                        {
                              rowCount++;
                              gridSelections.AppendFormat("The checkbox for {0} was selected<br>",
                                    dgCustomFindResults.DataKeys[DemoGridItem.ItemIndex].ToString());
                        }
                  }
                  gridSelections.Append("<hr>");

                  gridSelections.AppendFormat("Total number selected is: {0}", rowCount.ToString());
                  lblResultsInfo.Text = gridSelections.ToString();
            }



      }
}


 
0
FastEddie___
Asked:
FastEddie___
1 Solution
 
nguyenvinhtuCommented:
I have had a look at this page. They called Stored Procedure in Postback event to make sure that in the grid, there should be some data already incase you loop through the checkbox.
http://support.microsoft.com/default.aspx?scid=kb;en-us;Q320707
About your code:
Your put Stored Procedure call into this function "CustomFindEngage". However, did you make sure CustomFindEngage be called to get some data into grid before GetSelectionsEngage called, otherwise, you may get "Index was out of range".
We can try one of the following:
1 - You should disabled the function GetSelectionsEngage when there is no data in grid.
or
2-  If(DemoGridItem.Items.Count > 0)
     {
               int rowCount = 0;
               StringBuilder gridSelections = new StringBuilder();

               //Loop through each DataGridItem, and determine which CheckBox controls have been selected.
               foreach(DataGridItem DemoGridItem in dgCustomFindResults.Items)
               {
                    CheckBox myCheckbox = (CheckBox)DemoGridItem.Cells[0].Controls[1];
                    if(myCheckbox.Checked == true)
                    {
                         rowCount++;
                         gridSelections.AppendFormat("The checkbox for {0} was selected<br>",
                              dgCustomFindResults.DataKeys[DemoGridItem.ItemIndex].ToString());
                    }
               }
               gridSelections.Append("<hr>");

               gridSelections.AppendFormat("Total number selected is: {0}", rowCount.ToString());
               lblResultsInfo.Text = gridSelections.ToString();
      }
0
 
FastEddie___Author Commented:
Hello nguyenvinhtu.

Thanks for your quick response but the link that you gave me is somthing I already looked at.
In fact, I put the exact same URL reference in my question.
Perhaps I didn't expain it very well but what I need is a solution that does not use the IsPostBack block.

Here is the situation:

When the user comes to the page they are presented with a form with several textboxes.
The user can choose to fill in any the textboxes or leave them blank.
The user presses a button and the results are displayed in the datagrid.
The datagrid contains checkboxes in the very first column.
The user may choose to keep modifying the results by entering different criteria from the textboxes OR the user may select multiple rows by using the checkboxes.
If the user selects multiple checkboxes they can then press another button to display which items they have selected.

The problem is that because I have a form that is used to change the results of the datagrid I am constantly making post calls.
That means I can NOT use the IsPostBack block because a user may continue to filter the data as they please in essesence there will always be a postback. Also, when I write the code to find which textboxes are selected I can not process the code because it is making another post and the data (selected items) are wiped out.

So what I need is a way to keep updating the datagrid but also find out which rows the user selected.

It seem like a simple thing but I just can't figure out how to do that.

Thanks again for your input.

-Eddie




0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now