public partial class Form1 : Form
{
string strCon;
SqlConnection sqlCon;
public Form1()
{
InitializeComponent();
}
private void Label1_Click(object sender, EventArgs e)
{
}
private void DBConnect()
{
//编写数据库连接字符串
strCon = "server = 'Dolphin-pc';database = 'scoreMIS';uid ='sa'; pwd ='******' ;";
//新建SQL SERVER 连接
sqlCon = new SqlConnection(strCon);
}
//刷新显示数据
private void ComonDataView()
{
try
{
DBConnect();
//创建适配器
SqlDataAdapter da = new SqlDataAdapter("select ID as 学号, name as 姓名 , class as 班级 from students", sqlCon);
//创建数据集
DataSet ds = new DataSet();
da.Fill(ds, "tablename");
dataGridView1.DataSource = ds.Tables[0];
cbID.DisplayMember = "学号";
cbID.ValueMember = "学号";
cbID.DataSource = ds.Tables[0].DefaultView;
}
catch (SystemException ex)
{
MessageBox.Show("错误:" + ex.Message, "错误提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}
finally
{
if (sqlCon.State == ConnectionState.Open)
{
sqlCon.Close();
sqlCon.Dispose();
}
}
}
//加载
private void Form1_Load(object sender, EventArgs e)
{
ComonDataView();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
DBConnect();
sqlCon.Open();
SqlCommand cmd = new SqlCommand("insert into students values ('" + cbID.Text + "', '" + tbName.Text + "', '" + tbClass.Text + "')", sqlCon);
cmd.ExecuteNonQuery();
sqlCon.Close();
ComonDataView();
}
catch (SystemException ex)
{
MessageBox.Show("错误:" + ex.Message, "错误提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}
}
private void button3_Click(object sender, EventArgs e)
{
try
{
DBConnect();
sqlCon.Open();
SqlCommand cmd = new SqlCommand("delete from students where ID = '" + cbID.Text +"'", sqlCon);
cmd.ExecuteNonQuery();
sqlCon.Close();
ComonDataView();
}
catch (SystemException ex)
{
MessageBox.Show("错误:" + ex.Message, "错误提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
DBConnect();
sqlCon.Open();
SqlCommand cmd = new SqlCommand("UPDATE students SET ID = '"+ cbID.Text + "', name = '"
+ tbName.Text + "',class = '" + tbClass.Text + "' WHERE ID = '"+ cbID.Text + "'", sqlCon);
cmd.ExecuteNonQuery();
sqlCon.Close();
ComonDataView();
}
catch (SystemException ex)
{
MessageBox.Show("错误:" + ex.Message, "错误提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}
}
}
https://m.sciencenet.cn/blog-465809-483282.html
上一篇:
Word如何去掉正文边框下一篇:
Photoshop如何加水印