Sagar Seela

Sagar Seela

  • NA
  • 4
  • 552

How to solve System.OutOfRange exception for below code

Jun 5 2019 2:58 AM

 // Sorce Code  //

using System.Data;
using System.Data.SqlClient;
 
namespace ASPNET
{
public partial class company : System.Web.UI.Page
{
DataSet ds;
int RowIndex=0;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Database=SagarDB;Integrated Security=SSPI");
SqlDataAdapter da = new SqlDataAdapter("Select ID,FirstName,LastName,Gender,Salary from company", con);
ds = new DataSet();
ShowData();
da.Fill(ds, "company");
Session["CDS"] = ds;
Session["RowIndex"] = RowIndex;
}
else
{
ds = (DataSet)Session["CDS"];
RowIndex = (int)Session["RowIndex"];
}
}
private void ShowData()
{
txtId.Text = ds.Tables[0].Rows[RowIndex]["ID"].ToString();
txtFName.Text = ds.Tables[0].Rows[RowIndex]["FirstName"].ToString();
txtLName.Text= ds.Tables[0].Rows[RowIndex]["LastName"].ToString();
txtGender.Text= ds.Tables[0].Rows[RowIndex]["Gender"].ToString();
txtSalary.Text= ds.Tables[0].Rows[RowIndex]["Salary"].ToString();
}
protected void btnFirst_Click(object sender, EventArgs e)
{
RowIndex = 0;
ShowData();
Session["RowIndex"] = RowIndex;
}
protected void btnPrev_Click(object sender, EventArgs e)
{
if(RowIndex>0)
{
RowIndex -= 1;
ShowData();
Session["RowIndex"] = RowIndex;
}
else
{
Response.Write("<script>alert('First Record of table')</script>");
}
}
protected void btnNext_Click(object sender, EventArgs e)
{
if(RowIndex<ds.Tables[0].Rows.Count-1)
{
RowIndex += 1;
ShowData();
Session["RowIndex"] = RowIndex;
}
else
{
Response.Write("<script>alert('Last Record of table')</script>");
}
}
protected void btnLast_Click(object sender, EventArgs e)
{
RowIndex = ds.Tables[0].Rows.Count - 1;
ShowData();
Session["RowIndex"] = RowIndex;
}
}
}

Answers (2)