In this article we will see how to display records from a database into text boxes using First, Next, Previous and Last Buttons in WPF. I am using the Code-First Approach to create the database in SQL Server. The data displayed in a data grid are taken from the database. I am using buttons to fetch the records from the database (Data Grid) into text boxes in the form of the first record, next record, previous record and last record as shown in the following snapshot.
Now I will explain how all 4 button events work one by one as shown below.
First Button
When you click the first button, the very first records from the data grid will be fetched into the text boxes as shown below.
The code behind for the first button click event is:
private void First_Click(object sender, RoutedEventArgs e)
{
Database DB = new Database();
var query = DB.Products.Select(c => c).FirstOrDefault();
txtName.Text = query.Name;
txtPrice.Text = query.Price.ToString();
textBox1.Text = query.Stock.ToString();
}
Next Button
When you click the next button, the next record of the current record will be fetched into the text boxes. The code behind for the next button click event is:
private void Next_Click(object sender, RoutedEventArgs e)
{
Database DB = new Database();
if (count < (DB.Products.Count() - 1))
{
count++;
var query = DB.Products.OrderBy(t => t.Id).Skip(count).FirstOrDefault();
txtName.Text = query.Name;
txtPrice.Text = query.Price.ToString();
textBox1.Text = query.Stock.ToString();
}
else
{
var query = DB.Products.Select(c => c).FirstOrDefault();
txtName.Text = query.Name;
txtPrice.Text = query.Price.ToString();
textBox1.Text = query.Stock.ToString();
count = 0;
}
}
Previous Button
When you click the previous button, the previous record of the current record will be fetched into the text boxes. The code behind for the previous button click event is:
private void Previo_Click(object sender, RoutedEventArgs e)
{
Database DB = new Database();
count--;
if (count < 0)
{
count = DB.Products.Count();
}
var query = DB.Products.OrderBy(t => t.Id).Skip(count).Take(1);
foreach (var s1 in query)
{
txtName.Text = s1.Name;
txtPrice.Text = s1.Price.ToString();
textBox1.Text = s1.Stock.ToString();
}
}
Last Button
When you click the last button, the last records from the data grid will be fetched into the text boxes. The code behind for the last button is:
private void Last_Click(object sender, RoutedEventArgs e)
{
Database DB = new Database();
count = -1;
var query = DB.Products.OrderByDescending(c => c.Id).FirstOrDefault();
txtName.Text = query.Name;
txtPrice.Text = query.Price.ToString();
textBox1.Text = query.Stock.ToString();
}
Summary
In this article I have explained how first, next, previous and last buttons can fetch records from the database. I have uploaded the source code also. If you have any queries regarding this article then please comment. Thanks for reading my article.