【问题标题】:How to delete a row in a gridview and the underlying datasource without using a SqlDataSource, ObjectDataSource, etc如何在不使用 SqlDataSource、ObjectDataSource 等的情况下删除 gridview 和底层数据源中的一行
【发布时间】:2009-05-01 20:40:25
【问题描述】:

我有一个 GridView,我通过调用一个方法来填充它以返回一个包含两列的数据表。返回数据表后,我将它绑定到gridview并显示它。

我没有使用 SqlDataSource 或 ObjectDataSource,那么从 gridview 和数据库中的基础数据中删除一行的正确方法是什么。我只需要从一个称为投资组合的表中删除。它有 3 列,ID,即唯一键、PortfolioID 和 PortfolioName。数据表返回 PortfolioName 和 Portfolio 中的项目数。我在想我可以在 Row_Deleting 事件中执行此操作,我会执行以下操作:

DELETE * FROM Portfolio WHERE PortfolioID = @PortfolioID

我是否走在正确的轨道上,我该怎么做?我可以将 PortfolioID 绑定到 GridView DataKey 属性吗(执行此操作的正确语法是什么?)

【问题讨论】:

    标签: c# asp.net gridview


    【解决方案1】:

    我假设您在按下按钮时删除了一行。如果是这样,我通常会这样做:

    <asp:GridView ID="myGrid" runat="server" DataKeyNames='PortfolioID' OnRowCommand="dgStudent_RowCommand">
        <Columns>
            <asp:ButtonField ButtonType="Button" CommandName="Delete" Text="Delete"></asp:ButtonField>
        </Columns>
    </asp:GridView>
    

    然后在你的代码隐藏中:

    protected void myGrid_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        // create and open DB connection
        int PortfolioID = (int)myGrid.DataKeys[Convert.ToInt32(e.CommandArgument)].Value;
        DeleteRow(PortfolioID); // your implementation
        myGrid.DataBind(); 
    }
    

    DeleteRow 是您对行删除的实现(可能是您上面的 SQL)。 myGrid 是您的网格。 PortfolioID 是主键。这也假定网格中唯一的按钮是删除按钮。如果您有多个按钮,则需要检查e.CommandName=="Delete" 以确保您获得了删除按钮。

    【讨论】:

      【解决方案2】:

      我可能会比那里更进一步抽象 DB 调用。我可能会在行更改完成后处理这些行。对于后处理,您可以检查行状态以确定如何处理行中的数据。

      【讨论】:

        【解决方案3】:

        据我了解,您想从数据库表中归档的数据网格视图中删除一行。这意味着您要从某个数据库中删除和表记录。 最好的方法是在某处放置一个文本框并为您的 datagridview 创建一个事件(在行选择事件上)。这样,当您选择要删除的行时,该行的 id 将被发送到文本框(这将被编码)。获得要删除的行的 ID 后,只需再添加一个按钮即可删除数据库中的记录并再次绑定 datagridview。

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
            {
        
                this.txt_portfolioId.Text=dataGridView1.CurrentRow.Cells["portfolioID"].Value.ToString();
        
        
            }
        
        
        private void btn_Delete(object sender, EventArgs e)
            {
        
                //You need to connect to database(regular database connection this connection string and sqlcommand and add this sqlquerry:
        

        从您的表中删除 * 其中投资组合 ID = '"+Convert.ToInt32(this.portfolioId.Text)+"';
        }

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-09-23
          • 1970-01-01
          • 2023-03-05
          • 2011-07-07
          • 2013-12-03
          • 2015-01-13
          • 1970-01-01
          相关资源
          最近更新 更多