Fetch Data from Table in C# 5

Fetching data from a table in C Sharp is quite easy. It First of all requires creating a connection to the database in the form of a connection string that provides an interface to the database with our development environment. We create a temporary DataTable for storing the database records for faster retrieval as retrieving from the database time and again could have an adverse effect on the performance. To move contents of the SQL database in the DataTable we need a DataAdapter. Filling of the table is performed by the Fill() function. Finally the contents of DataTable can be accessed by using a double indexed object in which the first index points to the row number and the second index points to the column number starting with 0 as the first index. So, if you have 3 rows in your table then they would be indexed by row numbers 0 , 1 & 2.

using System;
using System.Data.SqlClient;

namespace Data_Fetch_In_Table.Net
    public partial class Form1 : Form
        public Form1()

        SqlConnection con = new SqlConnection(@"Data
        Source=.\SQLEXPRESS; AttachDbFilename=” + Application.StartupPath.ToString() +
        “\\Database1.mdf; Integrated Security=True; User Instance=True");

        SqlDataAdapter adapter = new SqlDataAdapter();
        SqlCommand cmd = new SqlCommand();
        DataTable dt = new DataTable();
        private void Form1_Load(object sender, EventArgs e)
            SqlDataAdapter adapter = new SqlDataAdapter("select * from Table1",con);
            adapter.SelectCommand.Connection.ConnectionString = @"Data
            Source=.\SQLEXPRESS; AttachDbFilename=” Application.StartupPath.ToString() + 
                     "\\Database1.mdf;Integrated Security=True; User Instance=True");


        private void button1_Click(object sender, EventArgs e)

            Int16 x = Convert.ToInt16(textBox1.Text);
            Int16 y = Convert.ToInt16(textBox2.Text);

            string current =dt.Rows[x][y].ToString();



Please Note :
** Do not Copy & Paste code written here ; instead type it in your Development Environment
** Testing done in .Net Framework 4.5 but code should be very similar for previous versions of .Net
** All Program Codes here are  100%  tested & running.  

Custom Search