sb.Append("update stunits set stucode=@stucode,spcode=@spcode,ctcode=@ctcode,stunits=@stunits where stucode=‘" + this.Listv.SelectedItems[0].Text + "‘ ");
using (SqlConnection con = new SqlConnection("server=.;uid=sa;pwd=system;database=jtyyhis"))
dapt.UpdateCommand.Parameters.Add("@stucode", SqlDbType.VarChar, 10);
dapt.UpdateCommand.Parameters.Add("@spcode", SqlDbType.VarChar, 10);
dapt.UpdateCommand.Parameters.Add("@ctcode", SqlDbType.VarChar, 10);
dapt.UpdateCommand.Parameters.Add("@stunits", SqlDbType.VarChar, 40);
private void btnAdd_Click(object sender, EventArgs e)
{
if (this.textBox1.Text == string.Empty)
{
MessageBox.Show("代码不能为空", "提示");
}
else
{
using (SqlConnection con = new SqlConnection(constring))
{
//con.Open();
StringBuilder sb = new StringBuilder();
sb.Append("insert into stunits(stucode,spcode,ctcode,stunits) values(@dm,@pym,@dym,@stunit)");
dapt = new SqlDataAdapter();
//产生一个新行
DataRow dr = ds.Tables[0].NewRow();
dr[0] = this.textBox1.Text;
dr[1] = this.textBox2.Text;
dr[2] = this.textBox3.Text;
dr[3] = this.textBox4.Text;
//将新行添加到ds.Tables[0].Rows中
ds.Tables[0].Rows.Add(dr);
SqlCommand cmd = new SqlCommand(sb.ToString(), con);
cmd.Parameters.Add("@dm", SqlDbType.VarChar, 10, "stucode");
cmd.Parameters.Add("@pym", SqlDbType.VarChar, 20, "spcode");
cmd.Parameters.Add("@dym", SqlDbType.VarChar, 20, "ctcode");
cmd.Parameters.Add("@stunit", SqlDbType.VarChar, 40, "stunits");
dapt.InsertCommand = cmd;
//dapt.InsertCommand = new SqlCommand(sb.ToString(), con);
//dapt.InsertCommand.Parameters.Add("@dm", SqlDbType.Int,10,"stucode");
//dapt.InsertCommand.Parameters.Add("@pym", SqlDbType.VarChar,20,"spcode");
//dapt.InsertCommand.Parameters.Add("@dym", SqlDbType.VarChar,20,"ctcode");
//dapt.InsertCommand.Parameters.Add("@stunit",SqlDbType.VarChar,40,"stunits");
try
{
dapt.Update(ds, "stunit");
MessageBox.Show("添加成功");
}
catch (ArgumentNullException ex)
{
MessageBox.Show(ex.Message);
}
catch (SqlException ex1)
{
MessageBox.Show(ex1.Message);
}
}
4)删除操作
private void btnDele_Click(object sender, EventArgs e)
{
//ds = new DataSet();
using (SqlConnection con = new SqlConnection(constring))
{
//con.Open();
StringBuilder sb = new StringBuilder();
sb.Append("delete stunits where stucode=‘" + this.listView1.SelectedItems[0].Text + "‘");
SqlCommand cmd = new SqlCommand(sb.ToString(), con);
dapt = new SqlDataAdapter();
dapt.DeleteCommand = cmd;
int index = this.listView1.SelectedIndices[0];//得到选中行的索引
ds.Tables["stunit"].Rows[index].Delete();//改变行的状态
//try
//{
// int Count = cmd.ExecuteNonQuery();
// if (Count > 0) MessageBox.Show("删除成功", "提示");
//}
//catch (SqlException ex)
//{
// MessageBox.Show(ex.Message);
//}
if (ds.HasChanges(DataRowState.Deleted))
{
try
{
dapt.Update(ds, "stunit");
MessageBox.Show("删除成功", "提示");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message, "提示");