我終於得到了連接字符串的工作。現在我已經寫了一些代碼來插入Customers
表中的Database.mdf
表中。當我單擊表單中的「註冊表」按鈕時,我將名稱TF2插入到表中,然後我調用ShowCustomers
方法重新加載列表框。重新運行c後數據未保存在SQL Server數據庫中#
當我重新運行程序時,它仍顯示先前在列表框中創建名稱,但仍不顯示服務器資源管理器中的名稱。
代碼:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ProductClient.ProductService;
using TestDB;
using System.Configuration;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
ProductServiceClient productProxy = new ProductServiceClient();
SqlConnection connection;
string connectionString;
public Form1()
{
InitializeComponent();
connectionString = ConfigurationManager.ConnectionStrings["TestDB.Properties.Settings.DatabaseConnectionString"].ConnectionString;
ShowCustomers();
}
private void ShowCustomers()
{
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Customer", connection))
{
DataTable productTable2 = new DataTable();
adapter.Fill(productTable2);
lstBox.DisplayMember = "Name";
lstBox.ValueMember = "Id";
lstBox.DataSource = productTable2;
}
}
private void registreerBTN_Click(object sender, EventArgs e)
{
string response = productProxy.Register(usernameTF2.Text);
wachtwoordLAB.Text = response;
string query = "INSERT INTO Customer VALUES(@Name, 20)"; ////
using (connection = new SqlConnection(connectionString))////
using (SqlCommand command = new SqlCommand(query, connection))////
{
connection.Open();
command.Parameters.AddWithValue("@Name",usernameTF2.Text);////
command.ExecuteNonQuery();
MessageBox.Show("Added");
connection.Close();
}
ShowCustomers();
}
}
}
的Copy to Output Directory
已設置爲Copy if newer
。
的ConnectionString:
形式:
connectionString = ConfigurationManager.ConnectionStrings["TestDB.Properties.Settings.DatabaseConnectionString"].ConnectionString;
在應用程序配置:
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True"
您需要告訴我們您的連接字符串是什麼;如果您有密碼,請輸入您的密碼。 –
你刷新了服務器資源管理器嗎? – wonderbell
在窗體中:connectionString = ConfigurationManager.ConnectionStrings [「TestDB.Properties.Settings.DatabaseConnectionString」]。ConnectionString; 在app config:connectionString =「Data Source =(LocalDB)\ v11.0; AttachDbFilename = | DataDirectory | \ Database.mdf; Integrated Security = True」 – Elvira