GridView删除行
HTML code
- <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDeleting="GridView1_RowDeleting">
- <Columns>
- <asp:BoundField DataField="id" HeaderText="id" />
- <asp:BoundField DataField="name" HeaderText="name" />
- <asp:TemplateField ShowHeader="False">
- <ItemTemplate>
- <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Delete"
- Text="删除" OnClientClick='<%# "if (!confirm(\"你确定要删除" + Eval("name").ToString() + "吗?\")) return false;"%>'></asp:LinkButton>
- </ItemTemplate>
- </asp:TemplateField>
- </Columns>
- </asp:GridView>
C# code
- private void BindGridView()
- {
- SqlConnection cn = new SqlConnection(@"server=.\SQLExpress;uid=sa;pwd=;database=Demo");
- SqlDataAdapter da = new SqlDataAdapter("select id, name from yourtable", cn);
- DataSet ds = new DataSet();
- cn.Open();
- da.Fill(ds);
- cn.Close();
- GridView1.DataSource = ds.Tables[0].DefaultView;
- GridView1.DataKeyNames = new string[] { "id" };
- GridView1.DataBind();
- }
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- BindGridView();
- }
- }
- protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
- {
- string strSql = "delete from yourtable where id = @id";
- SqlConnection cn = new SqlConnection(@"server=.\SQLExpress;uid=sa;pwd=;database=Demo");
- SqlCommand cmd = new SqlCommand(strSql, cn);
- cmd.Parameters.Add("@id", SqlDbType.VarChar, 11).Value = GridView1.DataKeys[e.RowIndex].Value.ToString();
- cn.Open();
- cmd.ExecuteNonQuery();
- cn.Close();
- BindGridView();
- }