asp.net删除一行数据
前台的代码:注意没有使用sqldatasource
- <asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="6" OnRowDeleting="GridView1_deleting"
- AutoGenerateColumns="False" DataKeyNames="用户名" Width="819px">
- <Columns>
- <asp:BoundField DataField="用户名" HeaderText="用户名" ReadOnly="True"
- SortExpression="用户名" />
- <asp:BoundField DataField="密码" HeaderText="密码" SortExpression="密码" />
- <asp:BoundField DataField="性别" HeaderText="性别" SortExpression="性别" />
- <asp:BoundField DataField="出生时间" HeaderText="出生时间" SortExpression="出生时间" />
- <asp:BoundField DataField="联系方式" HeaderText="联系方式" SortExpression="联系方式" />
- <asp:BoundField DataField="邮箱" HeaderText="邮箱" SortExpression="邮箱" />
- <asp:BoundField DataField="密码保护问题" HeaderText="密码保护问题"
- SortExpression="密码保护问题" />
- <asp:BoundField DataField="密码保护问题回答" HeaderText="密码保护问题回答"
- SortExpression="密码保护问题回答" />
- <asp:BoundField DataField="注册时间" HeaderText="注册时间" SortExpression="注册时间" />
- <asp:TemplateField ShowHeader="true" HeaderText="删除用户">
- <ItemTemplate>
- <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Delete"
- Text="删除" OnClientClick='<%# "if (!confirm(\"你确定要删除" + Eval("用户名").ToString() + "吗?\")) return false;"%>'></asp:LinkButton>
- </ItemTemplate>
- </asp:TemplateField>
- </Columns>
- </asp:GridView>
后台的代码:
- protected void Page_Load(object sender, EventArgs e)
- {
- if(!Page.IsPostBack)
- {
- bind();
- }
- }
- public void bind()
- {
- SqlConnection conn = new SqlConnection(CommonMethods.connstring);
- conn.Open();
- string cmd = "select * from userlogin";
- SqlDataAdapter da = new SqlDataAdapter(cmd, conn);
- DataSet ds = new DataSet();
- da.Fill(ds);
- GridView1.DataSource = ds;
- GridView1.DataBind();
- conn.Close();
- }
- protected void GridView1_deleting(object sender, GridViewDeleteEventArgs e)//注意各种事件的参数类型
- {
- SqlConnection conn = new SqlConnection(CommonMethods.connstring);
- conn.Open();
- string deleteuser = GridView1.DataKeys[e.RowIndex].Value.ToString();//获取主键
- string cmd = "delete from userlogin where 用户名='" + deleteuser+"'" ;//
- SqlCommand cmdt = new SqlCommand(cmd, conn);
- try
- {
- cmdt.ExecuteNonQuery();
- Response.Write("<script>alert('删除成功!')</script>");
- }
- catch
- {
- return;
- }
- bind();
- conn.Close();
- }