基本信息
源码名称:WinFrom DataGridView增删查改
源码大小:0.06M
文件格式:.zip
开发语言:C#
更新时间:2016-06-18
友情提示:(无需注册或充值,赞助后即可获取资源下载链接)
嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300
本次赞助数额为: 2 元×
微信扫码支付:2 元
×
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
源码介绍
1.先创建 名为 Sample 的sql server数据库
2. 执行Script.sql脚本
3. 打开解决方案后,即可对 datagridview 进行 增删改查
using System; using System.Data; using System.Windows.Forms; using System.Data.SqlClient; namespace InsertUpdateDeleteDemo { public partial class frmMain : Form { SqlConnection con= new SqlConnection("Data Source=.;Initial Catalog=Sample;Integrated Security=true;"); SqlCommand cmd; SqlDataAdapter adapt; //ID variable used in Updating and Deleting Record int ID = 0; public frmMain() { InitializeComponent(); DisplayData(); } //Insert Data private void btn_Insert_Click(object sender, EventArgs e) { if (txt_Name.Text != "" && txt_State.Text != "") { cmd = new SqlCommand("insert into tbl_Record(Name,State) values(@name,@state)", con); con.Open(); cmd.Parameters.AddWithValue("@name", txt_Name.Text); cmd.Parameters.AddWithValue("@state", txt_State.Text); cmd.ExecuteNonQuery(); con.Close(); MessageBox.Show("Record Inserted Successfully"); DisplayData(); ClearData(); } else { MessageBox.Show("Please Provide Details!"); } } //Display Data in DataGridView private void DisplayData() { con.Open(); DataTable dt=new DataTable(); adapt=new SqlDataAdapter("select * from tbl_Record",con); adapt.Fill(dt); dataGridView1.DataSource = dt; con.Close(); } //Clear Data private void ClearData() { txt_Name.Text = ""; txt_State.Text = ""; ID = 0; } //dataGridView1 RowHeaderMouseClick Event private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { ID = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString()); txt_Name.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString(); txt_State.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString(); } //Update Record private void btn_Update_Click(object sender, EventArgs e) { if (txt_Name.Text != "" && txt_State.Text != "") { cmd = new SqlCommand("update tbl_Record set Name=@name,State=@state where ID=@id", con); con.Open(); cmd.Parameters.AddWithValue("@id", ID); cmd.Parameters.AddWithValue("@name", txt_Name.Text); cmd.Parameters.AddWithValue("@state", txt_State.Text); cmd.ExecuteNonQuery(); MessageBox.Show("Record Updated Successfully"); con.Close(); DisplayData(); ClearData(); } else { MessageBox.Show("Please Select Record to Update"); } } //Delete Record private void btn_Delete_Click(object sender, EventArgs e) { if(ID!=0) { cmd = new SqlCommand("delete tbl_Record where ID=@id",con); con.Open(); cmd.Parameters.AddWithValue("@id",ID); cmd.ExecuteNonQuery(); con.Close(); MessageBox.Show("Record Deleted Successfully!"); DisplayData(); ClearData(); } else { MessageBox.Show("Please Select Record to Delete"); } } } }