日期:2014-05-18 浏览次数:20848 次
DataTable dt = dataGridView1.DataSource as DataTable;//把DataGridView绑定的数据源转换成DataTable foreach (DataRow row in dt.Rows) { //根据行的状态决定对数据库接行什么操作 switch (row.RowState) { case DataRowState .Added: //把这一行添加回数据库 break; case DataRowState.Deleted: //把数据库里的这一行删除 break; case DataRowState.Modified: //更新数据库里的该条记录 break; } }
------解决方案--------------------
以下是我自己使用的一个 DBObject.cs类使用方法很简单.使用了OleDb数据库接口,
在初始化的时候,
DBObject db=new DBObject(你的数据库连接字符串);
string sql="select * from A where A1=1";
DataTable dt=db.GetTable(sql);
接下来对dt进行操作
dt.rows[0][1]="1" 设置第1行的第2列内容为1...
等等...
最后,要保存到数据库的时候,调用
db.UpdateDB(sql,dt);即可
using System; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Configuration; using System.Web; /// <summary> /// Summary description for DBObject /// </summary> namespace Ben3.Core { public class DBObject { private string connString; private SqlConnection conn; private SqlCommand cmd; private SqlCommandBuilder cb; private DataSet ds; private SqlDataAdapter da; private SqlDataReader dr; public DBObject(string connectionString) { if (connectionString.IndexOf(";") >= 0) connString = connectionString; else { ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings[connectionString]; connString = (settings.ConnectionString); } } public DBObject() { ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["dbConnectionString"]; connString = (settings.ConnectionString); } public int RunSql(string sqlString) { using (conn = new SqlConnection(connString)) { conn.Open(); cmd = new SqlCommand(sqlString, conn); return cmd.ExecuteNonQuery(); } } public object RunSql2(string sqlString) { using (conn = new SqlConnection(connString)) { conn.Open(); cmd = new SqlCommand(sqlString, conn); try { return cmd.ExecuteScalar(); } catch { return (object)0; } } } public string RunSql(string sqlString, int columnID) { using (conn = new SqlConnection(connString)) { conn.Open(); cmd = new SqlCommand(sqlString, conn); dr = cmd.ExecuteReader(); if (!dr.Read()) return "#"; else return dr[columnID].ToString(); } } public string RunSql(string sqlString, string columnName) { using (conn = new SqlConnection(connString)) { conn.Open(); cmd = new SqlCommand(sqlString, conn); dr = cmd.ExecuteReader(); if (!dr.Read()) return "#"; else return dr[colum