在DataGridView中修改后的数据如何保存到数据库
vs2005,在DataGridView中修改后,点击button,如何把数据保存到数据库中,需要详细代码,C#,谢谢!...
vs2005,在DataGridView中修改后,点击button,如何把数据保存到数据库中,需要详细代码,C#,谢谢!
展开
1个回答
2013-10-30
展开全部
namespace DategridviewToSQL
{
public partial class Form1 : Form
{
private DataTable DT = new DataTable();
private SqlDataAdapter SDA = new SqlDataAdapter();
private Boolean isUpdate = false;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
load();
}
private void load()
{
SqlConnection conn = new SqlConnection(@"server = (local)\\SQL2005;Integrated Security = true;" + "DataBase = test1");
SqlCommand SCD = new SqlCommand("select * from aaa ", conn);
SDA.SelectCommand = SCD;
SDA.Fill(DT);
dataGridView1.DataSource = DT;
}
private void button1_Click(object sender, EventArgs e)
{
if (isUpdate)
{
try
{
SqlCommandBuilder SCB = new SqlCommandBuilder(SDA);
SDA.Update(DT);
isUpdate = false;
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
return;
}
MessageBox.Show("更新成功! ");
}
else
{
MessageBox.Show("没有更新内容! ");
}
for (int i = 0; i < DT.Rows.Count; i++)
for (int j = 0; j < DT.Columns.Count; j++ )
{
dataGridView1[j, i].Style.BackColor = Color.White;
}
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
isUpdate = true;
dataGridView1[e.ColumnIndex,e.RowIndex].Style.BackColor = Color.Blue;
}
自己写的一个小实例,连接一个数据库,取了一个表显示,里面的链接语句可以根据你自己的数据库修改。试试看
{
public partial class Form1 : Form
{
private DataTable DT = new DataTable();
private SqlDataAdapter SDA = new SqlDataAdapter();
private Boolean isUpdate = false;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
load();
}
private void load()
{
SqlConnection conn = new SqlConnection(@"server = (local)\\SQL2005;Integrated Security = true;" + "DataBase = test1");
SqlCommand SCD = new SqlCommand("select * from aaa ", conn);
SDA.SelectCommand = SCD;
SDA.Fill(DT);
dataGridView1.DataSource = DT;
}
private void button1_Click(object sender, EventArgs e)
{
if (isUpdate)
{
try
{
SqlCommandBuilder SCB = new SqlCommandBuilder(SDA);
SDA.Update(DT);
isUpdate = false;
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
return;
}
MessageBox.Show("更新成功! ");
}
else
{
MessageBox.Show("没有更新内容! ");
}
for (int i = 0; i < DT.Rows.Count; i++)
for (int j = 0; j < DT.Columns.Count; j++ )
{
dataGridView1[j, i].Style.BackColor = Color.White;
}
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
isUpdate = true;
dataGridView1[e.ColumnIndex,e.RowIndex].Style.BackColor = Color.Blue;
}
自己写的一个小实例,连接一个数据库,取了一个表显示,里面的链接语句可以根据你自己的数据库修改。试试看
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询