Gridview: Index was out of range. Must be non-negative and less - c#

I want to get the value from my gridview depending on the row I select.
I am getting the error "Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index"
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
string name = GridView1.SelectedRow.Cells[0].Text;
}
/*---------------------------------------------------------------------------*/
<asp:GridView ID="GridView1"
OnSelectedIndexChanged = "OnSelectedIndexChanged"
autogeneratecolumns="false" runat="server">
<Columns>
<asp:BoundField DataField="ESS_ID" HeaderText="ID" Visible=false/>
<asp:BoundField DataField="ESS_Pay_Dt" HeaderText="Pay Date" DataFormatString="{0:d}"
HtmlEncode="false" ItemStyle-Width="100" HeaderStyle-BorderColor=navy ItemStyle-BorderColor="navy" ItemStyle-HorizontalAlign="center"/>
<asp:BoundField DataField="ESS_Emp_Name" HeaderText="Employee Name" ItemStyle-Width="250" HeaderStyle-BorderColor=navy ItemStyle-BorderColor="navy" ItemStyle-HorizontalAlign="center"/>
<asp:BoundField DataField="ESS_Emp_Num" HeaderText="Number" ItemStyle-Width="75" HeaderStyle-BorderColor=navy ItemStyle-BorderColor="navy" ItemStyle-HorizontalAlign="center"/>
<asp:BoundField DataField="ESS_Emp_Dept" HeaderText="Department" ItemStyle-Width="100" HeaderStyle-BorderColor=navy ItemStyle-BorderColor="navy" ItemStyle-HorizontalAlign="center"/>
<asp:BoundField DataField="ESS_Pay_End_Dt" HeaderText="Pay End Date" Visible="false" />
<asp:BoundField DataField="ESS_Net_Amt" HeaderText="Net Amount" ItemStyle-Width="150" HeaderStyle-BorderColor=navy ItemStyle-BorderColor="navy" ItemStyle-HorizontalAlign="center"/>
<asp:BoundField DataField="ESS_Total_Earnings1" HeaderText="Total Earnings1" Visible="false"/>
<asp:BoundField DataField="ESS_Total_Earnings2" HeaderText="Total Earnings2" Visible="false"/>
<asp:BoundField DataField="ESS_Total_Taxes1" HeaderText="Total Taxes1" Visible="false"/>
<asp:BoundField DataField="ESS_Total_Taxes2" HeaderText="Total Taxes2" Visible="false"/>
<asp:BoundField DataField="ESS_Total_Deductions1" HeaderText="Total Deductions1" Visible="false"/>
<asp:BoundField DataField="ESS_Total_Deductions2" HeaderText="Total Deductions2" Visible="false"/>
<asp:BoundField DataField="ESS_Net_Pay1" HeaderText="Net Pay1" Visible="false"/>
<asp:BoundField DataField="ESS_Net_Pay2" HeaderText="Net Pay2" Visible="false"/>
<asp:BoundField DataField="ESS_Vac_Hrs" HeaderText="Vacation Hours" Visible="false"/>
<asp:BoundField DataField="ESS_Sck_Hrs" HeaderText="Sick Hours" Visible="false" />
<asp:BoundField DataField="ESS_Batch_Num" HeaderText="Batch Number" Visible="false"/>
<asp:BoundField DataField="ESS_Load_Count" HeaderText="Load Count" Visible="false"/>
<asp:BoundField DataField="ESS_Load_Dt" HeaderText="Load Date" Visible="false"/>
<asp:ButtonField Text="Select" CommandName="Select" ItemStyle-Width="150" />
</Columns>
</asp:GridView>

you appear to be in the wrong EventHandler try the following example
private void GridView1_SelectionChanged(object sender, EventArgs e)
{
if (GridView1.SelectedCells.Count > 0)
{
int selectedrowindex = GridView1.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = GridView1.Rows[selectedrowindex];
name = Convert.ToString(selectedRow.Cells["Cell Zero's Name goes here"].Value);
}
}
if you are going to use the name local variable outside of this method then string name needs
to be declared outside the local scope
for example at the class level declare it as the following then you can use it globally
public static string name = string.Empty;
Some additional Methods / Events you can checkout as well DataGrid.SelectedItem Property

Related

PageIndex changes but data stays the same

I have a GridView that I bind a list to from data retrieved via edmx. My issue is when I click on pagers, the page changes, and I have debugged and know that it's changing the value, but it always just shows the data from the first page. What am I missing? Oh, and I call LoadAllRequestsData() from Page_Load in an if(!Page.IsPostBack).
<cm:GridControl runat="server" ID="gvAllRequests" DataKeyNames="Number" OnPageIndexChanging="AllRequestsGridViewPageIndexChanging" ShowHeaderWhenEmpty="True" EmptyDataText="No requests to show." >
<Columns>
<asp:BoundField DataField="Number" HeaderText="Number" SortExpression="Number" InsertVisible="False" ReadOnly="True"></asp:BoundField>
<asp:BoundField DataField="CustomerId" HeaderText="CustomerId" SortExpression="CustomerId" Visible="False"></asp:BoundField>
<asp:BoundField DataField="Customer" HeaderText="Customer" SortExpression="Customer" Visible="False"></asp:BoundField>
<asp:BoundField DataField="TypeId" HeaderText="TypeId" SortExpression="TypeId" Visible="False"/>
<asp:BoundField DataField="Type" HeaderText="Type" SortExpression="Type"></asp:BoundField>
<asp:BoundField DataField="Note" HeaderText="Note" SortExpression="Note"/>
<asp:BoundField DataField="RequestedOn" HeaderText="Requested On" SortExpression="RequestedOn"/>
<asp:BoundField DataField="RequestedById" HeaderText="RequestedById" SortExpression="RequestedById" Visible="False" />
<asp:BoundField DataField="RequestedBy" HeaderText="Requested By" SortExpression="RequestedBy" />
<asp:BoundField DataField="CompletedOn" HeaderText="Completed On" SortExpression="CompletedOn" />
<asp:BoundField DataField="CompletedById" HeaderText="CompletedById" SortExpression="CompletedById" Visible="False"/>
<asp:BoundField DataField="CompletedBy" HeaderText="Completed By" SortExpression="CompletedBy" />
<asp:BoundField DataField="LastModifiedOn" HeaderText="LastModified On" SortExpression="LastModifiedOn" />
<asp:BoundField DataField="LastModifiedById" HeaderText="LastModifiedById" SortExpression="LastModifiedById" Visible="False"/>
<asp:BoundField DataField="LastModifiedBy" HeaderText="LastModified By" SortExpression="LastModifiedBy" />
<asp:CheckBoxField DataField="IsDeleted" HeaderText="IsDeleted" SortExpression="IsDeleted" Visible="False"/>
</Columns>
</cm:GridControl>
private void LoadAllRequestsData(string sortExpression = "RequestedOn", SortDirection sortDirection = SortDirection.Descending)
{
var db = new CrewManagerEntities();
var list = db.GetAllRequestsByUserId(_customerId).ToList();
if (!string.IsNullOrEmpty(sortExpression))
{
list = list.AsQueryable().OrderBy(sortExpression + " " + (sortDirection == SortDirection.Ascending ? "ASC" : "DESC")).ToList();
gvAllRequests.SetSort(sortExpression, sortDirection);
}
gvAllRequests.DataSource = list;
gvAllRequests.DataBind();
}
protected void AllRequestsGridViewPageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvAllRequests.PageIndex = e.NewPageIndex;
LoadAllRequestsData();
}
Edit: So, I tried using SqlDataSource instead of doing call in codebehind and using a list and the paging works. That is fine but I would like to know why the list doesn't work as there may be instances where I need to use a list source. Any ideas?

Gridview controllers null after inserting column

I am developing a Web App for managing Student exam entries but I am coming across an issue with my gridview.
The basic idea is that a user can go on and enter and update details on a students exam. Complications arise when certain subjects require different fields to be populated and this is where my issue is.
The exception is thrown when the Save Button method is run. I get a Null Object reference thrown when running the AddAudit and UpdateRecord methods. After some debugging from the looks of it the issue is the controls (ddlDate, txtAssesmentLevel etc) are not being declared from the FindCotrol method of the gridview meaning when the AddAudit and UpdateRecord methods are called they point to a null controller.
Be aware that this issue does not occur when the code is not "C2555" which leads me to suspect the issue is with dynamically adding columns and controls getting muddled up though i am not sure.
Any assistance would be great and feel free to ask for more information.
Below is my basic code:
Page Load Method
protected void Page_Load(object sender, EventArgs e){
if(!IsPostBack){
//Selected class passed through
selectedClass sc = (selectedClass)Session["selectedClass"] as selectedClass;
//Get Class Code
lblAosCode.Text = sc.getAOSCode();
//If class is English
if(lblAosCode.Text == "C2555"){
TemplateField speakingListening = new TemplateField();
speakingListening.HeaderText = "Speaking and Listening";
dgvSelectedClasses.Columns.Insert(7, speakingListening);
}
//Populate Gridview
DataTable dsSelectedClasses = AccessData.getSelectedClasses(sc.getAOSCode(), sc.getAOSPeriod(), sc.getDescription());
dgvSelectedClasses.DataSource = dsSelectedClasses;
dgvSelectedClasses.DataBind();
//Check if txtAssesmentLevel is populated
for (int index = 0; index < dgvSelectedClasses.Rows.Count; index++)
{
TextBox txtAssessmentLevel = (TextBox)dgvSelectedClasses.Rows[index].FindControl("txtAssessmentLevel");
if (dgvBefore.Rows[index].Cells[4].Text != " ")
{
txtAssessmentLevel.ReadOnly = true;
}
}
}
}
Save Method (Exception Thrown)
protected void btnSave_Click(object sender, EventArgs e)
{
for (int i = 0; i < dgvSelectedClasses.Rows.Count; i++)
{
DropDownList ddlL1L2 = (DropDownList)dgvSelectedClasses.Rows[i].FindControl("ddlL1L2");
DropDownList ddlExamDate = (DropDownList)dgvSelectedClasses.Rows[i].FindControl("ddlExamDate");
TextBox txtAssessmentLevel = (TextBox)dgvSelectedClasses.Rows[i].FindControl("txtAssessmentLevel");
DropDownList ddlSpeakingListening = null;
if (lblAosCode.Text.Contains("C2555"))
{
ddlSpeakingListening = (DropDownList)dgvSelectedClasses.Rows[i].FindControl("ddlSpeakingListening");
}
if (IsPostBack)
{
if (lblAosCode.Text.Contains("C2555"))
{
AccessData.addAudit(dgvSelectedClasses.Rows[i].Cells[0].Text, Context.User.Identity.Name, "Assessment Level", txtAssessmentLevel.Text, dgvBefore.Rows[i].Cells[4].Text);
AccessData.addAudit(dgvSelectedClasses.Rows[i].Cells[0].Text, Context.User.Identity.Name, "Exam request L1 or L2", ddlL1L2.SelectedValue, dgvBefore.Rows[i].Cells[14].Text);
AccessData.addAudit(dgvSelectedClasses.Rows[i].Cells[0].Text, Context.User.Identity.Name, "Exam Date", ddlExamDate.SelectedValue, dgvBefore.Rows[i].Cells[15].Text);
AccessData.addAudit(dgvSelectedClasses.Rows[i].Cells[0].Text, Context.User.Identity.Name, "Speaking and Listening", ddlSpeakingListening.SelectedValue, dgvBefore.Rows[i].Cells[7].Text);
AccessData.updateRecord(txtAssessmentLevel.Text, ddlL1L2.SelectedValue, ddlExamDate.SelectedValue, lblAosCode.Text, lblAosPeriod.Text, dgvSelectedClasses.Rows[i].Cells[0].Text, ddlSpeakingListening.SelectedValue);
}
else
{
AccessData.addAudit(dgvSelectedClasses.Rows[i].Cells[0].Text, Context.User.Identity.Name, "Assessment Level", txtAssessmentLevel.Text, dgvBefore.Rows[i].Cells[4].Text);
AccessData.addAudit(dgvSelectedClasses.Rows[i].Cells[0].Text, Context.User.Identity.Name, "Exam request L1 or L2", ddlL1L2.SelectedValue, dgvBefore.Rows[i].Cells[13].Text);
AccessData.addAudit(dgvSelectedClasses.Rows[i].Cells[0].Text, Context.User.Identity.Name, "Exam Date", ddlExamDate.SelectedValue, dgvBefore.Rows[i].Cells[14].Text);
AccessData.updateRecord(txtAssessmentLevel.Text, ddlL1L2.SelectedValue, ddlExamDate.SelectedValue, lblAosCode.Text, lblAosPeriod.Text, dgvSelectedClasses.Rows[i].Cells[0].Text);
}
}
}
Response.Redirect("~/contact");
}
On Row Data Bound
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (lblAosCode.Text.Contains("C2555"))
{
DropDownList ddlSpeakingListening = new DropDownList();
ddlSpeakingListening.ID = "ddlSpeakingListening";
ddlSpeakingListening.Items.Add("L1");
ddlSpeakingListening.Items.Add("L2");
ddlSpeakingListening.Items.Add("Entry");
ddlSpeakingListening.Items.Add("NS");
e.Row.Cells[7].Controls.Add(ddlSpeakingListening);
}
}
}
ASP.NET
<asp:GridView ID="dgvSelectedClasses" runat="server" AutoGenerateColumns="False" OnRowDataBound="OnRowDataBound">
<Columns>
<asp:BoundField DataField="StudentID" HeaderText="Student ID" ReadOnly="True" />
<asp:BoundField DataField="StageCode" HeaderText="Stage Code" ReadOnly="True" />
<asp:BoundField DataField="Forename" HeaderText="Forename" ReadOnly="True" />
<asp:BoundField HeaderText="Surname" DataField="Surname" />
<asp:TemplateField HeaderText="Assessment Level">
<ItemTemplate>
<asp:TextBox ID="txtAssessmentLevel" Text ='<%#Bind("AssessmetLevel") %>' runat="server" Width="50px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="TargetLevel" HeaderText="Target Level" />
<asp:BoundField DataField="Achievelevel" HeaderText="Achieve Level" />
<asp:BoundField DataField="FELSOutcome" HeaderText="FELS Outcome" />
<asp:BoundField DataField="Registration" HeaderText="Registration" />
<asp:BoundField DataField="DateSpreadsheetSent" HeaderText="Last Update" />
<asp:BoundField DataField="Dayofclass" HeaderText="Day of class" />
<asp:BoundField DataField="Timeofclass" HeaderText="Time of class" />
<asp:BoundField DataField="Location" HeaderText="Location" />
<asp:TemplateField HeaderText="Exam request L1 or L2" >
<ItemTemplate>
<asp:DropDownList ID="ddlL1L2" runat="server" >
<asp:ListItem>Not Set</asp:ListItem>
<asp:ListItem>L1</asp:ListItem>
<asp:ListItem>L2</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Exam date">
<ItemTemplate>
<asp:DropDownList ID="ddlExamDate" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:GridView ID="dgvBefore" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="StudentID" HeaderText="Student ID" ReadOnly="True" />
<asp:BoundField DataField="StageCode" HeaderText="Stage Code" ReadOnly="True" />
<asp:BoundField DataField="Forename" HeaderText="Forename" ReadOnly="True" />
<asp:BoundField HeaderText="Surname" DataField="Surname" />
<asp:BoundField DataField="AssessmetLevel" HeaderText="Assessment Level" NullDisplayText=" "/>
<asp:BoundField DataField="TargetLevel" HeaderText="Target Level" />
<asp:BoundField DataField="AchieveLevel" HeaderText="Achieve Level" />
<asp:BoundField DataField="FELSOutcome" HeaderText="FELS Outcome" />
<asp:BoundField DataField="Registration" HeaderText="Registration" />
<asp:BoundField DataField="DateSpreadsheetSent" HeaderText="Date Spreadsheet Sent" />
<asp:BoundField DataField="Dayofclass" HeaderText="Day of class" />
<asp:BoundField DataField="Timeofclass" HeaderText="Time of class" />
<asp:BoundField DataField="Location" HeaderText="Location" />
<asp:BoundField DataField="ExamrequestL1orL2" HeaderText="Exam request L1 or L2" />
<asp:BoundField DataField="Examdate" HeaderText="Exam date" />
<asp:BoundField DataField="Reviewed" HeaderText="Reviewed" />
</Columns>
</asp:GridView>
P.S. This is my first question hopefully it makes sense and I am open to pointers :)
Edit: The page load method does include code to populate dgvBefore as well as a few authentications thing i just forgot to include it.
I think you need to add the drop down list column on every postback. Refer this link : https://www.codeproject.com/Tips/682689/Add-populated-dropdownlist-to-GridView-dynamically

Make asp buttonfield visible at runtime

I have an <asp:ButtonField> inside a gridview. How do I target the button in the gridview to make it Visible on runtime based on a condition ? I am not able to target it since it doesnt have the ID property. I am stuck here. Here is the code below
<asp:GridView ID="OrdersDataList1" runat="server" DataKeyNames="OrderID" Width="100%" SkinID="Gridview" OnPageIndexChanging="orders_PageIndexChanging"
EmptyDataText="You have no orders." AllowSorting="True" OnSorting="OnSort" AllowPaging="true" PageSize="15" AutoGenerateColumns="False" OnRowCommand="updateStatus">
<Columns>
<asp:BoundField DataField="CustomerUser_ID" HeaderText="UserID" Visible="true" />
<asp:BoundField DataField="OrderID" HeaderText="OrderNo" InsertVisible="False" ReadOnly="True" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left" SortExpression="OrderID" />
<asp:BoundField DataField="OrderDate" HeaderText="OrderDate" SortExpression="OrderDate" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center"/>
<asp:BoundField DataField="Base" HeaderText="Base" DataFormatString="{0:C}" SortExpression="Base" HeaderStyle-HorizontalAlign="Right" ItemStyle-HorizontalAlign="Right"/>
<asp:BoundField DataField="Freight" HeaderText="Freight" DataFormatString="{0:C}" SortExpression="Freight" HeaderStyle-HorizontalAlign="Right" ItemStyle-HorizontalAlign="Right"/>
<asp:BoundField DataField="Total" HeaderText="Total" DataFormatString="{0:C}" SortExpression="Total" HeaderStyle-HorizontalAlign="Right" ItemStyle-HorizontalAlign="Right"/>
<asp:BoundField DataField="Products" HeaderText="Products" SortExpression="Products" DataFormatString="{0} product" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left"/>
<asp:BoundField DataField="Units" HeaderText="Units" SortExpression="Units" DataFormatString="{0} units" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left"/>
<asp:BoundField DataField="OrderStatusName" HeaderText="Current Status" SortExpression="OrderStatusName" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left"/>
<asp:BoundField DataField="OrderStatusID" HeaderText="Orderstatusid" Visible="true" />
<asp:BoundField DataField="OrderTracking_ID" HeaderText="TrackingNo" SortExpression="OrderTracking_ID" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left"/>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<%# GetViewOrderLink(Eval("OrderID").ToString(), Eval("OrderState").ToString())%>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Change Status" SortExpression="OrderStatusName">
<ItemTemplate>
<asp:DropDownList ID="OrderStatusDD" runat="server"
DataSourceID="OrdersStatuses" DataTextField="OrderStatusName" DataValueField="OrderStatusID" Visible="false">
</asp:DropDownList>
<asp:SqlDataSource ID="OrdersStatuses" runat="server"
ConnectionString="<%$ ConnectionStrings:SqlConn %>"
SelectCommand="SELECT [OrderStatusID], [OrderStatusName] FROM [Orders_Statuses] where OrderStatusID = 2 or OrderStatusID = 8 ORDER BY [OrderStatusName]">
</asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField ButtonType="Button" Text="Update status" Visible="false" HeaderText="Change Status" />
</Columns>
</asp:GridView>
PS I have the onrowCommand set on the gridview to listen to button click in gridview
You need to create RowCreated event for the gridview example
Before the GridView control can be rendered, a GridViewRow object must be created for each row in the control. The RowCreated event is raised when each row in the GridView control is created. This enables you to provide an event-handling method that performs a custom routine, such as adding custom content to a row, whenever this event occurs.
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
}
OR
<asp:GridView runat="server" ID="GV1" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Age" HeaderText="Age" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" Text="Reject"
Visible='<%# IsOverAgeLimit((Decimal)Eval("Age")) %>'
CommandName="Select"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected Boolean IsOverAgeLimit(Decimal Age) {
return Age > 35M;
}
Reference example
You can use the RowCreated event in the GridView as follows:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
Button btn = (Button) e.Row.Cells[12].Controls[0];
if(1==1)
{
btn.Visible = true;
}
}
((BoundField)grv_selec.Columns[1]).DataFormatString = "{0:N2}";

multiple select buttons in gridview

I'm trying to create multiple select buttons in grid view
however I seem to be having some issues
the record is not selected using the code below
<asp:GridView ID="GridView1" runat="server" CssClass="table table-bordered text-nowrap" AutoGenerateColumns="False" DataKeyNames="Qutation_ID" OnRowDeleting="GridView1_RowDeleting" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:BoundField DataField="Qutation_ID" HeaderText="Qutation ID" InsertVisible="False" ReadOnly="True" SortExpression="Qutation_ID" />
<asp:BoundField DataField="CustID" HeaderStyle-CssClass="hiddencol" HeaderText="Customer ID" InsertVisible="False" ItemStyle-CssClass="hiddencol" ReadOnly="True" SortExpression="Qutation_ID">
<HeaderStyle CssClass="hiddencol" />
<ItemStyle CssClass="hiddencol" />
</asp:BoundField>
<asp:BoundField DataField="Type" HeaderText="Type" SortExpression="Type" />
<asp:BoundField DataField="Subject" HeaderText="Subject" SortExpression="Subject" />
<asp:ButtonField Text="Click" CommandName="ActionCommand" ItemStyle-Width="30" />
</Columns>
<EmptyDataTemplate>
"No records found"
</EmptyDataTemplate>
</asp:GridView>
protected void ActionCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "ActionCommand")
{
msg.Text = GridView1.SelectedRow.Cells[1].Text;
}
}

Delete row using gridview_rowdeleting event

I'm trying to delete a row in Grid View programmatically
I have created this GridView
<asp:GridView ID="GridView1" CssClass="HeaderTables" runat="server" AllowPaging="True"
EmptyDataText="There is no data record to display"
AllowSorting="True" AutoGenerateColumns="false"
CellPadding="0" Height="0px" Width="800px"
onpageindexchanging="GridView1_PageIndexChanging"
onsorting="GridView1_Sorting" onrowdeleting="GridView1_RowDeleting">
<Columns>
<asp:BoundField DataField="first_name" HeaderText="First name"/>
<asp:BoundField DataField="last_name" HeaderText="Last name"/>
<asp:BoundField DataField="mobile_phone" HeaderText="Mobile number"/>
<asp:BoundField DataField="email" HeaderText="Email"/>
<asp:BoundField DataField="city" HeaderText="City"/>
<asp:BoundField DataField="street_number" HeaderText="Street number"/>
<asp:CommandField ShowEditButton="True" ButtonType="Button" />
<asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
</Columns>
<HeaderStyle HorizontalAlign="Left" />
<RowStyle HorizontalAlign="Left" />
</asp:GridView>
and my code behind is:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
if (MessageBox.Show("Are you sure you want to delete this data?",
"Confirm delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["mySqlString"].ConnectionString);
MySqlCommand cmd = new MySqlCommand("DELETE FROM persons WHERE id = #id", conn);
MySqlParameter param = new MySqlParameter();
try
{
int rowID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
cmd.Parameters.AddWithValue("#id", rowID);
conn.Open();
cmd.ExecuteNonQuery();
GridView1.DataBind();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
I'm getting the error:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Your grid doesn't set the DataKeyNames property, so this grid isn't tracking any datakeys. Probably thats why you are getting an index error.
You should set the DataKeyNames property. In your code you also need to check to make sure the collection contains elements.The datakeys collection itself may not be null, but it can contain zero elements.
Use DataKeyNames="ID" like
<asp:GridView ID="GridView1" CssClass="HeaderTables" runat="server" AllowPaging="True"
EmptyDataText="There is no data record to display" DataKeyNames="ID"
AllowSorting="True" AutoGenerateColumns="false"
CellPadding="0" Height="0px" Width="800px"
onpageindexchanging="GridView1_PageIndexChanging"
onsorting="GridView1_Sorting" onrowdeleting="GridView1_RowDeleting">
<Columns>
<asp:BoundField DataField="first_name" HeaderText="First name"/>
<asp:BoundField DataField="last_name" HeaderText="Last name"/>
<asp:BoundField DataField="mobile_phone" HeaderText="Mobile number"/>
<asp:BoundField DataField="email" HeaderText="Email"/>
<asp:BoundField DataField="city" HeaderText="City"/>
<asp:BoundField DataField="street_number" HeaderText="Street number"/>
<asp:CommandField ShowEditButton="True" ButtonType="Button" />
<asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
</Columns>
<HeaderStyle HorizontalAlign="Left" />
<RowStyle HorizontalAlign="Left" />
</asp:GridView>
Then it will work for you
Your forgot to add DataKeyNames to your gridview
DataKeyNames="Valid Column Name" //Column name here instead of Valid Column name
Full Code below :
<asp:GridView ID="GridView1" DataKeyNames="Valid Column Name" CssClass="HeaderTables" runat="server" AllowPaging="True"
EmptyDataText="There is no data record to display"
AllowSorting="True" AutoGenerateColumns="false"
CellPadding="0" Height="0px" Width="800px"
onpageindexchanging="GridView1_PageIndexChanging"
onsorting="GridView1_Sorting" onrowdeleting="GridView1_RowDeleting">
<Columns>
<asp:BoundField DataField="first_name" HeaderText="First name"/>
<asp:BoundField DataField="last_name" HeaderText="Last name"/>
<asp:BoundField DataField="mobile_phone" HeaderText="Mobile number"/>
<asp:BoundField DataField="email" HeaderText="Email"/>
<asp:BoundField DataField="city" HeaderText="City"/>
<asp:BoundField DataField="street_number" HeaderText="Street number"/>
<asp:CommandField ShowEditButton="True" ButtonType="Button" />
<asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
</Columns>
<HeaderStyle HorizontalAlign="Left" />
<RowStyle HorizontalAlign="Left" />
</asp:GridView>

Categories