【问题标题】:Cancel/insert/update not saving to the DB取消/插入/更新不保存到数据库
【发布时间】:2014-04-21 05:30:08
【问题描述】:

我正在研究重现此demo 的 Northwind 数据库。代码没有显示任何错误,但所有插入/更新/删除操作都只是暂时的。如果我下次运行代码时添加记录或取消或更新,表的内容仍然是原始的,没有我在数据库中保存的任何修改。

private static DataTable GetDataTable(string queryString)
  {
      String connString = ConfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].ConnectionString;
       SqlConnection mySqlConnection = new SqlConnection(connString);
       SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
       mySqlDataAdapter.SelectCommand = new SqlCommand(queryString, mySqlConnection);

       DataTable myDataTable = new DataTable();
       mySqlConnection.Open();
       try
       {
            mySqlDataAdapter.Fill(myDataTable);
       }
       finally
       {
            mySqlConnection.Close();
       }

       return myDataTable;
  }

  private DataTable Employees
  {
       get
       {
            object obj = this.Session["Employees"];
            if ((!(obj == null)))
            {
                 return ((DataTable)(obj));
            }
            DataTable myDataTable = new DataTable();
            myDataTable = GetDataTable("SELECT * FROM Employees");
            this.Session["Employees"] = myDataTable;
            return myDataTable;
       }
  }

  protected void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
  {
       this.RadGrid1.DataSource = this.Employees;
       this.Employees.PrimaryKey = new DataColumn[] { this.Employees.Columns["EmployeeID"] };
  }

  protected void RadGrid1_UpdateCommand(object source, GridCommandEventArgs e)
  {
       GridEditableItem editedItem = e.Item as GridEditableItem;
       UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);

       //Prepare new row to add it in the DataSource
       DataRow[] changedRows = this.Employees.Select("EmployeeID = " + editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["EmployeeID"]);

       if (changedRows.Length != 1)
       {
            RadGrid1.Controls.Add(new LiteralControl("Unable to locate the Employee for updating."));
            e.Canceled = true;
            return;
       }

       //Update new values
       Hashtable newValues = new Hashtable();

       newValues["Country"] = (userControl.FindControl("TextBox7") as TextBox).Text;
       newValues["City"] = (userControl.FindControl("TextBox8") as TextBox).Text;
       newValues["Region"] = (userControl.FindControl("TextBox9") as TextBox).Text;
       newValues["HomePhone"] = (userControl.FindControl("HomePhoneBox") as RadMaskedTextBox).Text;
       newValues["BirthDate"] = (userControl.FindControl("BirthDatePicker") as RadDatePicker).SelectedDate.ToString();
       newValues["TitleOfCourtesy"] = (userControl.FindControl("ddlTOC") as DropDownList).SelectedItem.Value;

       newValues["Notes"] = (userControl.FindControl("TextBox1") as TextBox).Text;
       newValues["Address"] = (userControl.FindControl("TextBox6") as TextBox).Text;
       newValues["FirstName"] = (userControl.FindControl("TextBox2") as TextBox).Text;
       newValues["LastName"] = (userControl.FindControl("TextBox3") as TextBox).Text;
       newValues["HireDate"] = (userControl.FindControl("HireDatePicker") as RadDatePicker).SelectedDate.ToString();
       newValues["Title"] = (userControl.FindControl("TextBox4") as TextBox).Text;

       changedRows[0].BeginEdit();
       try
       {
            foreach (DictionaryEntry entry in newValues)
            {
                 changedRows[0][(string)entry.Key] = entry.Value;
            }
            changedRows[0].EndEdit();
            this.Employees.AcceptChanges();
       }
       catch (Exception ex)
       {
            changedRows[0].CancelEdit();

            Label lblError = new Label();
            lblError.Text = "Unable to update Employees. Reason: " + ex.Message;
            lblError.ForeColor = System.Drawing.Color.Red;
            RadGrid1.Controls.Add(lblError);

            e.Canceled = true;
       }
  }

  protected void RadGrid1_InsertCommand(object source, GridCommandEventArgs e)
  {
       UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);

       //Create new row in the DataSource
       DataRow newRow = this.Employees.NewRow();

       //Insert new values
       Hashtable newValues = new Hashtable();

       newValues["Country"] = (userControl.FindControl("TextBox7") as TextBox).Text;
       newValues["City"] = (userControl.FindControl("TextBox8") as TextBox).Text;
       newValues["Region"] = (userControl.FindControl("TextBox9") as TextBox).Text;
       newValues["HomePhone"] = (userControl.FindControl("HomePhoneBox") as RadMaskedTextBox).Text;
       newValues["BirthDate"] = (userControl.FindControl("BirthDatePicker") as RadDatePicker).SelectedDate.ToString();
       newValues["TitleOfCourtesy"] = (userControl.FindControl("ddlTOC") as DropDownList).SelectedItem.Value;

       newValues["Notes"] = (userControl.FindControl("TextBox1") as TextBox).Text;
       newValues["Address"] = (userControl.FindControl("TextBox6") as TextBox).Text;
       newValues["FirstName"] = (userControl.FindControl("TextBox2") as TextBox).Text;
       newValues["LastName"] = (userControl.FindControl("TextBox3") as TextBox).Text;
       newValues["HireDate"] = (userControl.FindControl("HireDatePicker") as RadDatePicker).SelectedDate.ToString();
       newValues["Title"] = (userControl.FindControl("TextBox4") as TextBox).Text;

       //make sure that unique primary key value is generated for the inserted row
       newValues["EmployeeID"] = (int)this.Employees.Rows[this.Employees.Rows.Count - 1]["EmployeeID"] + 1;
       try
       {
            foreach (DictionaryEntry entry in newValues)
            {
                 newRow[(string)entry.Key] = entry.Value;
            }
            this.Employees.Rows.Add(newRow);
            this.Employees.AcceptChanges();
       }
       catch (Exception ex)
       {
            Label lblError = new Label();
            lblError.Text = "Unable to insert Employees. Reason: " + ex.Message;
            lblError.ForeColor = System.Drawing.Color.Red;
            RadGrid1.Controls.Add(lblError);

            e.Canceled = true;
       }
  }
  protected void RadGrid1_DeleteCommand(object source, GridCommandEventArgs e)
  {
       string iD = (e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["EmployeeID"].ToString();
       DataTable employeeTable = this.Employees;
       if (employeeTable.Rows.Find(iD) != null)
       {
            employeeTable.Rows.Find(iD).Delete();
            employeeTable.AcceptChanges();
       }
  }

为什么我的插入/删除/更新只是暂时的并且在当前会话中可见?如何解决此问题以插入/更新/删除更改数据库中的数据?

【问题讨论】:

  • 您实际上是在哪里将数据保存回数据库?
  • @dotNET,是的,我想保存回数据库。

标签: c# asp.net sql-server ado.net


【解决方案1】:

确认Rows.Add()AcceptChanges() 不会向底层数据库写入任何内容。它们只对内存中的数据结构进行操作,例如 DataTables 和 DataSets。要实际保存更改,您必须:

  1. 要么使用TableAdapter.Update() 方法并将您修改后的DataTable 提供给它。
  2. 使用SqlCommand并手动执行UPDATEINSERTDELETE命令。

在将更改发送回数据库之前,您不得致电 AcceptChanges()

【讨论】:

  • 感谢您的解释。我会尽量听从你的建议。但是,如果您可以将我需要制作的模块发布到上述代码中,那么作为一个非常自学的初学者将极大地帮助 e。这将支持我理解如何去做并最终学会它。
  • 我多年来一直使用类型化的数据集来处理这类东西,我建议你走这条路。 VS 和 .NET 可以为您做很多关于这些基本 CRUD 操作的工作。了解 Internet 上的类型化数据集。有无数好的资源可供使用。
  • 谢谢。如果我能做到,我就不会在这里寻求帮助。
猜你喜欢
  • 1970-01-01
  • 2013-09-15
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多