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.Configuration;
using System.Data.SqlClient;
namespace savedata
{
public partial class Form1 : Form
{
SqlConnection con
= newSqlConnection(ConfigurationManager.ConnectionStrings["Sqlcon"].ConnectionString);
public Form1()
{
InitializeComponent();
Bind();
}
private void Clear()
{
txtName.Text
= string.Empty;
txtLocation.Text
= string.Empty;
}
private void btnSave_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd
= new SqlCommand("Insert
Into Test_Data(Name,Location) Values (@Name,@Location)",
con);
cmd.Parameters.AddWithValue("Name",
txtName.Text);
cmd.Parameters.AddWithValue("Location",
txtLocation.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Inserted
sucessfully");
Bind();
Clear();
}
private void Bind()
{
con.Open();
SqlDataAdapter da
= new SqlDataAdapter("select
* from Test_Data", con);
DataTable dt
= new DataTable();
da.Fill(dt);
dataGridView1.DataSource
= dt;
con.Close();
}
private void btnDelete_Click(object sender, EventArgs e)
{
SqlCommand delcmd
= new SqlCommand();
if (dataGridView1.Rows.Count
> 1 && dataGridView1.SelectedRows[0].Index !=
dataGridView1.Rows.Count - 1)
{
delcmd.CommandText
= "DELETE FROM Test_Data WHERE ID=" +
dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "";
con.Open();
delcmd.Connection
= con;
delcmd.ExecuteNonQuery();
con.Close();
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
MessageBox.Show("Row
Deleted");
}
Bind();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd
= new SqlCommand("Update
Test_Data set Name=@Name,Location=@Location Where(Name=@Name)",
con);
cmd.Parameters.AddWithValue("@Name",
txtName.Text);
cmd.Parameters.AddWithValue("@Location",
txtLocation.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("updated......");
con.Close();
Bind();
Clear();
}
private void btnEdit_Click_1(object sender, EventArgs e)
{
int i;
i
= dataGridView1.SelectedCells[0].RowIndex;
txtName.Text
= dataGridView1.Rows[i].Cells[1].Value.ToString();
txtLocation.Text
= dataGridView1.Rows[i].Cells[2].Value.ToString();
}
}
}
Then run the
application you will get output like below:

No comments:
Post a Comment