日期:2014-05-18  浏览次数:20367 次

gridview 如何删除一行记录
大家注意我的datasource,我猜测这是我用的很多code不起作用的原因。在我的程序中,gv.DataKeys.Count=0!

C# code
DataTable dt = DB.GetAllLines(Int32.Parse(lblGameID.Text));
gv.DataSource = dt;
gv.DataBind();


gridview的设置:
HTML code
            <asp:GridView ID="gv" runat="server" AutoGenerateDeleteButton="True" 
                BorderColor="#99FF99" BorderStyle="Solid" BorderWidth="1px" 
                EmptyDataText="没有任何选项" AutoGenerateColumns="False" 
                onrowdeleting="gv_RowDeleting">
                <RowStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                <Columns>
                    <asp:BoundField DataField="line_id" Visible="False" />
                    <asp:BoundField DataField="line_text" HeaderText="选项"/>
                    <asp:BoundField DataField="line_odds" HeaderText="赔率"/>
                    <asp:BoundField DataField="line_status" HeaderText="状态" />
                </Columns>
                <HeaderStyle BorderStyle="Solid" BorderWidth="1px" HorizontalAlign="Center" 
                    VerticalAlign="Middle" />
                <AlternatingRowStyle BackColor="#9999FF" HorizontalAlign="Center" 
                    VerticalAlign="Middle" Width="695px" Wrap="False" />
            </asp:GridView>


这个是我的一个尝试:
C# code
        protected void gv_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
           
            GridViewRow row = gv.Rows[e.RowIndex];

            int result = DB.DeleteLine(Int32.Parse(row.Cells[0].ToString()));
            gv.DeleteRow(e.RowIndex);
            
        }


------解决方案--------------------
晕,你gridview不定义DataKeyNames,用DataKeyNames绑定你数据库主键,这样删除就OK拉
string id = this.GridView1.DataKeys[e.RowIndex]["id"].ToString();
string deda = "delete from tablename where id='" + id + "'";

<asp:GridView ID="GridView1" runat="server" Width="603px" Font-Size="12px" ForeColor="#333333"
AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="id" OnPageIndexChanging="GridView1_PageIndexChanging"
OnRowDeleting="GridView1_RowDeleting">
<Columns>
<asp:HyperLinkField DataTextField="company_name" DataNavigateUrlFields="id" DataNavigateUrlFormatString="UpdateJobCompany.aspx?Id={0}"
HeaderText="公司名称">
<HeaderStyle Width="350px" HorizontalAlign="Center" />
<ItemStyle Width="350px" HorizontalAlign="Center" />
</asp:HyperLinkField>
<asp:BoundField DataField="company_address" HeaderText="公司地址" SortExpression="company_address">
<HeaderStyle Width="350px" HorizontalAlign="