【问题标题】:C# Bound value does not match databaseC# 绑定值与数据库不匹配
【发布时间】:2016-03-02 16:22:27
【问题描述】:

C# VS2010 表单应用程序

我有一个带有 SQL Server 数据库(.mdf 文件)的 C# 项目,其中包括一个 ID 字段、数据类型 int、不允许空值;以便它自动编号。

在我的主表单中,我将表格绑定到绑定源,并将 ID 字段绑定到标签。

所有表单控件和它们的绑定属性都是在属性窗口中制作的,无需代码。

表单包含一个绑定导航器,它有一个 + 按钮(添加记录)。 单击 + 按钮的那一刻,将值 -1 分配给 ID 字段;大概是一个临时值,但这会自动发生,无需任何代码。

然后,当我将绑定控件中的所有值插入到数据库的各自列中时(此代码工作正常),除了由数据库自动分配的 ID(自动递增 int)。 所以这就是绑定控件中的值与数据库中存储的值不匹配的原因。

这使我无法继续创建通过引用 ID 字段来删除记录的方法,因为绑定控件中的值 (-1) 无效,即数据库中不存在此类记录。

我尝试了BindingSource.ResetBindings 方法并刷新了标签,但在退出并重新启动程序之前,该值仍为-1。

我还找到了尝试将 BindingSource.DataSource 设置为 null 然后重新绑定的建议,但是尝试将数据源或数据成员设置为 null 会引发异常。我发现另一个建议将BindingSource.RaiseListChangedEvents 设置为false,但仍然发生异常。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Address_Book
{
    public partial class FormMain : Form
    {

        public FormMain()
        {
            InitializeComponent();
            //***Program Execution***
            fillContactGrid();
        }    
        private void fillContactGrid()
        //This method retrieves and displays all records from ContactInfo
        {         
            //Create a connection to the database
            using (SqlConnection connection = new SqlConnection(Properties.Settings.Default.ContactsConnectionString))
            {               
                //Construct the SQL Query string
                string sqlQuery = "SELECT * FROM ContactInfo";
                //Open the connection
                connection.Open();
                //Pass the query to the database and receive dataset
                SqlDataAdapter dataadapter = new SqlDataAdapter(sqlQuery, connection);
                DataSet ds = new DataSet();               
                dataadapter.Fill(ds, "ContactInfo");
                //Close the connection
                connection.Close();
                //Load the dataset into GridView
                contactsGridView.DataSource = ds;
                contactsGridView.DataMember = "ContactInfo";
            }
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            //Initialize contactsDataSet
            this.contactInfoTableAdapter.Fill(this.contactsDataSet.ContactInfo);
        }

        private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
        {
            disableNavigation();
            //Show save and cancel buttons
            buttonSave.Visible = true;
            buttonCancel.Visible = true;
        }

        private void disableNavigation()
        {
            //Temporarily disable navigator controls
            bindingNavigatorAddNewItem.Enabled = false;
            bindingNavigatorDeleteItem.Enabled = false;
            bindingNavigatorPositionItem.Enabled = false;
            bindingNavigatorMoveFirstItem.Enabled = false;
            bindingNavigatorMoveLastItem.Enabled = false;
            bindingNavigatorMoveNextItem.Enabled = false;
            bindingNavigatorMovePreviousItem.Enabled = false;
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            //Cancel new record entry
            contactInfoBindingSource.RemoveCurrent();
            //Hide save and cancel buttons
            buttonSave.Visible = false;
            buttonCancel.Visible = false;
            enableNavigation();
        }

        private void enableNavigation()
        {
            //Enable navigator controls
            bindingNavigatorAddNewItem.Enabled = true;
            bindingNavigatorDeleteItem.Enabled = true;
            bindingNavigatorPositionItem.Enabled = true;
            bindingNavigatorMoveFirstItem.Enabled = true;
            bindingNavigatorMoveLastItem.Enabled = true;
            bindingNavigatorMoveNextItem.Enabled = true;
            bindingNavigatorMovePreviousItem.Enabled = true;
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            insertNewContact(); 
        }

        private void insertNewContact()
        {       
            using (SqlConnection connection = new SqlConnection(Properties.Settings.Default.ContactsConnectionString))
            {
                //***Construct the SQL Command string
                //Format: INSERT INTO table_name (column1,column2,column3,...) VALUES (value1,value2,value3,...)
                //Command
                string sqlCmd = "INSERT INTO ";
                //Table name
                sqlCmd += @"ContactInfo ";
                //Column names
                sqlCmd += @"(LastName, ";
                sqlCmd += @"FirstName, ";
                sqlCmd += @"Relationship, ";
                sqlCmd += @"Title, ";
                sqlCmd += @"Company, ";
                sqlCmd += @"OfficePhone, ";
                sqlCmd += @"OfficeExtension, ";
                sqlCmd += @"CellPhone, ";
                sqlCmd += @"HomePhone, ";
                sqlCmd += @"Email1, ";
                sqlCmd += @"Email2) ";
                //Values
                sqlCmd += @"VALUES ";
                sqlCmd += @"(@LastName, ";
                sqlCmd += @"@FirstName, ";
                sqlCmd += @"@Relationship, ";
                sqlCmd += @"@Title, ";
                sqlCmd += @"@Company, ";
                sqlCmd += @"@OfficePhone, ";
                sqlCmd += @"@OfficeExtension, ";
                sqlCmd += @"@CellPhone, ";
                sqlCmd += @"@HomePhone, ";
                sqlCmd += @"@Email1, ";
                sqlCmd += @"@Email2)";
                //Open the connection
                connection.Open();
                //Pass the command to the database
                using (SqlCommand command =new SqlCommand(sqlCmd, connection))
                {
                    command.Parameters.Add("@LastName", SqlDbType.NChar).Value = textLastName.Text;
                    command.Parameters.Add("@FirstName", SqlDbType.NChar).Value = textFirstName.Text;
                    command.Parameters.Add("@Relationship", SqlDbType.NChar).Value = textRelationship.Text;
                    command.Parameters.Add("@Title", SqlDbType.NChar).Value = textTitle.Text;
                    command.Parameters.Add("@Company", SqlDbType.NChar).Value = textCompany.Text;
                    command.Parameters.Add("@OfficePhone", SqlDbType.NChar).Value = textOfficePhone.Text;
                    command.Parameters.Add("@OfficeExtension", SqlDbType.NChar).Value = textOfficeExtension.Text;
                    command.Parameters.Add("@CellPhone", SqlDbType.NChar).Value = textCellPhone.Text;
                    command.Parameters.Add("@HomePhone", SqlDbType.NChar).Value = textHomePhone.Text;
                    command.Parameters.Add("@Email1", SqlDbType.NChar).Value = textEmail1.Text;
                    command.Parameters.Add("@Email2", SqlDbType.NChar).Value = textEmail2.Text;
                    try
                    {
                        int rows = command.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                connection.Close();
                buttonSave.Visible = false;
                buttonCancel.Visible = false;                
                enableNavigation();
            }
        }

        private void tabControl1_Selected(object sender, TabControlEventArgs e)
        {
            //Update the binding grid when its tab is selected
            fillContactGrid();
        }
    }
}

【问题讨论】:

  • 你能发布导致异常的代码吗?
  • contactInfoBindingSource.DataSource = null;无法绑定到 DataSource 上的属性或列 ID。
  • 编辑问题并插入该代码,同时插入周围的代码,以便其他用户了解您在做什么 - 以此处发布的代码量为例:stackoverflow.com/questions/35753030/…
  • 我的代码没有问题,问题是绑定到ID列的标签中的值与数据库ID列中存储的实际值不匹配。我需要代码来纠正这个问题,但我在类似帖子中找到的建议都不起作用。
  • stackoverflow.com/questions/22449461/how-to-clear-bindingsourcechecked answer表示将DataSource设置为null,但如上所述,这会抛出并接受。

标签: c# sql-server


【解决方案1】:

这是我所看到的问题:

您正在将数据集绑定到应用程序中的控件。您单击“+”按钮,它会在数据集中生成一个新行并分配默认的 Id 或 -1。然后,您通过insertNewContact 手动插入该数据,但是您从未真正检索发布Id 的数据库并将其应用于您的数据集。如果 Id 字段的值在您的数据集中仍然是 -1,那么您重置绑定的次数并不重要,您也不会从数据库中刷新数据集。

您可以通过多种方式之一来做到这一点。您可以在insertNewContact 之后调用fillContactGrid。或者您可以在查询结束时select @@identity 并手动更新您的数据集。为此,您需要将数据库调用更改为 command.ExecuteScalar()。

无论哪种方式,您都需要以某种方式从数据库中检索新插入的 Id 并更新我们数据集中的相应行。

如果我没记错的话(已经有一段时间了)。仅供参考,这有点骇人听闻,但它展示了这个概念:

地址:sqlCmd += @"; select @@identity";

变化:

int rows = command.ExecuteNonQuery();

到:

int newid = (int)command.ExecuteScalar();
((DataSet)contactsGridView.DataSource).Tables["ContactInfo"].Select("Id = -1")[0].SetField("Id", newId);

【讨论】:

  • fillContactGrid();在我的代码最底部。 Grid 在更新时确实包含正确的 ID 值,但这是因为它是由查询填充的,而不是被绑定的。
  • 我不确定您希望绑定做什么。插入后必须更新数据集中的正确字段,如果这样做,绑定将更新。
  • 对于您的第二个建议,我不知道如何实施。如果您有时间提供更多详细信息,我会很高兴,同时尝试自己遵循您的建议。谢谢!
  • 绑定只是在 ui 控件和您的数据集之间。您的数据集和数据库之间没有绑定,无论如何它并不存在。因此,如果您手动更新数据库(这就是您正在做的事情),您的数据集不知道数据库中的数据发生了变化。
  • 是的,我明白了……这就是为什么我期望 BindingSource.ResetBinding 方法可以工作,但它没有做任何事情。 ResetBinding 被称为解决之前几个类似问题的解决方案,但没有一个表明该方法确实有效....不幸的是。
【解决方案2】:

花了一段时间,但终于找到了问题/解决方案。

在 FormMain_Load 上,Visual Studio 添加了一行来填充我将控件绑定到 BindingSource 时创建的数据适配器;

this.contactInfoTableAdapter.Fill(this.contactsDataSet.ContactInfo);

在完成命令后添加这行代码。ExecuteNonQuery刷新了绑定控件中的数据,并将-1的ID值替换为SQLServer分配的正确值。

非常感谢布赖恩。我从您的帮助中学到了很多新东西,我相信这些东西将来会对我有所帮助。

【讨论】:

  • 这样做会有效地重新查询整个数据集。这不是最好的情况,但我很高兴它起作用了。
猜你喜欢
  • 1970-01-01
  • 2021-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多