【发布时间】: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