求高手解决在数据库与数据集中同步删除的行数据问题!!
赵何祺 2012-11-20 09:08:15 用C#编写数据库,在编写删除行这个程序时出现了问题:单按下删除时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.Data.SqlClient;
namespace WindowsApplication6
{
public partial class Form1 : Form
{
string connectionStr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True";
DataSet dataset = new DataSet();
SqlDataAdapter adapter = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(connectionStr);
conn.Open();
SqlCommand cmd=conn.CreateCommand();
cmd.CommandText = "select 学号=No,姓名=Name from Table1";
adapter = new SqlDataAdapter(cmd);
adapter.Fill(dataset);
dataGridView1.DataSource = dataset.Tables[0];
textBox1.DataBindings.Add("Text", dataset.Tables[0], "学号");
textBox2.DataBindings.Add("Text", dataset.Tables[0], "姓名");
//textBox2.Text =Convert.ToString (dataGridView1.CurrentRow.Index);
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult MsgBoxResult;//设置对话框的返回值
MsgBoxResult = MessageBox.Show("是否要修改数据","提示",MessageBoxButtons.YesNo,MessageBoxIcon.Warning,MessageBoxDefaultButton.Button1);
if (MsgBoxResult == DialogResult.Yes)//如果对话框的返回值是YES(按"Y"按钮)
{
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.Update(dataset.Tables[0]);
}
if (MsgBoxResult == DialogResult.No)//如果对话框的返回值是NO(按"N"按钮)
{
return;
}
}
private void button2_Click(object sender, EventArgs e)
{
DialogResult dialogresult;
dialogresult= MessageBox.Show("是否要删除","提示",MessageBoxButtons.YesNo,MessageBoxIcon.Warning,MessageBoxDefaultButton.Button2);
if(dialogresult==DialogResult.Yes)
{
dataset.Tables[0].Rows.RemoveAt(dataGridView1.CurrentRow.Index);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.Update(dataset.Tables[0]);
}
else
{
return;
}
}
}
}
顺便补充下:我已经在program.cs的Main函数下加了下面这段代码:
string dataDir = AppDomain.CurrentDomain.BaseDirectory;
if (dataDir.EndsWith(@"\bin\Debug\")
|| dataDir.EndsWith(@"\bin\Release\"))
{
dataDir = System.IO.Directory.GetParent(dataDir).Parent.Parent.FullName;
AppDomain.CurrentDomain.SetData("DataDirectory", dataDir);
}
所以应给不会是这段代码没加引起的。