我用C#开发了一个带有SQL数据库的winforms应用程序。一旦我将数据输入表单并按下显示按钮,它就会显示在datagridview上,但是一旦我重新启动应用程序,数据就不会显示在网格上。
这是添加新数据的代码。
if (textBox1.Text != "" && textBox2.Text != "" && textBox3.Text != "")
{
con = new SqlConnection();
con.ConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\shenal.mdf;Integrated Security=True";
cmd = new SqlCommand("insert into [dbo].[user] (Id,username,password) values(@id,@name,@state)", con);
// cmd.CommandText = "insert into [dbo].[user] (Id,username,password) values(@id,@name,@state)";
cmd.Parameters.AddWithValue("@id", textBox1.Text);
cmd.Parameters.AddWithValue("@name", textBox2.Text);
cmd.Parameters.AddWithValue("@state", textBox3.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Inserted Successfully");
}
else {
MessageBox.Show("Please Provide Details!");
}
这是检索它的代码。
con = new SqlConnection();
con.ConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\shenal.mdf;Integrated Security=True";
con.Open();
DataTable dt = new DataTable();
adapt = new SqlDataAdapter("select * from [dbo].[user]", con);
adapt.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();