Display data from database to textbox and navigate data Next,Prev,First,Last using csharp

26/04/2017   10:44:08 AM

Hello,in this c# tutorial i will explain how to display data from sql server database to textboxes in csharp.then how to navigate data in to textboxes i.e move from first record to next and onwoards.and back to previous record.also search data and move to last and first record directly.

 

1 .Create a database name as Test.Create a Table name as Car in this database.

Column Name

Data Types

Id

Int [Identity Property Set =True]

CarName

varchar(50)

CarSpeed

varchar(50)

 

2. Open VisualStudio.Net /  Select C# / Windows Application

 

3. Make the design of the form as Follows.

4.Add following code for display data to textbox and navigate data to next,prev,last,first and search data

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace DisplayRecordTextboxNavigate
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection c = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=Test;Integrated Security=True");
SqlDataAdapter da;
DataSet ds;
int R;
 
private void Form1_Load(object sender, EventArgs e)
{
da = new SqlDataAdapter("Select * From Car", c);
ds = new DataSet();
da.Fill(ds, "Car");
Getdata();
}
private void Getdata()
{
 
 
txtId.Text = ds.Tables[0].Rows[R][0].ToString();
txtCarname.Text = ds.Tables[0].Rows[R][1].ToString();
txtcarspeed.Text = ds.Tables[0].Rows[R][2].ToString();
lblrecordstatus.Text = (R + 1) + " OF " + ds.Tables[0].Rows.Count;
}
 
private void btnFirst_Click(object sender, EventArgs e)
{
R = 0;
Getdata();
}
 
private void btnNext_Click(object sender, EventArgs e)
{
if (R == ds.Tables[0].Rows.Count - 1)
{
MessageBox.Show("This is last Record");
}
else
{
R = R + 1;
Getdata();
}
}
 
private void btnPrev_Click(object sender, EventArgs e)
{
if (R == 0)
{
 
MessageBox.Show("This is first record");
}
else
{
R = R - 1;
Getdata();
}
}
 
private void btnLast_Click(object sender, EventArgs e)
{
R = ds.Tables[0].Rows.Count - 1;
Getdata();
}
 
private void btnGoto_Click(object sender, EventArgs e)
{
if (Convert.ToInt32(txtsearchrecord.Text) < 1 || Convert.ToInt32(txtsearchrecord.Text) > ds.Tables[0].Rows.Count)
{
MessageBox.Show("Invalid Id");
}
else
{
R = Convert.ToInt32(txtsearchrecord.Text) - 1;
Getdata();
}
}
}

Output

                   

Support us by Sharing