Associate
- Joined
- 23 Oct 2005
- Posts
- 201
- Location
- North London
Here is a starter for you. I am using SessionState to store the current record index and the dataset, so that you dont need to keep your connection to the database open while you are browsing forward/backwards through records:-
Code:
public partial class _Default : System.Web.UI.Page
{
private DataSet dataSet;
private int currentRow = 0;
private const string RecordIndexSessionName = "RecordIndex";
private const string DataSetSessionName = "Workers";
protected void Page_Load(object sender, EventArgs e)
{
// If it is the first time that the page is loaded, set up the sql connection
if (!Page.IsPostBack)
{
string sqlConnectionString = DataSource=@".\SQLEXPRESS; AttachDbFilename =C:\\MyWorkers.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
string sqlQuery = "SELECT * FROM tblWorkers";
dataSet = new DataSet();
System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection();
sqlConnection.ConnectionString = sqlConnectionString;
// Open the SQL connection
sqlConnection.Open();
// Create the new sql dat adapter instance
System.Data.SqlClient.SqlDataAdapter sqlDataAdapter = new System.Data.SqlClient.SqlDataAdapter(sqlQuery, sqlConnection);
sqlDataAdapter.Fill(dataSet, DataSetSessionName);
// Once the dataset is filled, close the connection
sqlConnection.Close();
// Add the dataset to the session state
Session[DataSetSessionName] = dataSet;
}
else
{
// Get the current row pointer from session state
if (Session.Contents[RecordIndexSessionName] != null)
{
currentRow = Convert.ToInt32(Session[RecordIndexSessionName]);
}
// Get the dataset from session state
if (Session.Contents[DataSetSessionName] != null)
{
dataSet = Session[DataSetSessionName] as DataSet;
}
}
NavigateRecords();
}
protected void NavigateRecords()
{
DataRow dRow = dataSet.Tables[DataSetSessionName].Rows[currentRow];
TextBox1.Text = dRow.ItemArray.GetValue(0).ToString();
TextBox2.Text = dRow.ItemArray.GetValue(1).ToString();
TextBox3.Text = dRow.ItemArray.GetValue(2).ToString();
}
protected void btnPrevious_Click(object sender, EventArgs e)
{
if (currentRow > 0)
{
currentRow--;
Session[RecordIndexSessionName] = currentRow;
NavigateRecords();
}
}
protected void btnNext_Click(object sender, EventArgs e)
{
if (currentRow != dataSet.Tables[DataSetSessionName].Rows.Count - 1)
{
currentRow++;
Session[RecordIndexSessionName] = currentRow;
NavigateRecords();
}
}
}