Search code examples
c#.netasp.netgridviewobjectdatasource

Deleting a record from Gridview with ObjectDataSource


I have a gridview that binds its rows from an objects method:

public DataSet GetObjects() { DataSet ds = new DataSet(); DataTable dt = new DataTable(); var source = from p in CommentsList select new { p.CommentID, p.Img, p.Name, p.Comment };

dt.Columns.Add("CommentsID");
dt.Columns.Add("Img");
dt.Columns.Add("Name");
dt.Columns.Add("Comment");

foreach (var item in source)
{



    DataRow userDetailsRow=dt.NewRow();
    userDetailsRow["Img"] = item.Img;
    userDetailsRow["Name"] = item.Name;

    DataRow commentsID = dt.NewRow();
    userDetailsRow["CommentsID"] = item.CommentID;

    DataRow comments = dt.NewRow();
    userDetailsRow["Comment"] = item.Comment;
    dt.Rows.Add(userDetailsRow);
    //dt.Rows.Add(comments);
}
ds.Tables.Add(dt);
return ds;

} My delete method. Should receive the commentsID to delete it from the database and then rebind the Gridview.. But how? do i pass the CommentsID from the gridview to this method public void RemoveComment(int CommentsID) { }

GridViews Two templates:

 <Columns>
      <asp:TemplateField>
                        <ItemTemplate>
                            <asp:Label ID="lblMessage" runat="server"  Text='<%# Bind("Comment") %>'></asp:Label>
                        </ItemTemplate>
       </asp:TemplateField>

           <asp:TemplateField>
                        <ItemTemplate>
                            <asp:Image ID="imgName" runat="server"  imageUrl='<%# Bind("Img") %>'></asp:Image><br />
                            <asp:Hyperlink ID="hyperLink" runat="server"  Text='<%# Bind("Name") %>' ></asp:Hyperlink>
                        </ItemTemplate>
       </asp:TemplateField>
   </Columns>

Now, I want to delete a row, how do I do that? I know that DataKeyNames exist..but how do I set the commentsID as my dataKeyNames, and how do i delete a record?


Solution

  • You can specify the Delete method to the objectDataSource and it will be very simple...e.g.

     <asp:ObjectDataSource ID="ods" runat="server" DeleteMethod="RemoveComment" SelectMethod="GetCityByStateID" TypeName="">
            <DeleteParameters>
                <asp:Parameter Name="CommentsID" Type="Int32" />
             </DeleteParameters>
              <SelectParameters>
              </SelectParameters>
      </asp:ObjectDataSource>
    

    Whenever the Gridview Delete button is hit this will automatically fire this method and delete the record.