首先建立如下图所示的控制台窗体:
编写代码:
using System;
using System.Collections.Generic;
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;
namespace APPTRY1029
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
LoadData();
}
private void label2_Click(object sender, EventArgs e)
{
}
private void label3_Click(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void LoadData()
{
List<Classinfo> list = new List<Classinfo>();
string str = "Data Source=ECUST-GLOBAL;Initial Catalog=dbtest;Integrated Security=true ";
using (SqlConnection con=new SqlConnection(str))
{
string sql = "select *from ClassInfo";
using (SqlCommand cmd=new SqlCommand(sql,con))
{
con.Open();
using (SqlDataReader reader=cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
Classinfo model = new Classinfo();
model.Cid = reader.GetInt32(0);
model.Classname = reader.GetString(1);
model.ClassDesc = reader.GetString(2);
list.Add(model);
}
}
}
}
}
this.dataGridView1.DataSource = list;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace APPTRY1029
{
public class Classinfo
{
public int Cid { get; set; }
public string Classname { get; set; }
public string ClassDesc { get; set; }
}
}
结果如下:
点击按钮插入数据:
private void button1_Click(object sender, EventArgs e)
{
int r = 0;
string className = ClassName.Text.Trim();
string classdesc = Miaoshu.Text.Trim();
string str = "Data Source=ECUST-GLOBAL;Initial Catalog=dbtest;Integrated Security=true ";
using (SqlConnection con = new SqlConnection(str))
{
string sql = string.Format("insert ClassInfo values (N'{0}',N'{1}') ", className, classdesc);
using (SqlCommand cmd = new SqlCommand(sql, con))
{
con.Open();
r = cmd.ExecuteNonQuery();
}
}
if (r>0)
{
this.Text = "插入成功";
LoadData();
}
}
点击按钮删除数据:
private void button3_Click(object sender, EventArgs e)
{
int r = 0;
int clssid = Convert.ToInt32(textcid.Text);
string str = "Data Source=ECUST-GLOBAL;Initial Catalog=dbtest;Integrated Security=true ";
using (SqlConnection con = new SqlConnection(str))
{
string sql = string.Format("delete ClassInfo where cId={0} ", clssid);
using (SqlCommand cmd = new SqlCommand(sql, con))
{
con.Open();
r = cmd.ExecuteNonQuery();
this.Text = "删除了" + r + "条数据";
LoadData();
}
}
}
结果显示: