datagridview 添加数据库数据

 private void btnadd_Click(object sender, EventArgs e)
        {
            string str = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Test;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
            SqlConnection sqlConnection = new SqlConnection(str);
            sqlConnection.Open();
            string Sql = String.Format("insert into Student(Age, Name) values('{0}','{1}')", txtAge.Text, txtName.Text);
            SqlCommand sqlCommand = new SqlCommand(Sql, sqlConnection);
            sqlCommand.ExecuteNonQuery();
            sqlConnection.Close();
            this.dataGridView1.DataSource = null;
            load();
        }
        public void load()
        {
            string str = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Test;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
            SqlConnection sqlConnection = new SqlConnection(str);
            sqlConnection.Open();
            string sql = "select * from Student";
            SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, sqlConnection);
            DataSet dataSet = new DataSet();
            dataAdapter.Fill(dataSet);
            this.dataGridView1.DataSource = dataSet.Tables[0].DefaultView;
            sqlConnection.Close();
        }

 

posted @ 2019-03-15 16:32  JackJu  阅读(2082)  评论(0编辑  收藏  举报