public partial class Form1 : Form
{
private string connString = ConfigurationManager.ConnectionStrings["connstring"].ToString();
SqlConnection conn ;
DataSet ds = new DataSet();
private int actionFlag = 0;
SqlCommandBuilder scb;
SqlDataAdapter sda;
public Form1()
{
InitializeComponent();
LoadData();
dgvStudent.DataSource = null;
dgvStudent.DataSource = ds.Tables["student"];
txtSNO.Text = dgvStudent.Rows[0].Cells[0].Value.ToString();
txtSName.Text = dgvStudent.Rows[0].Cells[1].Value.ToString();
groupBox1.Enabled = false;
}
private void LoadData()
{
conn = new SqlConnection(connString);
string sql = "select SNO,SName from Student";
SqlCommand cmd = new SqlCommand(sql, conn);
sda = new SqlDataAdapter(cmd);
sda.SelectCommand = cmd;
//实例化sqlCommandBuild对象
scb = new SqlCommandBuilder(sda);
conn.Open();
sda.Fill(ds, "student");
conn.Close();
ds.Tables["student"].PrimaryKey = new DataColumn[] {ds.Tables["student"].Columns["SNO"] };
}
private void dgvStudent_SelectionChanged(object sender, EventArgs e)
{
if (dgvStudent.Rows.Count == 0) return;
txtSNO.Text = dgvStudent.CurrentRow.Cells[0].Value.ToString();
txtSName.Text = dgvStudent.CurrentRow.Cells[1].Value.ToString();
}
private void btnAdd_Click(object sender, EventArgs e)
{
actionFlag = 1;
groupBox1.Enabled = true;
txtSNO.Text = string.Empty;
txtSNO.Focus();
txtSName.Text = string.Empty;
}
private void btnUpdate_Click(object sender, EventArgs e)
{
actionFlag = 2;
groupBox1.Enabled = true;
txtSNO.Enabled = false;
}
private void btnCommit_Click(object sender, EventArgs e)
{
groupBox1.Enabled = false;
switch (actionFlag)
{
case 1:
DataRow dr = ds.Tables["student"].NewRow();
dr["SNO"] = txtSNO.Text.Trim().ToString();
dr["SName"] = txtSName.Text.Trim().ToString();
ds.Tables["student"].Rows.Add(dr);
break;
case 2:
dr = ds.Tables["student"].Rows.Find(txtSNO.Text.Trim());
if (dr != null)
{
dr.BeginEdit();
dr["SName"] = txtSName.Text.Trim();
dr.EndEdit();
txtSNO.Enabled = true;
}
break;
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
string sno = txtSNO.Text.Trim();
string sql = "delete from student where SNO=" + sno;
ds.Tables["student"].Rows.Find(sno).Delete();
}
private void button1_Click(object sender, EventArgs e)
{
//打开连接
conn.Open();
//更新到数据库
sda.Update(ds,"student");
MessageBox.Show("更新成功!");
//关闭
conn.Close();
}
}