C#通过DataGridView对数据库进行增删改查

C#通过DataGridView对数据库进行增删改查,第1张

(1)增加新的数据行

(2)显示选中行数

(3)修改选中行数据

(1)执行SQL返回受影响的行数的ExecuteNoQuery方法

(2)执行SQL返回查询结果中第一行第一列的值的ExecuteScalar方法

(3)执行SQL返回一个DataTable的ExecuteDataTable方法

(4)执行SQL返回一个SqlDataReader的ExecutedReader方法

实现思路:

实现数据库和datagridview数据连接

实现修改datagridview触发事件,获取更新数据存放在变量里

通过变量的变化实现数据库更新功能。

功能代码:

using System

using System.Collections.Generic

using System.ComponentModel

using System.Data

using System.Drawing

using System.Text

using System.Windows.Forms

using System.Collections

using System.Data.SqlClient

namespace Quanxian

{

public partial class Form2 : Form

{

public Form2()

{

InitializeComponent()

}

private int job_id

private string job_desc

private int min_lvl

private int max_lvl

private void Form2_Load(object sender, EventArgs e)

{

binddatagridview()

}

/// <summary>

/// 绑定Datagridview的方法

/// </summary>

private void binddatagridview()

{

SqlConnection sqlcon = new SqlConnection("server=.uid=sapwd=database=pubs")

SqlDataAdapter sqldap = new SqlDataAdapter("select * from jobs", sqlcon)

DataSet ds = new DataSet()

sqldap.Fill(ds)

this.dataGridView1.DataSource = ds.Tables[0]

}

/// <summary>

/// 编辑单元格后触发

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)

{

if (dataGridView1.Rows.Count >0)

{

job_id = int.Parse (this.dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString())

job_desc = this.dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString()

min_lvl = int.Parse(this.dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString())

max_lvl = int.Parse(this.dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString())

}

}

/// <summary>

/// 修改

/// </summary>

private void button1_Click(object sender, EventArgs e)

{

SqlConnection sqlcon = new SqlConnection("server=.uid=sapwd=database=pubs")

string str = "update jobs set job_desc='" + job_desc + "',min_lvl=" + min_lvl + ",max_lvl=" + max_lvl + " where job_id=" + job_id + ""

SqlCommand sqlcom = new SqlCommand(str,sqlcon)

try

{

sqlcon.Open()

if (sqlcom.ExecuteNonQuery() >0)

MessageBox.Show("保存成功")

else

MessageBox.Show("保存失败!")

}

catch

{

//异常

}

finally

{ sqlcon.Close()}

}

/// <summary>

/// 刷新

/// </summary>

private void button2_Click(object sender, EventArgs e)

{

binddatagridview()

}

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/sjk/9885066.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-03
下一篇 2023-05-03

发表评论

登录后才能评论

评论列表(0条)

保存