Thursday, June 16, 2011

Program to retrieve data from a table

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormsApplication1

   public partial class Form1 : Form
{
   public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{

 SqlCommand cmd = new SqlCommand(" select * from EMP where ENAME='" + textBox1.Text + "'",cn);
 SqlDataReader dr = cmd.ExecuteReader();
cn.Open();
dr.Read();
if (dr.HasRows)
{
label2.Text = dr["DESIG"].ToString();
label3.Text = dr["SAL"].ToString();
}
if (!dr.HasRows)
{
MessageBox.Show("ERROR IN RETRIEVING","Error Message"MessageBoxButtons.OKCancel ,  MessageBoxIcon.Warning,  MessageBoxDefaultButton.Button1);
}
}
}
}

connection string can be found in database properties

example of a connection string

("Data Source=.\\SQLEXPRESS;AttachDbFilename= C:\\Users\\manish\\Documents\\niist.mdf; Integrated Security=True;Connect Timeout=30;User Instance=True")SqlConnection cn = new SqlConnection("PASTE CONNECTION STRING HERE");