Reader Level:
ARTICLE

How to Display Records as First-Next-Previous-Last in a Textboxes Using Windows Application

Posted by Syed Shakeer Articles | Windows Forms C# June 01, 2010
In this article you will know how to display records in a textboxes as First,Next,Previous and Last records.
  • 1
  • 0
  • 63649

HTML clipboard

In this article you will know how to display records in a textboxes as First,Next,Previous and Last records.

For doing this we have to add textboxes and 4 buttons on a Windows form.see below design of windows form containing buttons and textboxes.

image1.gif

Here I am using DataGridvew to show you records present in atable.Bind a Data to the DataGridview.Here i am using MsAccess DataProvider as Odbc client.You can use your own DataProvider in the same way.

Explanation: When the users clicks on 'First Button' ,the first record of a table have to display in a corresponding column textboxe.

Coding for 'First Button':- Double click on 'First Button' and write the below code.

        private void btnfirst_Click(object sender, EventArgs e)
        {
            if (ds.Tables[0].Rows.Count > 0)
            {
                i = 0;
                textBox1.Text = ds.Tables[0].Rows[i]["ID"].ToString();
                textBox2.Text = ds.Tables[0].Rows[i]["empname"].ToString();
                textBox3.Text = ds.Tables[0].Rows[i]["salary"].ToString();
            }
        }

image2.gif

First Button Image

Coding for 'Last Button':- Double click on'Last Button' and write the below code.

        private void btnlast_Click(object sender, EventArgs e)
        {
            i = ds.Tables[0].Rows.Count - 1;
            textBox1.Text = ds.Tables[0].Rows[i]["ID"].ToString();
            textBox2.Text = ds.Tables[0].Rows[i]["empname"].ToString();
            textBox3.Text = ds.Tables[0].Rows[i]["salary"].ToString();

        }

image3.gif

Last Button Image

Coding for 'Next Button':- Double click on'Next Button' and write the below code.

        private void btnnext_Click(object sender, EventArgs e)
        {

            if (i < ds.Tables[0].Rows.Count - 1)
            {
                i++;
                textBox1.Text = ds.Tables[0].Rows[i]["ID"].ToString();
                textBox2.Text = ds.Tables[0].Rows[i]["empname"].ToString();
                textBox3.Text = ds.Tables[0].Rows[i]["salary"].ToString();
            }
            else
            {
                //no records to see more.
            }
        }

image4.gif

Next Button Image

Coding for 'Previous Button':- Double click on'Previous Button' and write the below code.

        private void btnprevious_Click(object sender, EventArgs e)
        {
            if (i == ds.Tables[0].Rows.Count - 1 || i != 0)
            {
                i--;
                textBox1.Text = ds.Tables[0].Rows[i]["ID"].ToString();
                textBox2.Text = ds.Tables[0].Rows[i]["empname"].ToString();
                textBox3.Text = ds.Tables[0].Rows[i]["salary"].ToString();
            }
            else
            {
                //No records to see more
            }
        }

Above ds.Tables[0].Rows.Count means it counts number of records presnt in a table.

The Complete coding in Form1.cs as follows:-

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.Odbc;
using System.IO;
namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        OdbcDataAdapter da;
        DataSet ds;
        int i = 0;
        int j;
        OdbcConnection conn;
        int last;
        private void Form1_Load(object sender, EventArgs e)
        {
            conn = new OdbcConnection("dsn=t1");
            conn.Open();
            da = new OdbcDataAdapter("select * from emp", conn);
            OdbcCommandBuilder builder = new OdbcCommandBuilder(da);
            ds = new DataSet();
            da.Fill(ds, "emp");
            dataGridView1.DataSource = ds.Tables["emp"];
        }

        private void btnfirst_Click(object sender, EventArgs e)
        {
            if (ds.Tables[0].Rows.Count > 0)
            {
                i = 0;
                textBox1.Text = ds.Tables[0].Rows[i]["ID"].ToString();
                textBox2.Text = ds.Tables[0].Rows[i]["empname"].ToString();
                textBox3.Text = ds.Tables[0].Rows[i]["salary"].ToString();
            }
        }
        private void btnlast_Click(object sender, EventArgs e)
        {
            i = ds.Tables[0].Rows.Count - 1;
            textBox1.Text = ds.Tables[0].Rows[i]["ID"].ToString();
            textBox2.Text = ds.Tables[0].Rows[i]["empname"].ToString();
            textBox3.Text = ds.Tables[0].Rows[i]["salary"].ToString();

        }
        private void btnnext_Click(object sender, EventArgs e)
        {
 
            if (i < ds.Tables[0].Rows.Count - 1)
            {
                i++;
                textBox1.Text = ds.Tables[0].Rows[i]["ID"].ToString();
                textBox2.Text = ds.Tables[0].Rows[i]["empname"].ToString();
                textBox3.Text = ds.Tables[0].Rows[i]["salary"].ToString();
            }
            else
            {
            }
        }
        private void btnprevious_Click(object sender, EventArgs e)
        {
            if (i == ds.Tables[0].Rows.Count - 1 || i != 0)
            {
                i--;
                textBox1.Text = ds.Tables[0].Rows[i]["ID"].ToString();
                textBox2.Text = ds.Tables[0].Rows[i]["empname"].ToString();
                textBox3.Text = ds.Tables[0].Rows[i]["salary"].ToString();
            }
            else
            {
            }
        }
    }
}

Thanks for reading my article!

Syed Shakeer Hussain


 

Article Extensions
Contents added by Shah Hussain on Aug 19, 2013
Download File: CSharpNextPre.zip
Hey, i have modified the code original written by Mr. Syed Shakeer Hussain for windows based application: available on
http://www.c-sharpcorner.com/uploadfile/syedshakeer/how-to-display-records-as-first-next-previous-last-in-a-textboxes-using-windows-application/

Title: "How to Display Records as First-Next-Previous-Last in a Textboxes Using Windows Application"

I want to say special thanks to Mr. Syed Shakeer Hussain and hope someone will get help from this.
The complete source code alongwith database and Visual Studio project Solution included in the code attached.
First add reference to mysql.dll and install
Connector/Net
---------------------------------------------------------------------------
First + Next + Previous + Last Records from MySql Database table "World" on aspx page.
---------------------------
Default.aspx page
------------------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" EnableSessionState="True" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .auto-style1 {
            width: 100%;
        }
        .auto-style2 {
            width: 114px;
        }
        .auto-style4 {
            width: 236px;
        }
        .auto-style5 {
            width: 370px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <br />
        <table class="auto-style1">
            <tr>
                <td class="auto-style2">
                    <asp:Label ID="Label1" runat="server" Text="Country Name"></asp:Label>
                </td>
                <td class="auto-style5">
                    <asp:TextBox ID="c_name" runat="server" Width="300px"></asp:TextBox>
                </td>
                <td class="auto-style4">&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td class="auto-style2">
                    <asp:Label ID="Label2" runat="server" Text="Code"></asp:Label>
                </td>
                <td class="auto-style5">
                    <asp:TextBox ID="code" runat="server" Width="300px"></asp:TextBox>
                </td>
                <td class="auto-style4">&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td class="auto-style2">
                    <asp:Label ID="Label3" runat="server" Text="Region"></asp:Label>
                </td>
                <td class="auto-style5">
                    <asp:TextBox ID="region" runat="server" Width="300px"></asp:TextBox>
                </td>
                <td class="auto-style4">&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td class="auto-style2">&nbsp;</td>
                <td class="auto-style5">
                    <asp:Button ID="firstBtn" runat="server" Text="First" OnClick="firstBtn_Click" />
                    <asp:Button ID="nextBtn" runat="server" Text="Next" OnClick="nextBtn_Click" />
                    <asp:Button ID="preBtn" runat="server" Text="Previous" OnClick="preBtn_Click" />
                    <asp:Button ID="lastBtn" runat="server" Height="26px" Text="Last" OnClick="lastBtn_Click" />
                </td>
                <td class="auto-style4">&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
        </table>
        <br />
    <asp:Label ID="msg" runat="server"  Text=""></asp:Label>
        <br />
    
        <asp:GridView ID="GridView1" runat="server" Width="522px">
        </asp:GridView>
    </div>
    </form>
</body>
</html>
-----------------------------------------------------------------------------------
default.aspx.cs
--------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    CRUD crud = new CRUD();
    Int32 i = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        this.GridView1.DataSource = crud.dataTable("SELECT CODE,NAME,Region FROM country");
        this.GridView1.DataBind();
        this.GridView1.Visible = false;
        if (!IsPostBack) { Session["counter"] = 0; }
        if (this.GridView1.Rows.Count > 0)
        {
            i = 0;
            this.c_name.Text = this.GridView1.Rows[i].Cells[1].Text.ToString();
            this.code.Text = this.GridView1.Rows[i].Cells[0].Text.ToString();
            this.region.Text = this.GridView1.Rows[i].Cells[2].Text.ToString();
        }

       }
    protected void firstBtn_Click(object sender, EventArgs e)
    {
        Session["counter"] = 0;
        if (this.GridView1.Rows.Count > 0) {
            i = Int32.Parse(Session["counter"].ToString());
            this.c_name.Text = this.GridView1.Rows[i].Cells[1].Text.ToString();
            this.code.Text = this.GridView1.Rows[i].Cells[0].Text.ToString();
            this.region.Text = this.GridView1.Rows[i].Cells[2].Text.ToString();
        }
    }
    protected void nextBtn_Click(object sender, EventArgs e)
    {
        i = Int32.Parse(Session["counter"].ToString()) + 1;

        if (i < (this.GridView1.Rows.Count - 1)) {
            this.c_name.Text = this.GridView1.Rows[i].Cells[1].Text.ToString();
            this.code.Text = this.GridView1.Rows[i].Cells[0].Text.ToString();
            this.region.Text = this.GridView1.Rows[i].Cells[2].Text.ToString();
            Session["counter"] = Int32.Parse(Session["counter"].ToString()) + 1;
        }
    }
    protected void preBtn_Click(object sender, EventArgs e)
    {
        if (!Session["counter"].Equals(null) && !Session["counter"].Equals(0))
        {
            i = Int32.Parse(Session["counter"].ToString()) - 1;
        }
        else {
            i = Int32.Parse(Session["counter"].ToString());       
        }
        if (i < (this.GridView1.Rows.Count - 1))
        {
            this.c_name.Text = this.GridView1.Rows[i].Cells[1].Text.ToString();
            this.code.Text = this.GridView1.Rows[i].Cells[0].Text.ToString();
            this.region.Text = this.GridView1.Rows[i].Cells[2].Text.ToString();
            Session["counter"] = Int32.Parse(Session["counter"].ToString()) - 1;
        }
    }
    protected void lastBtn_Click(object sender, EventArgs e)
    {
        if (this.GridView1.Rows.Count > 0)
        {
            Session["counter"] = this.GridView1.Rows.Count - 1;
            i = Int32.Parse(Session["counter"].ToString());
            this.c_name.Text = this.GridView1.Rows[i].Cells[1].Text.ToString();
            this.code.Text = this.GridView1.Rows[i].Cells[0].Text.ToString();
            this.region.Text = this.GridView1.Rows[i].Cells[2].Text.ToString();
        }
    }
}
---------------------------------------------------------------------------------------------------------
web.config
----------------------
<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5"/>
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <connectionStrings>
    <remove name="localSqlServer"/>
    <add name="conStr" connectionString="Server=localhost; Database=world; Uid=root; Pwd=thefire;"/>
  </connectionStrings>
</configuration>
-------------------------------------------------------------------------------------------------
Class file which includes Database connectivity and other important methods
--------------------
CRUD.cs
-------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Xml.Linq;
using System.Data;
using System.Data.Odbc;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text;
using MySql.Data.MySqlClient;

/// <summary>
/// Summary description for CRUD
/// </summary>
public class CRUD
{
    //private OdbcConnection con;
    private MySqlConnection con;
    //private OdbcCommand cmd;
    private MySqlCommand cmd;
    private MySqlDataAdapter oda;
    private MySqlDataReader odr;
    private DataTable dt;
    private DataSet ds;

    public CRUD()
    {
        //default constructor
    }
    /// <summary>
    /// void connect()
    /// This method is responsible to connect to database via connectionString from web.config file
    /// </summary>
    private void connect()
    {
        try
        {
            con = new MySqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
        }
        catch (Exception exc)
        {
            catchError(exc);
        }
    }
    /// <summary>
    /// void closeCon()
    /// this method is responsible to close connection to database.
    /// </summary>
    private void closeCon()
    {
        try
        {
            if (con.State == ConnectionState.Open)
            {
                con.Close();
            }
        }
        catch (Exception exc)
        {
            catchError(exc);
        }
    }
    /// <summary>
    /// bool search(string sql)
    /// </summary>
    /// <param name="sql">sql query as parameter</param>
    /// <returns>return true if record greater than 0</returns>
    public bool search(string sql)
    {
        bool flag = false;
        try
        {
            connect();
            cmd = new MySqlCommand(sql, con);
            object result = cmd.ExecuteScalar();
            if (result != null)
            {
                flag = true;
            }
            //if (cmd.ExecuteNonQuery() > 0) {
            //    flag = true;
            //}
        }
        catch (Exception exc)
        {
            catchError(exc);
        }
        finally
        {
            try
            {
                closeCon();
            }
            catch (Exception excf)
            {
                catchError(excf);
            }
        }
        return flag;
    }
    /// <summary>
    /// bool insert(string sql)
    /// </summary>
    /// <param name="sql">sql query to insert record to table(s)</param>
    /// <returns></returns>
    public bool insert(string sql)
    {
        bool flag = false;
        try
        {
            connect();
            cmd = new MySqlCommand(sql, con);
            if (cmd.ExecuteNonQuery() > 0)
            {
                flag = true;
            }
        }
        catch (Exception exc)
        {
            catchError(exc);
        }
        finally
        {
            try
            {
                closeCon();
            }
            catch (Exception excf)
            {
                catchError(excf);
            }
        }
        return flag;
    }
    public bool delete(string sql)
    {
        bool flag = false;
        try
        {
            connect();
            cmd = new MySqlCommand(sql, con);
            if (cmd.ExecuteNonQuery() > 0)
            {
                flag = true;
            }
            else
            {
                flag = false;
            }
        }
        catch (Exception exc)
        {
            catchError(exc);
        }
        finally
        {
            try
            {
                closeCon();
            }
            catch (Exception excc)
            {
                catchError(excc);
            }
        }
        return flag;
    }
    /// <summary>
    /// DataTable dataTable(string sql)
    /// </summary>
    /// <param name="sql">sql query as parameter</param>
    /// <returns>Returns Filled or Empty DataTable</returns>
    public DataTable dataTable(string sql)
    {
        try
        {
            connect();
            dt = new DataTable();
            oda = new MySqlDataAdapter(sql, con);
            oda.Fill(dt);
        }
        catch (Exception exc)
        {
            catchError(exc);
        }
        finally
        {
            try
            {
                closeCon();
            }
            catch (Exception excf)
            {
                catchError(excf);
            }
        }
        return dt;
    }
    /// <summary>
    /// OdbcCommand getRecordSet(string sql)
    /// </summary>
    /// <param name="sql"> sql query</param>
    /// <returns>OdbcCommand</returns>
    public MySqlCommand getRecordSet(string sql)
    {
        try
        {
            connect();
            cmd = new MySqlCommand(sql, con);
            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            catchError(ex);
        }
        return cmd;
    }//getRecordSet();

    public string getValue(string sql, string fld)
    {
        try
        {
            connect();
            cmd = new MySqlCommand(sql, con);
            cmd.ExecuteNonQuery();
            odr = cmd.ExecuteReader();
            if (odr.Read())
            {
                fld = odr[fld].ToString();
            }
            else
            {
                fld = "";
            }
        }
        catch (Exception exc)
        {
            catchError(exc);
        }
        finally
        {
            try
            {
                closeCon();
            }
            catch (Exception excc)
            {
                catchError(excc);
            }
        }
        return fld;
    }

    /// <summary>
    /// void catchError(Exception object)
    /// </summary>
    /// <param name="ex">Error Handelor</param>
    public void catchError(Exception ex)
    {
        try
        {
            //send Exception details in email
        }
        catch (Exception exc)
        {
            catchError(exc);
        }
    }
    /// <summary>
    /// bool checkLogin(string,string,string)
    /// </summary>
    /// <param name="userid">session[userid]</param>
    /// <param name="userkey">session[password]</param>
    /// <param name="sno">session[std_sno]</param>
    /// <returns>if three parems are correctly available it will return true otherwise, false</returns>
    public bool checkLogin(string userid, string userkey, string std_id)
    {
        bool flag = false;
        try
        {
            if (string.IsNullOrEmpty(userid) || string.IsNullOrWhiteSpace(userid) || string.IsNullOrEmpty(userkey) || string.IsNullOrWhiteSpace(userkey) || string.IsNullOrEmpty(std_id) || string.IsNullOrWhiteSpace(std_id))
            {
                flag = false;
            }
            else
            {
                flag = true;
            }
        }
        catch (Exception exc)
        {
            catchError(exc);
        }
        return flag;
    }

    /// <summary>
    /// StringBuilder stringBuilder(string,string,string,string)
    /// </summary>
    /// <param name="sql">sql Query to select data from table</param>
    /// <param name="separator">Separator may be html code, i.e. 'br /' , hr or it could be any symbol like ^, & * etc for string.replace() or string.split() </param>
    /// <param name="fld_1">fld_1 is The table Field/Column Name, Required to return value from</param>
    /// <param name="fld_2">fld_2 is The table Field/Column Name, Optional to return value from</param>
    /// <param name="fld_3">fld_3 is The table Field/Column Name, Optional to return value from</param>
    /// <returns>StringBuilder object, need to val.toString() when use</returns>
    public StringBuilder stringBuilder(string sql, string separator, string fld_1, string fld_2 = "", string fld_3 = "")
    {
        StringBuilder sb = new StringBuilder();
        try
        {
            connect();
            cmd = new MySqlCommand(sql, con);
            cmd.ExecuteNonQuery();
            odr = cmd.ExecuteReader();
            if (odr.HasRows)
            {
                while (odr.Read())
                {
                    sb.Append(odr[fld_1].ToString());
                    if (!string.IsNullOrWhiteSpace(fld_2))
                    {
                        sb.Append(separator);//flag for separator
                        sb.Append(odr[fld_2].ToString());
                    }//if
                    else if (!string.IsNullOrWhiteSpace(fld_3))
                    {
                        sb.Append(separator);//flag for separator
                        sb.Append(odr[fld_3].ToString());
                    }//else if
                    else
                    {
                        sb.Append(separator);//flag for separator
                    }//else
                }//while()
            }//if odr.HasRows
        }//try
        catch (Exception ex)
        {
            catchError(ex);
        }
        return sb;
    }//getRecordSet();

}
--------------------------------------------------------------------------------------------------------
Please contact me on shahhussain305@gmail.com.
Thanks.
COMMENT USING

Trending up