日期:2014-05-20  浏览次数:20780 次

什么方法能一次把DataGrid中的数据写回到数据库中?
有没有什么方法是直接把DataGrid中的数据不使用循环直接写回到数据库!

断开连接模式都可以!

高手指教哈!

------解决方案--------------------
核心就是SqlDataAdapter+SqlCommandBuilder+BindingSource...

写了个简单的例子,测试通过:

两个按钮,一个 "加载 ",一个 "更新 ",还有一个 "DataGridView "

using System.Data;
using System.Data.SqlClient;

namespace DataGridViewUpdateToDataBase
{
public partial class Form1 : Form
{
private SqlDataAdapter sda = new SqlDataAdapter();
private BindingSource bs = new BindingSource();
public Form1()
{
InitializeComponent();
}

//加载
private void btnLoad_Click(object sender, EventArgs e)
{
DataBind();
}

//数据绑定
private void DataBind()
{
SqlConnection con = new SqlConnection( "server=.;database=student;uid=sa;pwd=0421 ");
sda = new SqlDataAdapter( "select * from studentDetails ", con);
SqlCommandBuilder buider = new SqlCommandBuilder(sda);
DataSet ds = new DataSet();
sda.Fill(ds, "student ");
bs .DataSource =ds.Tables [ "student "];
this.dataGridView1.DataSource = bs;
}

//更新
private void btnUpdate_Click(object sender, EventArgs e)
{
sda.Update((DataTable)bs.DataSource);
}
}
}

------解决方案--------------------
用dataTable當數據源,把dataTable填充進DataGrid,判斷DataRow 的狀態︰
foreach (DataRow dr in ds.Tables[ "ProgramOwnAuthority "].Rows)
{
switch (dr.RowState)
{
case DataRowState.Added:
cmd.CommandText = "insert into ProgramOwnAuthority(programId,authorityId,Description) values(@programId,@authorityId,@Description); ";
cmd.Parameters[ "@programId "].Value = dr[ "programId "];
cmd.Parameters[ "@authorityId "].Value = dr[ "authorityId "];
cmd.Parameters[ "@Description "].Value = dr[ "Description "];
cmd.ExecuteNonQuery();
break;
case DataRowState.Modified:
cmd.CommandText = "update ProgramOwnAuthority set Description=@Description where programId=@programId and authorityId=@authorityId ";
cmd.Parameters[ "@programId "].Value = dr[ "programId "];
cmd.Parameters[ "@authorityId "].Value = dr[ "authorityId "];
cmd.Parameters[ "@Description "].Value = dr[ "Description "];
cmd.ExecuteNonQuery();
break;
case DataRowState.Deleted:
//dr.RejectChanges();
dr.Delete();
cmd.CommandText = "delete from ProgramOwnAuthority where programId=@programId and authorityId=@authorityId ";
cmd.Parameters[ "@programId "].Value = dr[ "programId ", DataRowVersion.Original];
cmd.Parameters[ "@authorityId "].Value = dr[ "authorityId ", DataRowVersion.Original];