当前位置:编程学习 > C#/ASP.NET >>

.net中Gridview控件中删除数据代码怎么写

答案:private void btnDelete_Click(object sender, EventArgs e) { if (dataGridView1.CurrentRow == null || dataGridView1.CurrentRow.IsNewRow) { MessageBox.Show("未选中行", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } if (dataGridView1.CurrentRow.Index < 0) { MessageBox.Show("未选中行", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } int productid = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value); //MessageBox.Show(productid.ToString()); //根据产品id进行删除, //重新绑定数据 BindProductList(); }
其他:Gridview 不是有提供自动删除的吗?用哪个也行,不过代码就跳过冗余了
自己写的思路是: 获取你点击那条记录的 ID (唯一性)
然后就 delete 表 Where ID=@ID 。。。。
接下去的删除都是一样的。。。。
最后重新绑定GridView.
获取ID 是 GridView1.FindControl("控件ID名");
希望可以帮助你理解。 GridView的Rows是不能直接删除的,你能把里面的数据数据到DataTable里面,删完了再绑进去 添加模版列
 <asp:TemplateField HeaderText="删除">
                                    <EditItemTemplate>
                                        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                                    </EditItemTemplate>
                                    <ItemTemplate>
                                         <asp:LinkButton ID="BtnDelete" runat="server" CausesValidation="False" 
                                            CommandArgument='<%#DataBinder.Eval(Container,"DataItem.News_ID")%>' 
                                            CommandName="Delete" OnClientClick="return confirm('确认要删除此行信息吗?')" 
                                            Text="Delete"></asp:LinkButton>
                                    </ItemTemplate>
                                    <ControlStyle ForeColor="Red" />
                                    <ItemStyle ForeColor="Red" />
                                </asp:TemplateField>

后台代码
    protected void Gvnews_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Delete")
        {
            if (e.CommandArgument != null)
            {
                delnews(int.Parse(e.CommandArgument.ToString()));

                UPAlert(upsum, "删除成功!");
                Bind_Gv();
            }
        }

    }
    protected void Gvnews_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        e.Cancel = true;
    }

伪代码 自己重写下
 

上一个:在.Net C# 语言中如何将一个字符串类型的数据转换成一个decimal 类型的数据
下一个:.net中怎么取GridView中的值

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,