C#新手,关于bindingnavigator中添加一个SaveButton保存的问题?
我用的VS2008,在winform中,拖入控件datagridview1,bindingnavigator1,并在bindingnavigator中设置了一个textbox1和一个button1,
代码如下,已经可以实现在textbox1中搜索并把结果在dataGridView1中显示:
private void button1_Click(object sender, EventArgs e)
//String ConnectionString = global::LogisticsInfoSys.Properties.Settings.Default.ConnectionString;
//SqlConnection MyConnection = new SqlConnection(conn);
SqlConnection conn = BaseClass.DBConn.MainConn();
conn.Open();
string MySQL = "Select * From tb_Master Where iCarOrder LIKE '" + this.textbox1.Text + "'";
DataTable MyMsaterTable = new DataTable();
SqlDataAdapter tb_MasterTableAdapter = new SqlDataAdapter(MySQL, conn);
tb_MasterTableAdapter.Fill(MyMsaterTable);
this.dataGridView1.DataSource = MyMsaterTable;
if (conn.State == ConnectionState.Open)
conn.Close();
问题是,我想在bindingnavigator中又添加一个SaveButton,想实现datagridview中直接修改数据后保存,在MSDN官方上的解决答案是如下代码:
private void SaveButton_Click(System.Object sender,
System.EventArgs e)
TableAdapterName.Update(DataSetName.TableName);
如它的格式我试了N次,我几天都搞不定,请能帮助我。谢谢!!
谢谢:xinshoushanglua的代码,还有GTX280的提醒,
原来是需要this.validate ,呵呵,现在结贴。
private void btnUpdate_Click(object sender, EventArgs e)
sda.Update((DataTable)bs.DataSource); /////写回数据库
我是直接在datagridview1里直接编辑的里面搜索出的数据,修改后点的btnUpdate保存,然后再搜索同个数据出来看到数据还是没有变化。这个sda.Update((DataTable)bs.DataSource);需要怎么用?
核心就是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); /////写回数据库
注意:写回数据库时,写入的项要与select时的项一样,如果试图写入查询中没有的项,那么此项的值将为空;