AIM: Design an application to Retrive data from Database using SqlDataReader(Sql Server).
Source Code :
// Main Page
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 WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
sqlConnection1.Open();
sqlCommand1.Connection = sqlConnection1;
sqlCommand1.CommandText = "insert into student values('" + textBox1.Text + "','" + textBox2.Text + "','" + comboBox1.Text + "','" + textBox3.Text + "','" + textBox4.Text + "')";
sqlCommand1.ExecuteNonQuery();
MessageBox.Show("Data Inserted");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
sqlConnection1.Close();
}
private void searchToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 f = new Form2();
f.Show();
}
}
}
// Search Page
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;
namespace WindowsFormsApplication2
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form3 o = new Form3(textBox1.Text);
o.Show();
this.Hide();
}
}
}
// Data Page
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 WindowsFormsApplication2
{
public partial class Form3 : Form
{
SqlDataReader dr;
String roll;
public Form3()
{
InitializeComponent();
}
public Form3(String str)
{
roll = str;
InitializeComponent();
}
private void Form3_Load(object sender, EventArgs e)
{
try
{
sqlConnection1.Open();
sqlCommand1.Connection = sqlConnection1;
sqlCommand1.CommandText = "select * from student where roll=roll";
dr = sqlCommand1.ExecuteReader();
while (dr.Read())
{
label6.Text = dr.GetValue(0).ToString();
label7.Text = dr.GetValue(1).ToString();
label8.Text = dr.GetValue(2).ToString();
label9.Text = dr.GetValue(3).ToString();
label10.Text = dr.GetValue(4).ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
sqlConnection1.Close();
}
}
}
Output: