C# 将更新从datagrid查看器传递回sql server

C# 将更新从datagrid查看器传递回sql server,c#,sql,C#,Sql,我在私有void中声明了一个sqladapter,我无法将其引用到更新void中。 谁能告诉我应该在哪里声明它,这样它就可以在整个脚本中使用吗 SqlAdapter称为sqlDataAdap sqladapter在GetList void中声明,然后需要在此处调用,但无法引用 private void UpdateRowToDatabase() { if (LastDataRow!=null) { if (LastDataRow.RowState==

我在私有void中声明了一个sqladapter,我无法将其引用到更新void中。 谁能告诉我应该在哪里声明它,这样它就可以在整个脚本中使用吗

SqlAdapter称为sqlDataAdap

sqladapter在GetList void中声明,然后需要在此处调用,但无法引用

 private void UpdateRowToDatabase() {
        if (LastDataRow!=null) {
          if (LastDataRow.RowState==
              DataRowState.Modified) {
            sqlDataAdap.Update(LastDataRow);
          }
        }
      }
为帮助干杯-再次成为一名新手很难! 戴夫


您需要:dtRecord.AcceptChanges();好的,谢谢-我需要在哪里添加它?当您想将数据保存回数据库时。我的意思是代码中的确切位置。我是C#的新手,所以请耐心等待。将dt的定义从方法内部移动到方法外部。表将成为类的属性。您需要:dtRecord.AcceptChanges();好的,谢谢-我需要在哪里添加它?当您想将数据保存回数据库时。我的意思是代码中的确切位置。我是C#的新手,所以请耐心等待。将dt的定义从方法内部移动到方法外部。表将成为类的属性。
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data;
using System;
using System.Data.SqlClient; //For SQL Connection



namespace Reference_Table_Updater
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
           this.Load += Form1_Load;
        }


    void GetList()
        {

        String strConnection = "server=myserver';" +
                   "Database='Scratchpad';" +
                   "Integrated Security=SSPI";

        SqlConnection con = new SqlConnection(strConnection);

        SqlCommand sqlCmd = new SqlCommand();

        sqlCmd.Connection = con;
        sqlCmd.CommandType = CommandType.Text;
        sqlCmd.CommandText = "Select * from dbo.UPDATE_Test";
        SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);

        DataTable dtRecord = new DataTable();
        sqlDataAdap.Fill(dtRecord);
        dataGridView1.DataSource = dtRecord;
        dataGridView1.Refresh();
        //con.Close();

    }

    private void Form1_Load(object sender, EventArgs e)

    {            
        GetList();
    }

       private DataRow LastDataRow = null;


  private void UpdateRowToDatabase() {
    if (LastDataRow!=null) {
      if (LastDataRow.RowState==
          DataRowState.Modified) {
        sqlDataAdap.Update(LastDataRow);
      }
    }
  }

  private void regionBindingSource_PositionChanged(
    object sender, EventArgs e) 
  {

BindingSource thisBindingSource = 
  (BindingSource)sender;
DataRow ThisDataRow=
  ((DataRowView)thisBindingSource.Current).Row;
if (ThisDataRow==LastDataRow) {

  throw new ApplicationException("It seems the" +
    " PositionChanged event was fired twice for" + 
    " the same row");
}

UpdateRowToDatabase();

LastDataRow = ThisDataRow;
  }

  private void MainForm_FormClosed(
    object sender, FormClosedEventArgs e) 
  {
    UpdateRowToDatabase();
  }
}
    }