AIM: Design an application to Retrive data from Database using SqlDataAdapter and DataSet (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 WindowsFormsApplication3
{
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 button2_Click(object sender, EventArgs e)
{
Form2 f = new Form2();
f.Show();
}
}
}
// Table Data
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 WindowsFormsApplication3
{
public partial class Form2 : Form
{
int i;
SqlDataAdapter da;
DataSet ds = new DataSet();
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
sqlConnection1.Open();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
da = new SqlDataAdapter("select * from student", sqlConnection1);
da.Fill(ds);
if (ds.Tables[0].Rows.Count != 0)
{
label6.Text = ds.Tables[0].Rows[i].ItemArray[0].ToString();
label7.Text = ds.Tables[0].Rows[i].ItemArray[1].ToString();
label8.Text = ds.Tables[0].Rows[i].ItemArray[2].ToString();
label9.Text = ds.Tables[0].Rows[i].ItemArray[3].ToString();
label10.Text = ds.Tables[0].Rows[i].ItemArray[4].ToString();
}
i++;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
sqlConnection1.Close();
}
}
}
Output: