Click here to Skip to main content
15,910,661 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
//On link button click i got that error Index was out of range. Must be non-negative and less than the size of the collection. Please help

protected void grdLocationDetail_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (grdLocationDetail.DataKeys.Count > 0)
        {
            //if (e.CommandName == "Update")
            //{
                DropDownList ddllocation1F = (DropDownList)grdLocationDetail.FooterRow.Cells[1].FindControl("ddllocation1F");
                DropDownList ddllocationNameF = (DropDownList)grdLocationDetail.FooterRow.Cells[1].FindControl("ddllocationNameF");
                CheckBox chkActive = (CheckBox)grdLocationDetail.FooterRow.Cells[1].FindControl("chkActive");
                HiddenField hdfStatus = (HiddenField)grdLocationDetail.FooterRow.Cells[4].FindControl("hdfStatus");


                //try
                //{
                SqlConnection lconn = null;
                SqlTransaction ltran = null;
                lconn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["SQLConn"]);
                lconn.Open();
                ltran = lconn.BeginTransaction();
                marrParm = new SqlParameter[7];
                marrParm[0] = new SqlParameter("@LocationId", SqlDbType.Int);
                marrParm[0].Value = 0;
                marrParm[1] = new SqlParameter("@LocationName", SqlDbType.VarChar, 100);
                marrParm[1].Value = ddllocationNameF.SelectedItem.Text;
                marrParm[2] = new SqlParameter("@Location", SqlDbType.VarChar, 50);
                marrParm[2].Value = ddllocation1F.SelectedItem.Text;
                marrParm[3] = new SqlParameter("@Status", SqlDbType.VarChar, 10);
                //if (chkActive.Checked == true)
                //{
                marrParm[3].Value = "Active";
                //}
                //else
                //{
                //    marrParm[3].Value = "InActive";
                //}
                marrParm[4] = new SqlParameter("@RetMsg", SqlDbType.VarChar, 200);
                marrParm[4].Direction = ParameterDirection.InputOutput;

                marrParm[5] = new SqlParameter("@Flag", SqlDbType.VarChar, 10);
                marrParm[5].Value = "Insert";
                marrParm[6] = new SqlParameter("@UserID", SqlDbType.Int);
                marrParm[6].Value = Convert.ToInt32(Session["UserID"]);

                mObjBll.ProcedureName = "TrainingGroupM_LDAPLocationMapping";
                mObjBll.ParametersList = marrParm;
                mObjBll.AddUpdateMasters();
                //ldsLogin = mObjBll.GetList();
                if (mObjBll.IsRedirect == false)
                {
                    lblMsg.Text = "TrainingGroupM_UpdateLocationDetail : " + mObjBll.ErrorMessage;
                    return;
                }
                return;
                //}
                //catch (Exception ex)
                //{
                //    lblMsg.Text = ex.Message + ex.StackTrace;
                //}
                //finally
                //{
                //    marrParm = null;

                //}

            }

        }
Posted
Updated 24-Sep-14 23:50pm
v2
Comments
BillWoodruff 25-Sep-14 5:58am    
Set a break-point in the code, and then single-step (F11) until you reach the place where the error occurs. Describe here where the error occurs.
Praveenhart 25-Sep-14 6:03am    
protected void grdLocationDetail_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (grdLocationDetail.DataKeys.Count > 0)
{
//if (e.CommandName == "Update")
//{
DropDownList ddllocation1F = (DropDownList)grdLocationDetail.FooterRow.Cells[1].FindControl("ddllocation1F");
DropDownList ddllocationNameF = (DropDownList)grdLocationDetail.FooterRow.Cells[1].FindControl("ddllocationNameF");
CheckBox chkActive = (CheckBox)grdLocationDetail.FooterRow.Cells[1].FindControl("chkActive");
HiddenField hdfStatus = (HiddenField)grdLocationDetail.FooterRow.Cells[4].FindControl("hdfStatus");


//try
//{
SqlConnection lconn = null;
SqlTransaction ltran = null;
lconn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["SQLConn"]);
lconn.Open();
ltran = lconn.BeginTransaction();
marrParm = new SqlParameter[7];
marrParm[0] = new SqlParameter("@LocationId", SqlDbType.Int);
marrParm[0].Value = 0;
marrParm[1] = new SqlParameter("@LocationName", SqlDbType.VarChar, 100);
marrParm[1].Value = ddllocationNameF.SelectedItem.Text;
marrParm[2] = new SqlParameter("@Location", SqlDbType.VarChar, 50);
marrParm[2].Value = ddllocation1F.SelectedItem.Text;
marrParm[3] = new SqlParameter("@Status", SqlDbType.VarChar, 10);
//if (chkActive.Checked == true)
//{
marrParm[3].Value = "Active";
//}
//else
//{
// marrParm[3].Value = "InActive";
//}
marrParm[4] = new SqlParameter("@RetMsg", SqlDbType.VarChar, 200);
marrParm[4].Direction = ParameterDirection.InputOutput;

marrParm[5] = new SqlParameter("@Flag", SqlDbType.VarChar, 10);
marrParm[5].Value = "Insert";
marrParm[6] = new SqlParameter("@UserID", SqlDbType.Int);
marrParm[6].Value = Convert.ToInt32(Session["UserID"]);

mObjBll.ProcedureName = "TrainingGroupM_LDAPLocationMapping";
mObjBll.ParametersList = marrParm;
mObjBll.AddUpdateMasters();
//ldsLogin = mObjBll.GetList();
if (mObjBll.IsRedirect == false)
{
lblMsg.Text = "TrainingGroupM_UpdateLocationDetail : " + mObjBll.ErrorMessage;
return;
}
return;
//}
//catch (Exception ex)
//{
// lblMsg.Text = ex.Message + ex.StackTrace;
//}
//finally
//{
// marrParm = null;

//}

}

} ///Here i got error Index was out of range. Must be non-negative and less than the size of the collection.
BillWoodruff 25-Sep-14 7:30am    
I have no idea where "here" is: show the specific line in your code where the error occurred.

Please check that you are getting value in
GridViewCommandEventArgs "e"


value of e...
Need to modify .aspx page(design)
 
Share this answer
 
Comments
Praveenhart 25-Sep-14 5:58am    
//That is my aspx gridview design.
<asp:GridView ID="grdLocationDetail" runat="server" AutoGenerateColumns="false"
onpageindexchanging="grdLocationDetail_PageIndexChanging"
onrowcancelingedit="grdLocationDetail_RowCancelingEdit"
onrowediting="grdLocationDetail_RowEditing"
onrowupdating="grdLocationDetail_RowUpdating" DataKeyNames ="LocationId" class="view2" Width="50%" ShowFooter="False" OnRowCommand="grdLocationDetail_RowCommand" >
<columns>
<asp:TemplateField HeaderText="Sr No" HeaderStyle-HorizontalAlign="left" >
<%--<edititemtemplate>
<asp:Label ID="lblSrNo" runat="server">
--%>
<itemtemplate>
<%# ((GridViewRow)Container).RowIndex + 1%>


<asp:TemplateField HeaderText="LDAP Location" SortExpression="Location" HeaderStyle-HorizontalAlign="left">

<edititemtemplate>
<asp:DropDownList ID="ddllocation1" runat="server" Width="171px">

<asp:Label ID="lblLocationPraveen" Visible="false" runat="server" Text='<%# Bind("LDAPLocationName") %>'>

<footertemplate>
<asp:DropDownList ID="ddllocation1F" runat="server" >


<itemtemplate>
<asp:Label ID="lblLocationName" runat="server" Text='<%# Bind("LDAPLocationName") %>'>



<asp:TemplateField HeaderText="Location Name" SortExpression="LocationName" HeaderStyle-HorizontalAlign="left">
<edititemtemplate>
<%-- <asp:TextBox ID="txtLocation1" runat="server" Text='<%# Bind("LocationName") %>'>--%>
<asp:DropDownList ID="ddllocationName" Width="171px" runat="server">

<asp:Label ID="lblLocation1Name" Visible="false" runat="server" Text='<%# Bind("LocationName") %>'>

<footertemplate>
<asp:DropDownList ID="ddllocationNameF" runat="server" >


<itemtemplate>
<asp:Label ID="lblLocation1" runat="server" Text='<%# Bind("LocationName") %>'>




<asp:TemplateField HeaderText="Active" SortExpression="Status" HeaderStyle-HorizontalAlign="left">
<edititemtemplate>
<asp:HiddenField ID="hdfStatus" runat="server" Value='<%# Bind("Status") %>' />
<asp:CheckBox ID="chkActive" runat="server" />

<footertemplate>
<asp:CheckBox ID="chkActiveF" runat="server" />

<itemtemplate>
<asp:Label ID="lblUserStatus" runat="server" Text='<%# Bind("Status") %>'>


<asp:TemplateField ShowHeader="False">
<edititemtemplate>
<asp:Button ID="btnUpdate" runat="server" CausesValidation="false"
CommandName
Praveenhart 25-Sep-14 5:58am    
Please suggest.
Leena 206 25-Sep-14 6:01am    
can you post full code? as
<asp:Button ID="btnUpdate" runat="server" CausesValidation="false"
CommandName.... --> what is next?

Praveenhart 25-Sep-14 6:05am    
//ASPX PAGE
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Location.aspx.cs" Inherits="Location" %>

<%@ Register Src="~/UserControl/AuditTrail.ascx" TagName="UCAuditLog" TagPrefix="UC" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc2" %>
<%@ Register Assembly="CheckBoxListExCtrl" Namespace="CheckBoxListExCtrl" TagPrefix="cc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="Server">
<style type="text/css">
.style1
{
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 12px;
font-style: normal;
font-weight: bold;
color: #356886;
text-decoration: none;
width: 91px;
}

.style2
{
width: 177px;
}

.style4
{
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 12px;
font-style: normal;
font-weight: bold;
color: #356886;
text-decoration: none;
width: 85px;
}

.style5
{
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 12px;
font-style: normal;
font-weight: bold;
color: #356886;
text-decoration: none;
width: 43px;
}
</style>
<script type="text/javascript">
function validateSave() {
if ((document.getElementById("ctl00_Main_txtLocationName").value) == "") {
alert("Please Enter Location Name");
document.getElementById("ctl00_Main_txtLocationName").focus();
return false;
}

}
function ValidateGridUpdate(LocationName) {
if ((LocationName.value) == "") {
alert("Please Enter Location Name.");
LocationName.focus();
return false;
}

}

</script>

<asp:Content ID="Content2" ContentPlaceHolderID="Main" runat="Server">
<form id="frmLocati>
<%--
--%>

<table cellpadding="3" cellspacing="2" class="data" style="border-bottom-width: thick; border-bottom-color: Black; border-left-width: thick; border-left-color: Black; border-right-width: thick; border-right-color: Black; border-top-width: thick; border-top-color: Black" width="100%">
<tr>
<td valign="top" class="heading_blue" align="left" colspan="6">
<asp:Label ID="lblHeading" runat="server" Text="Location Mapping">
</td>
</tr>
<tr>
<td valign="top" class="errmsg" align="left" colspan="6">
<asp:Label ID="lblMsg" runat="server"
Font-Size="Small" ForeColor="Red">
</td>
</tr>
</table>

<asp:GridView ID="grdLocationDetail" runat="server" AutoGenerateColumns="false"
onpageindexchanging="grdLocationDetail_PageIndexChanging"
onrowcancelingedit="grdLocationDetail_RowCancelingEdit"
onrowediting="grdLocationDetail_RowEditing"
onrowupdating="grdLocationDetail_RowUpdating" DataKeyNames ="LocationId" class="view2" Width="50%" ShowFooter="False" OnRowCommand="grdLocationDetail_RowCommand" >
<columns>
<asp:TemplateField HeaderText="Sr No" HeaderStyle-HorizontalAlign="left" >
<%--<edititemtemplate>
<asp:Label ID="lblSrNo" runat="server">
--%>
<itemtemplate>
<%# ((GridViewRow)Container).RowIndex + 1%>


&
Praveenhart 25-Sep-14 6:06am    
//Code behind Page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using SystemLayers;
using System.Web.UI.WebControls;

public partial class Location : System.Web.UI.Page
{
SystemLayers.BLL mObjBll = new BLL();
SqlParameter[] marrParm = null;

protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{

lblMsg.Text = "";
ViewState["AddUpdateFlag"] = "add";
//FillDropdown();
UserLocationData();
}
if (ViewState["AddUpdateFlag"].ToString() == "add")
{
ucauditlog.Visible = false;
}
else
{
ucauditlog.Visible = true;
}


}
//protected void btnSave_Click(object sender, EventArgs e)
//{
// if (txtLocationName.Text == "")
// {
// lblMsg.Text = "Enter Location Name";
// return;
// }
// try
// {

// marrParm = new SqlParameter[6];
// marrParm[0] = new SqlParameter("@LocationName", SqlDbType.VarChar, 100);
// marrParm[0].Value = txtLocationName.Text.Trim();
// marrParm[1] = new SqlParameter("@Status", SqlDbType.VarChar, 10);
// if (chkActive.Checked == true)
// {
// marrParm[1].Value = "Active";
// }
// else
// {
// marrParm[1].Value = "InActive";
// }
// marrParm[2] = new SqlParameter("@LocationId", SqlDbType.Int);
// marrParm[2].Value = 0;
// marrParm[3] = new SqlParameter("@Flag", SqlDbType.VarChar, 10);
// marrParm[3].Value = "Insert";
// marrParm[4] = new SqlParameter("@UserID", SqlDbType.Int);
// marrParm[4].Value = Convert.ToInt32(Session["UserID"]);
// marrParm[5] = new SqlParameter("@RetMsg", SqlDbType.VarChar, 200);
// marrParm[5].Direction = ParameterDirection.InputOutput;
// //marrParm[6] = new SqlParameter("@Location", SqlDbType.VarChar, 50);
// //marrParm[6].Value = ddlLocation.SelectedItem.Text.ToString();
// mObjBll.ProcedureName = "TrainingGroupM_SaveLocation";
// mObjBll.ParametersList = marrParm;
// mObjBll.AddUpdateMasters();
// if (mObjBll.IsRedirect == false)
// {
// lblMsg.Text = "TrainingGroupM_SaveLocation : " + mObjBll.ErrorMessage;
// return;
// }
// else
// {
// UserLocationData();
// //FillDropdown();
// txtLocationName.Text = "";
// //Response.Redirect("Login.aspx?msg=Password has been set.", true);
// lblMsg.Text = mObjBll.GetOutputValue("@RetMsg").ToString();
// //lblMsg.Text = "Password has been set.";
// }


// }
// catch (Exception ex)
// {
// lblMsg.Text = ex.Message + ex.StackTrace;
// }
// finally
// {
// marrParm = null;
// }
//}
//protected void btnView_Click(object sender, EventArgs e)
//{
// lblMsg.Text = "";
// UserLocationData();
// //FillDropdown();
//}
public void UserLocationData()
{
DataSet ldsLogin = new DataSet();
try
{

mObjBll.ProcedureName = "TrainingGroupM_GetUserLocationDetailMapping";
mObjBll.ParametersList = null;
ldsLogin = mObjBll.GetDetails();
grdLocationDetail.Visible = true;
grdLocationDetail.DataSource = ldsLogin;
grdLocationDetail.DataBind();
//hdnChildEmptyData.Value = "False";
}
catch (Exception ex)
{
Response.Write("Error :Page_Load " + ex.Message + " " + ex.StackTrace);
}
Add this:

HTML
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"


Eg
XML
<ItemTemplate>
            <asp:Button runat="server" ID="IncreaseButton"
              Text="Increase Price 5%"
              CommandName="Increase"
              CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
          </ItemTemplate>


For More details Refer:

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand(v=vs.110).aspx[^]
 
Share this answer
 
v5
Comments
george4986 25-Sep-14 6:26am    
instead of adding new solutions, please update ur previous solution with new code
Leena 206 26-Sep-14 0:54am    
I have added new solution as the code that you have putted is too long and unnecessary .
It will confuse you only ..

bdw have you overcome with your problem? is that solution 2 worked for you?
Praveenhart 26-Sep-14 6:49am    
Thanks Leena. You save my life.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900