using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace DataGridViewDemo
{
public partial class DataGridViewCustomPaint : Form
{
SqlConnection sqlConn;
SqlDataAdapter sqlDa;
DataSet sqlDs;
public DataGridViewCustomPaint()
{
InitializeComponent();
}
private void DataGridViewCustomPaint_Load(object sender,
EventArgs e)
{
sqlConn = new SqlConnection("Data
Source=.;Initial Catalog=jwinfo;Integrated
Security=True;");
sqlDa = new SqlDataAdapter("SELECT * FROM
学生信息", sqlConn);
sqlDs = new DataSet();
sqlDa.Fill(sqlDs, "学生信息");
dataGridView1.DataSource = sqlDs.Tables["学生信息"];
//然后用SqlCommandBuilder自动为SqlDataAdapter生成Insert、Update、Delete命令
SqlCommandBuilder sqlCmdBuilder = new
SqlCommandBuilder(sqlDa);
}
//更新
private void button1_Click(object sender,
EventArgs e)
{
if (sqlDs.HasChanges())
{
try
{
sqlDa.Update(sqlDs.Tables["学生信息"]);
sqlDs.Tables["学生信息"].AcceptChanges();
MessageBox.Show("更新成功!",
"操作结果",MessageBoxButtons.OK, MessageBoxIcon.Information
);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "更新失败!",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
//删除
private void button2_Click(object sender,
EventArgs e)
{
//删除首先要定位到当前选中的记录
int delRowIndex = dataGridView1.CurrentRow.Index;
if (delRowIndex != -1)
this.dataGridView1.Rows.RemoveAt(delRowIndex);
//然后调用保存按钮保存删除操作
button1.PerformClick();
}
}
}
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace DataGridViewDemo
{
}