Grid View Out of Range Exception, Value in Range
I have a GridView:
<asp:GridView runat="server" ID="_gv_AllResp" Width="100%" style="color: White;" DataKeyNames="recordid"
Font-Size="10pt" OnDataBound="_gvDataBind_Eve" AutoGenerateSelectButton="true" OnSelectedIndexChanged="_gv_AllResp_SelectedIndexChanged">
<RowStyle HorizontalAlign="Center" />
<HeaderStyle BackColor="#57768f"/>
<RowStyle BackColor="#dae2e8" ForeColor="Black" />
<AlternatingRowStyle BackColor="#ffffff" ForeColor="Black" />
</asp:GridView>
That I bind from the code behindwith ADO:
SELECT a.[recordid], [lname] + ', ' + [fname] as [name], Convert(char, [datebirth], 101) as 'DOB', phone1, phone2, phone3, ext FROM [dbo].[Respondent] a
I then have a procedure to select a random number of records from the grid and insertthem into a table:
var rnd = new Random();
var _rand = Enumerable.Range(0, _RowCount).Select(x => new { val = x, order = rnd.Next() }).OrderBy(i => i.order).Select(x => x.val).Take(_LockCount).ToArray();
string _jobnum = _dd_ActJobs.SelectedValue.ToString();
foreach (var a in _rand)
{
int b = Convert.ToInt32(a);
using (var con = new SqlConnection())
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["RM_V1.0CS"].ConnectionString;
try
{
con.Open();
var cmd = new SqlCommand("INS_DemoLockQuery", con) { CommandType = CommandType.StoredProcedure };
cmd.Parameters.Add("@jobnum", SqlDbType.NVarChar, 100, "jobnum");
cmd.Parameters.Add("@respnum", SqlDbType.NVarChar, 100, "respnum");
cmd.Parameters.Add("@name", SqlDbType.NVarChar, 100, "name");
cmd.Parameters.Add("@phone", SqlDbType.NVarChar, 100, "phone");
cmd.Parameters.Add("@wphone", SqlDbType.NVarChar, 100, "wphone");
cmd.Parameters.Add("@wphone_ext", SqlDbType.NVarChar, 100, "wphone_ext");
cmd.Parameters.Add("@cellp开发者_运维百科hone", SqlDbType.NVarChar, 100, "cellphone");
cmd.Parameters.Add("@quota", SqlDbType.NVarChar, 100, "quota");
cmd.Parameters["@jobnum"].Value = _jobnum;
//GETTING ERROR HERE
cmd.Parameters["@respnum"].Value = _gv_AllResp.Rows[b].Cells[1].Text.ToString();
cmd.Parameters["@name"].Value = _gv_AllResp.Rows[b].Cells[2].Text.ToString();
cmd.Parameters["@phone"].Value = _gv_AllResp.Rows[b].Cells[4].Text.ToString().Replace("(", "").Replace(")", "").Replace("-", "").Replace(" ", "").Trim();
cmd.Parameters["@wphone"].Value = _gv_AllResp.Rows[b].Cells[5].Text.ToString().Replace("(", "").Replace(")", "").Replace("-", "").Replace(" ", "").Trim();
cmd.Parameters["@wphone_ext"].Value = _gv_AllResp.Rows[b].Cells[6].Text.ToString().Replace("(", "").Replace(")", "").Replace("-", "").Replace(" ", "").Trim();
cmd.Parameters["@cellphone"].Value = _gv_AllResp.Rows[b].Cells[7].Text.ToString().Replace("(", "").Replace(")", "").Replace("-", "").Replace(" ", "").Trim();
cmd.Parameters["@quota"].Value = _ddActQuota.SelectedValue.ToString();
cmd.ExecuteNonQuery();
ViewAvailable();
}
//catch (Exception ex) { ErrHandler.WriteError(ex.Message); }
finally { con.Close(); }
}
}
I'm getting the following "Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index" There are 145 rows in the grid and the value of b (row number) is 120 for instance for this particular test. This is in the range of allowable rows. I'm don't understand how this is outside the index range.
Stack Trace
at System.Collections.ArrayList.get_Item(Int32 index)
at System.Web.UI.WebControls.GridViewRowCollection.get_Item(Int32 index)
at Default3._b_selectRepond(Object sender, EventArgs e) in c:\Afocus\Jobs\Query.aspx.cs:line 668
at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(Str ing eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
Any Suggestions ? Thanks in advance Guys / Girls
EDIT @ James
I just tried using the datakeynames as you suggested and replaced the insert block with
cmd.Parameters["@jobnum"].Value = _jobnum;
cmd.Parameters["@respnum"].Value = _gv_AllResp.DataKeys[b]["recordid"].ToString();
cmd.Parameters["@name"].Value = _gv_AllResp.DataKeys[b]["Name"].ToString().Replace(" ", "");
cmd.Parameters["@phone"].Value = _gv_AllResp.DataKeys[b]["Main"].ToString().Replace(" ", "").Replace("(", "").Replace(")", "").Replace("-", "").Replace(" ", "").Trim();
cmd.Parameters["@wphone"].Value = _gv_AllResp.DataKeys[b]["Work Phone"].ToString().Replace(" ", "").Replace("(", "").Replace(")", "").Replace("-", "").Replace(" ", "").Trim();
cmd.Parameters["@wphone_ext"].Value = _gv_AllResp.DataKeys[b]["ext"].ToString().Replace(" ", "").Replace("(", "").Replace(")", "").Replace("-", "").Replace(" ", "").Trim();
cmd.Parameters["@cellphone"].Value = _gv_AllResp.DataKeys[b]["Cell Phone"].ToString().Replace(" ", "").Replace("(", "").Replace(")", "").Replace("-", "").Replace(" ", "").Trim();
cmd.Parameters["@quota"].Value = _ddActQuota.SelectedValue;
However I still get the same error, I tried to "lock" 50 records with 145 rows in the grid and it looped through 23 times and then threw an error n the 135 row (b=135) Same Error "Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index"
You're specifying the column indexes starting at position 1
instead of 0
. You have 7 columns in your select, so your column indexes should range 0-6
.
I believe this is the offending line:
_gv_AllResp.Rows[b].Cells[7].Text // = bang!
EDIT
To eliminate the problem altogether, use data keys to access the columns you need:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="Name, DOB, phone1, phone2, ..." >
And in the code-behind:
string name = GridView1.DataKeys[0]["Name"].ToString();
精彩评论