查询删除页面
public partial class WebForm1 : System.Web.UI.Page
{
public string connStr = ConfigurationManager.ConnectionStrings["test"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
Init();
}
protected void Init()
{
GridView1.DataSource = GetData("select * from student");
GridView1.DataBind();
}
public DataTable GetData(string sql,params SqlParameter[] parameters)
{
using (SqlConnection conn=new SqlConnection(connStr))
{
conn.Open();
using(SqlCommand cmd=conn.CreateCommand())
{
cmd.CommandText = sql;
foreach(SqlParameter parameter in parameters )
{
cmd.Parameters.Add(parameter);
}
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(ds);
return ds.Tables[0];
}
}
}
public int ExecuteNonQuery(string sql, params SqlParameter[] parameters)
{
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
foreach (SqlParameter parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
return cmd.ExecuteNonQuery();
}
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
int id = Convert.ToInt32(GridView1.DataKeys[e.NewEditIndex].Value.ToString());
string url = "WebForm2.aspx?id=" + id;
Response.Redirect(url);
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int id=Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
string sql = "delete from student where id=@id";
ExecuteNonQuery(sql,new SqlParameter("id",id));
Init();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
Init();
}
}
添加修改页面
public partial class WebForm2 : System.Web.UI.Page
{
public string connStr = ConfigurationManager.ConnectionStrings["test"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.QueryString["id"] != null)
{
}
else
{
this.txtName.Text = "";
this.txtNumber.Text = "";
}
}
}
protected void insertData()
{
string sql = "insert into student(number,name) values(@number,@name)";
ExecuteNonQuery(sql,new SqlParameter("number",txtNumber.Text.Trim()),new SqlParameter("name",txtName.Text.Trim()));
}
public int ExecuteNonQuery(string sql, params SqlParameter[] parameters)
{
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
foreach (SqlParameter parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
return cmd.ExecuteNonQuery();
}
}
}
protected void submit_Click(object sender, EventArgs e)
{
insertData();
}
}