aSPX.CS
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
string strConnString = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(strConnString))
{
int selectedRow = GridView1.SelectedIndex;
GridViewRow theRow = GridView1.Rows[selectedRow];
string str = ("Delete TDLoanRate where Id=@id");
SqlCommand insert = new SqlCommand(str, con);
insert.Parameters.AddWithValue("@id", Convert.ToInt32(theRow.Cells[0].Text));
using (SqlDataAdapter sda = new SqlDataAdapter())
{
insert.Connection = con;
con.Open();
sda.SelectCommand = insert;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
con.Open();
}
}
Aspx.net
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" Width="371px" PageSize="5" AllowSorting="True" onsorting="GridView1_Sorting" OnRowDeleting="OnRowDeleting">
<Columns>
<asp:BoundField DataField="Id" HeaderText="id" SortExpression="Id" />
<asp:BoundField DataField="LoanType" HeaderText="LoanType" SortExpression="LoanType" />
<asp:BoundField DataField="LoanTerm" HeaderText="Term(Years)" SortExpression="LoanTerm" />
<asp:BoundField DataField="LoanRate" HeaderText="LoanRate" SortExpression="LoanRate" />
<asp:BoundField DataField="LoanEffectFrom" HeaderText="Loan Effect From" SortExpression="LoanEffectFrom" />
<asp:BoundField DataField="LoanMaturity" HeaderText="Loan Maturity Date" SortExpression="LoanMaturity" />
<asp:CommandField HeaderText="Edit" SelectText="Edit" ShowSelectButton="True" />
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" ShowHeader="True" />
</Columns>
</asp:GridView>
Index was out of range. Must be non-negative and less than the size of the collection in below line.
int selectedRow = GridView1.SelectedIndex;