gthendry
asked on
Index was out of range. Must be non-negative and less than the size of the collection.
Hi Experts,
I am having the following error in my code... there is a gridview and each row on it has a "delete" button which executes the following code:
protected void GridView_userList_Selected IndexChang ed(object sender, EventArgs e)
{
// Get User_ID of selected row
int nRecipUser_ID = Convert.ToInt16(((Label)Gr idView_use rList.Sele ctedRow.Fi ndControl( "lblRecipU ser_ID")). Text);
// Remove user from nomination
RecipientManager.recipient _DeleteFro mOrder(nRe cipUser_ID , SessionManager.Instance.nN omination_ ID);
}
This works fine when deleting items from the gridview except the very last item, which causes an error:
Index was out of range. Must be non-negative and less than the size of the collection.
The highlighted line error is:
Line 103: int nRecipUser_ID = Convert.ToInt16(((Label)Gr idView_use rList.Sele ctedRow.Fi ndControl( "lblRecipU ser_ID")). Text);
Any ideas?!
Thanks,
Anthony
I am having the following error in my code... there is a gridview and each row on it has a "delete" button which executes the following code:
protected void GridView_userList_Selected
{
// Get User_ID of selected row
int nRecipUser_ID = Convert.ToInt16(((Label)Gr
// Remove user from nomination
RecipientManager.recipient
}
This works fine when deleting items from the gridview except the very last item, which causes an error:
Index was out of range. Must be non-negative and less than the size of the collection.
The highlighted line error is:
Line 103: int nRecipUser_ID = Convert.ToInt16(((Label)Gr
Any ideas?!
Thanks,
Anthony
ASKER
Hi,
I'm sure it is correct because the ID it is retrieving is the text value of the label control which in turn is the ID of the database record, not the id of the row.
But I did find a mistake... I was choosing the nRecipUser_ID which was not the primary key for the Recipients table where my data is coming from for this gridview... I have now changed it to nRecipient_ID which is the primary key but I'm still having the same problem but also another problem. When I click the select button on the first gridview (gridview_SearchResults), I am not seeing the user appear in my 2nd gridview (GridView_userList) UNLESS I click TWICE on the "select" button in the first gridview.
Just to explain what this page is supposed to do...
1) User enters some search values into textboxes, then the search results appear in a gridview. Each row in that gridview has a select button.
2) When the select button is clicked, the page checks if there is an order session. If yes, then the recipient is added to the recipients table in database along with the existing order ID (in session)
3) If the order ID does not exist in session, then a new order is created and the order id is stored in a session. Then the recipient is added to this order as above.
4) Each time the page is loaded, the page checks to see if there is an existing order session ID. If there is, then the 2nd gridview is displayed (this one retrieves any recipients that have been added to this order). Each row in this gridview has a Delete button next to it, which when clicked, should remove the recipient from the recipients table in the database.
Here is all my code for this page:
I'm sure it is correct because the ID it is retrieving is the text value of the label control which in turn is the ID of the database record, not the id of the row.
But I did find a mistake... I was choosing the nRecipUser_ID which was not the primary key for the Recipients table where my data is coming from for this gridview... I have now changed it to nRecipient_ID which is the primary key but I'm still having the same problem but also another problem. When I click the select button on the first gridview (gridview_SearchResults), I am not seeing the user appear in my 2nd gridview (GridView_userList) UNLESS I click TWICE on the "select" button in the first gridview.
Just to explain what this page is supposed to do...
1) User enters some search values into textboxes, then the search results appear in a gridview. Each row in that gridview has a select button.
2) When the select button is clicked, the page checks if there is an order session. If yes, then the recipient is added to the recipients table in database along with the existing order ID (in session)
3) If the order ID does not exist in session, then a new order is created and the order id is stored in a session. Then the recipient is added to this order as above.
4) Each time the page is loaded, the page checks to see if there is an existing order session ID. If there is, then the 2nd gridview is displayed (this one retrieves any recipients that have been added to this order). Each row in this gridview has a Delete button next to it, which when clicked, should remove the recipient from the recipients table in the database.
Here is all my code for this page:
<%@ Page Language="C#" MasterPageFile="~/Pages/MasterPage.master" AutoEventWireup="true"
CodeFile="search.aspx.cs" Inherits="Pages_nominate_search" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="mainContent" runat="Server">
<div>
<div id="contentWrap">
<div id="colOne">
<div id="subNav">
</div>
</div>
<div id="colTwo">
<div id="titleArea2">
<img src="../../Assets/images/titles/nominate_chooserecipient.gif" alt="Choose a recipient" /></div>
<div id="textArea_wide">
<h1>
New Search</h1>
<p>
Enter the first or last name of the person you would like to nominate, choose whether
they are Team or Individual nominees and click <b>Search</b></p>
<p>
Partial entry will return wider results - e.g. entering just the first letter of
a surname will return all people with surnames beginning with that letter. You can
also filter on Business Unit, using the drop-down box provided.</p>
<table border="0" cellspacing="0" cellpadding="10" class="table1">
<tr>
<td>
<table cellspacing="0" cellpadding="4" border="0">
<tr>
<td>
<b>Type of Nominees</b>
</td>
<td>
<asp:RadioButton ID="radIndividual" GroupName="RecipientType" runat="server" Checked="true" />
Individual
<asp:RadioButton ID="radTeam" GroupName="RecipientType" runat="server" />
Team
</td>
</tr>
<tr>
<td>
<b>Preferred Name</b>
</td>
<td>
<asp:TextBox ID="txtForename" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<b>Last Name</b>
</td>
<td>
<asp:TextBox ID="txtSurname" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<b>Business Unit</b>
</td>
<td>
<asp:DropDownList ID="ddlBusinessUnit" runat="server">
</asp:DropDownList>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btnSearch" runat="server" OnClick="btnSearch_Click" Text="Search" />
</td>
</tr>
</table>
</td>
</tr>
</table>
<br />
<asp:Panel ID="panel_SearchResults" runat="server" Visible="False">
<asp:GridView ID="GridView_SearchResults" runat="server" AutoGenerateColumns="False"
DataSourceID="objdatasource_usersearch" HeaderStyle-CssClass="hc" CssClass="table2"
HeaderStyle-HorizontalAlign="Left" OnSelectedIndexChanged="GridView_SearchResults_SelectedIndexChanged">
<Columns>
<asp:TemplateField HeaderText="nUser_ID" Visible="false">
<ItemTemplate>
<asp:Label ID="lblUser_ID" runat="server" Text='<%#Eval("nUser_ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" HeaderStyle-Width="200">
<ItemTemplate>
<%# Eval("sForename") %>
<%# Eval("sSurname") %>
</ItemTemplate>
<HeaderStyle Width="200px" />
</asp:TemplateField>
<asp:BoundField DataField="sUserfield1" HeaderText="Business Unit" SortExpression="sUserfield1" />
<asp:BoundField DataField="sEmail" HeaderText="Email" SortExpression="sEmail" />
<asp:CommandField HeaderText="" ShowSelectButton="True" ButtonType="Button" />
</Columns>
<HeaderStyle CssClass="hc" />
</asp:GridView>
</asp:Panel>
<asp:ObjectDataSource ID="objdatasource_usersearch" runat="server" DataObjectTypeName="DES.Quantum.BO.Employee"
OldValuesParameterFormatString="original_{0}" SelectMethod="GetUserList" TypeName="DES.Quantum.BLL.EmployeeManager">
<SelectParameters>
<asp:ControlParameter ControlID="txtForename" Name="sForename" Type="String" DefaultValue="" />
<asp:ControlParameter ControlID="txtSurname" Name="sSurname" Type="String" DefaultValue="" />
<asp:ControlParameter ControlID="ddlBusinessUnit" Name="sBusinessUnit" Type="String"
DefaultValue="" />
</SelectParameters>
</asp:ObjectDataSource>
<br />
<asp:Panel ID="Panel_userList" runat="server" Visible="False">
</asp:Panel>
<br />
<asp:ObjectDataSource ID="objdatasource_userList" runat="server" DataObjectTypeName="DES.Quantum.BO.Recipient"
OldValuesParameterFormatString="original_{0}" SelectMethod="GetRecipientList" TypeName="DES.Quantum.BLL.RecipientManager">
<SelectParameters>
<asp:Parameter Name="nOrder_ID" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:GridView ID="GridView_userList" runat="server" AutoGenerateColumns="False" DataSourceID="objdatasource_userList"
HeaderStyle-CssClass="hc" CssClass="table2" OnSelectedIndexChanged="GridView_userList_SelectedIndexChanged">
<Columns>
<asp:TemplateField HeaderText="nRecipient_ID" Visible="false">
<ItemTemplate>
<asp:Label ID="lblRecipient_ID" runat="server" Text='<%#Eval("nRecipient_ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" HeaderStyle-Width="200">
<ItemTemplate>
<%# Eval("sForename") %>
<%# Eval("sSurname") %>
</ItemTemplate>
<HeaderStyle Width="200px" />
</asp:TemplateField>
<asp:BoundField DataField="sUserfield1" HeaderText="Business Unit" SortExpression="sUserfield1" />
<asp:BoundField DataField="sEmail" HeaderText="Email" SortExpression="sEmail" />
<asp:CommandField HeaderText="" ShowSelectButton="True" ButtonType="Button" SelectText="Remove" />
</Columns>
<HeaderStyle CssClass="hc"></HeaderStyle>
</asp:GridView>
</div>
</div>
</div>
<br clear="all" />
</div>
</asp:Content>
======== CODE BEHIND =============
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using DES.Quantum.BO;
using DES.Quantum.BLL;
public partial class Pages_nominate_search : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Bind drop down for business units
if (!IsPostBack)
{
loadBusinessUnits();
}
// Bind Datagrid to show current users in nomination
if (SessionManager.Instance.nNomination_ID != 0)
{
Panel_userList.Visible = true;
objdatasource_userList.SelectParameters.Clear();
objdatasource_userList.SelectParameters.Add("nOrder_ID", SessionManager.Instance.nNomination_ID.ToString());
GridView_userList.DataBind();
}
}
protected void loadBusinessUnits()
{
DataSet ds = NominationManager.GetBusinessUnits();
ddlBusinessUnit.DataSource = ds;
ddlBusinessUnit.DataTextField = "sUserfield1";
ddlBusinessUnit.DataValueField = "sUserfield1";
ddlBusinessUnit.DataBind();
ListItem item = new ListItem();
item.Value = "";
item.Text = "Please select...";
ddlBusinessUnit.Items.Insert(0, item);
}
protected void btnSearch_Click(object sender, EventArgs e)
{
panel_SearchResults.Visible = true;
//GridView_SearchResults.DataSource = objdatasource_usersearch;
GridView_SearchResults.DataBind();
}
protected void GridView_SearchResults_SelectedIndexChanged(object sender, EventArgs e)
{
// Get User_ID of selected row
int nUser_ID = Convert.ToInt16(((Label)GridView_SearchResults.SelectedRow.FindControl("lblUser_ID")).Text);
//Check if nomination exists, if not, then create new nomination
if (SessionManager.Instance.nNomination_ID == 0)
{
// Create new nomination
int nNomination_ID = NominationManager.InsertNomination(SessionManager.Instance.nUser_ID);
Nomination myNomination = NominationManager.GetNomination(nNomination_ID);
//Save nomination ID in Session
SessionManager.Instance.nNomination_ID = myNomination.nOrder_ID;
//Add Recipient To order
addEmployeeToOrder(nUser_ID);
Label1.Text = myNomination.nOrder_ID.ToString();
}
else
{
if (nUser_ID <= 0) throw new ApplicationException("Invalid User ID");
//Add Recipient To order
addEmployeeToOrder(nUser_ID);
Label1.Text = "Add";
}
}
protected void addEmployeeToOrder(int nUser_ID)
{
// Add recipient to current nomination
Employee myEmployee = EmployeeManager.GetUserByID(nUser_ID);
int nNomination_ID = (int)SessionManager.Instance.nNomination_ID;
RecipientManager.recipient_AddToOrder(myEmployee, SessionManager.Instance.nNomination_ID);
}
protected void GridView_userList_SelectedIndexChanged(object sender, EventArgs e)
{
// Get User_ID of selected row
int nRecipient_ID = Convert.ToInt16(((Label)GridView_userList.SelectedRow.FindControl("lblRecipient_ID")).Text);
// Remove user from nomination
RecipientManager.recipient_DeleteFromOrder(nRecipient_ID);
}
}
ASKER
Hi,
I seem to have fixed the problem for the "index out of range" error by doing the following:
1) Added "DataKeyNames="nRecipient_ ID" to the GridView control for the User_List (the 2nd gridview in my example)
2) Modified the SelectedIndexChanged event on the gridview to use the datakey as follows:
===
protected void GridView_userList_Selected IndexChang ed(object sender, EventArgs e)
{
// Get User_ID of selected row
//int nRecipient_ID = Convert.ToInt16(((Label)Gr idView_use rList.Sele ctedRow.Fi ndControl( "lblRecipi ent_ID")). Text);
int nRecipient_ID = (int)GridView_userList.Sel ectedDataK ey.Values[ "nRecipien t_ID"];
// Remove user from nomination
RecipientManager.recipient _DeleteFro mOrder(nRe cipient_ID );
// Databind
GridView_userList.DataBind ();
}
I'm still getting the problem of having to click "select" button twice on the first gridview before the 2nd one is updated which is strange...
Any suggestions for points???
Cheers,
Anthony
I seem to have fixed the problem for the "index out of range" error by doing the following:
1) Added "DataKeyNames="nRecipient_
2) Modified the SelectedIndexChanged event on the gridview to use the datakey as follows:
===
protected void GridView_userList_Selected
{
// Get User_ID of selected row
//int nRecipient_ID = Convert.ToInt16(((Label)Gr
int nRecipient_ID = (int)GridView_userList.Sel
// Remove user from nomination
RecipientManager.recipient
// Databind
GridView_userList.DataBind
}
I'm still getting the problem of having to click "select" button twice on the first gridview before the 2nd one is updated which is strange...
Any suggestions for points???
Cheers,
Anthony
ASKER
I think I've fixed the "clicking twice" issue as well. Essentially I had to re-bind the user_list gridview inside the selectedindexchanged event of the first gridview... eg.
Panel_userList.Visible = true;
objdatasource_userList.Sel ectParamet ers.Clear( );
objdatasource_userList.Sel ectParamet ers.Add("n Order_ID", SessionManager.Instance.nN omination_ ID.ToStrin g());
GridView_userList.DataBind ();
Cheers
Anthony
Panel_userList.Visible = true;
objdatasource_userList.Sel
objdatasource_userList.Sel
GridView_userList.DataBind
Cheers
Anthony
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks PrairieDog ... this is exactly what I did before you posted but since you gave a great step by step overview, I'll award you the points.
Thanks for taking the time to confirm what I thought was going on in the page :-)
Anthony
Thanks for taking the time to confirm what I thought was going on in the page :-)
Anthony
Are you sure you are deleting the correct rows? Try this maybe?
Open in new window