473,718 Members | 1,949 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

GridView - Index was out of range.

I've got a GridView that's sorted by a stored procedure with
ROW_NUMBER:

PROCEDURE dbo.GetCalendar sByStatusIDPage d
(
@startRowIndex int,
@maximumRows int,
@statusID int
)
AS
SELECT pk_calendarID, fk_statusID, filename, barcode, received,
atpress, athandfinishing , shipped, reprint, status
FROM
(
SELECT pk_calendarID, fk_statusID, filename, barcode,
received, atpress, athandfinishing , shipped, reprint,
(SELECT status FROM Statuses WHERE Statuses.pk_sta tusID =
Calendars.fk_st atusID) as status,
ROW_NUMBER() OVER (ORDER BY received) AS RowRank
FROM Calendars
) AS CalendarsWithRo wNumbers
WHERE RowRank @startRowIndex AND RowRank <= (@startRowIndex +
@maximumRows) AND fk_statusID = @statusID

Here's the GridView:

<asp:GridView ID="GridView1" runat="server"
DataSourceID="C alendarsDataSou rce" AutoGenerateCol umns="False"
DataKeyNames="p k_calendarID" AllowPaging="Tr ue" PageSize="100">
<Columns>
<asp:BoundFie ld DataField="barc ode"
HeaderText="Bar code" SortExpression= "barcode" />
<asp:BoundFie ld DataField="rece ived"
HeaderText="Rec eived" SortExpression= "received" />
<asp:BoundFie ld DataField="atpr ess"
HeaderText="At Press" SortExpression= "atpress" />
<asp:TemplateFi eld>
<ItemTemplate >
<asp:CheckBox
ID="SelectCalen darCheckbox" runat="server" />
</ItemTemplate>
<HeaderTemplate >
<input id="chkAll"
onclick="javasc ript:SelectAllC heckboxes(this) ;" runat="server"
type="checkbox" />
</HeaderTemplate>
</asp:TemplateFie ld>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnToHandFi nishing" runat="server"
Text="Move To 'At Hand Finishing' Status"
OnClick="btnToH andFinishing_Cl ick" /><br />
<asp:ObjectData Source ID="CalendarsDa taSource"
runat="server" SelectMethod="G etCalendarsBySt atusIDPaged"
TypeName="Calen darsBLL" EnablePaging="T rue"
SelectCountMeth od="TotalNumber OfCalendarsBySt atusID">
<SelectParamete rs>
<asp:Paramete r DefaultValue="2 "
Name="statusID" Type="byte" />
</SelectParameter s>
</asp:ObjectDataS ource>

Then, I've got a button to take selected rows (via checkboxes in a
TemplateField) and do something with them in the database:

protected void btnToHandFinish ing_Click(objec t sender, EventArgs e)
{
// Copy the items in the Rows collection into an array.
GridView gv1 = (GridView)Login View1.FindContr ol("GridView1") ;
GridViewRow[] rowArray = new GridViewRow[gv1.Rows.Count];
gv1.Rows.CopyTo (rowArray, 0);

// Iterate though the array and display the value in the first
cell of the row.
foreach (GridViewRow row in rowArray)
{
bool result =
((CheckBox)row. FindControl("Se lectCalendarChe ckbox")).Checke d;
if (result)
{
byte fk_statusID = 3;
DateTime athandfinishing = DateTime.Now;
int pk_calendarID =
(int)gv1.DataKe ys[row.RowIndex].Value;
Label1.Text += gv1.DataKeys[row.RowIndex].Value + " " +
row.Cells[1].Text + "<br />";
// Get filename
string filename =
methods.GetCale ndarFilename(pk _calendarID);
methods.UpdateC alendarAtHandFi nishing(fk_stat usID,
athandfinishing , pk_calendarID);
// Move Files to "READY_TO_PRINT " folder
string from = @"C:\HTTPPush\R EADY_TO_PRINT\" +
filename;
string to = @"C:\HTTPPush\P ROCESSED\" + filename;
// File.Move(from, to);
}
gv1.DataBind();
}
}

If I run it without the 'int pk_calendarID =
(int)gv1.DataKe ys[row.RowIndex].Value;' line, it runs fine, and
displays the appropriate values. But if I run it with the
pk_calendarID line it fails with :

Index was out of range. Must be non-negative and less than the size of
the collection.
Parameter name: index
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.

Exception Details: System.Argument OutOfRangeExcep tion: Index was out of
range. Must be non-negative and less than the size of the collection.
Parameter name: index

Source Error:
Line 35: byte fk_statusID = 3;
Line 36: DateTime athandfinishing = DateTime.Now;
Line 37: int pk_calendarID =
(int)gv1.DataKe ys[row.RowIndex].Value;
Line 38: Label1.Text +=
gv1.DataKeys[row.RowIndex].Value + " " + row.Cells[1].Text + "<br />";
Line 39: // key = GridView1.DataK eys[row.RowIndex];

Source File: c:\...\AtPress. aspx.cs Line: 37

Stack Trace:

[ArgumentOutOfRa ngeException: Index was out of range. Must be
non-negative and less than the size of the collection.
Parameter name: index]
System.Collecti ons.ArrayList.g et_Item(Int32 index) +2776189
System.Web.UI.W ebControls.Data KeyArray.get_It em(Int32 index) +9
AtPress.btnToHa ndFinishing_Cli ck(Object sender, EventArgs e) in
c:\...\AtPress. aspx.cs:37
System.Web.UI.W ebControls.Butt on.OnClick(Even tArgs e) +75
System.Web.UI.W ebControls.Butt on.RaisePostBac kEvent(String
eventArgument) +97

System.Web.UI.W ebControls.Butt on.System.Web.U I.IPostBackEven tHandler.RaiseP ostBackEvent(St ring
eventArgument) +7
System.Web.UI.P age.RaisePostBa ckEvent(IPostBa ckEventHandler
sourceControl, String eventArgument) +11
System.Web.UI.P age.RaisePostBa ckEvent(NameVal ueCollection postData)
+33
System.Web.UI.P age.ProcessRequ estMain(Boolean
includeStagesBe foreAsyncPoint, Boolean includeStagesAf terAsyncPoint)
+4921

Any ideas?

Thanks in advance.
-Sean

Sep 5 '06 #1
0 8058

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
4837
by: Dick | last post by:
I have a GridView bound to an ObjectDataSource. I have a Button that calls GridView.DataBind. I want the row that is selected before the DataBind to still be selected afterwards. This happens automatically if the data doesn't change. But if records have been added or deleted then it looks as if some code is necessary: I've done this by using GridView.SelectedValue to get the key value of the currently selected Row and then by itterating...
0
1170
by: cheloman12 | last post by:
Hi, I’m implementing SavePageStateToPersistenceMedium and LoadPageStateFromPersistenceMedium in asp.net 2.0 to increment performance avoiding sending viewstate of pages to browser. The code I use is: protected override void SavePageStateToPersistenceMedium(object state) { string str = "VIEWSTATE_" + Request.UserHostAddress + "_" + DateTime.Now.Ticks.ToString(); Cache.Add(str, state, null,
0
2813
by: tfsmag | last post by:
I'm having a weird problem with the rowdatabound event for a gridview in my application... Here is the code. -------------------------------------- Protected Sub AnswersGrid_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles AnswersGrid.RowDataBound If e.Row.Cells(1).Text = "True" Or e.Row.Cells.Item(1).Text = "False" Then Dim editbutton As LinkButton = e.Row.FindControl("LinkButton1")
1
2768
by: cheloman12 | last post by:
Hi, I posted this problem some days ago. I repeat it because it was no answered. If description is confused, please make me know and i'll try to explain the case better. Thanks a lot, Marcelo "I’m implementing SavePageStateToPersistenceMedium and LoadPageStateFromPersistenceMedium in asp.net 2.0 to increment performance
0
1251
by: Mike P | last post by:
When I am performing a command on a row in my gridview, it works fine, unless I have paging enabled and I try t execute the command on a page other than the first page. The error I get is 'Index was out of range. Must be non-negative and less than the size of the collection' on the capitalised line in my code : protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "ActivateDeactivate")
3
3191
by: Mike P | last post by:
When I am performing a command on a row in my gridview, it works fine, unless I have paging enabled and I try t execute the command on a page other than the first page. The error I get is 'Index was out of range. Must be non-negative and less than the size of the collection' on the capitalised line in my code : protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "ActivateDeactivate")
1
4283
by: Sharon | last post by:
Hello All, I have a gridview control in webform which is dynamically populated on page startup with a query. I was trying to change the header text for the columns and also set wrap to false. i have four columns in gridview. Any suggestions guys This is what i used but i keep getting error Private Sub changestyle() GridView1.Columns(1).HeaderText = "First Name"
3
4072
by: shapper | last post by:
Hello, I need to loop though each row in a GridView and if the checkbox is a Template Field is checked I want to display the value of an invisible column named "LevelName". I tried everything I could think off but I always get an error or no value. Could someone please let me know what might be wrong?
1
5758
by: officegeek | last post by:
I have a gridview that is populated via page_load. I can get the delete to work but get an error after it deletes. The error is below the index value that is returned is the one that is deleted so that is why I think I get an error. Any help would be great. I am in the process of moving from classic ASP to .NET so i am not well versed yet. Index was out of range. Must be non-negative and less than the size of the collection....
0
8827
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
8723
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9207
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9120
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9053
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5971
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4481
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4741
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2122
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.