Aubrey Love

Aubrey Love

  • NA
  • 173
  • 4.9k

How to populate a GridView column with current user on row delete

Apr 29 2022 2:14 PM

I’m having some trouble figuring this out. Hopefully someone on here can tell me what I’m doing wrong. I am trying to populate a “userName” column in a Gridview with the current logged in user when that user deletes a row. My end goal is to populate that “userName” column in a database with the user that deleted the row. I want to know who made a change and log that user in the “userName” column of the database table “userEntry”.

Here’s what I have. I created a sample database (sampleDB) and inside the database I created a simple table, “userEntry”. See sample db script below.

USE sampleDB;
GO

CREATE TABLE userEntry(
    id INT IDENTITY
    , someText VARCHAR(20)
    , userName VARCHAR(20)
    );
GO

INSERT INTO userEntry(someText, userName)
VALUES('Hello', 'John')
, ('Ohla', 'Sam');
GO

SELECT *
FROM userEntry;
GO

Next, I created a simple ASP.NET Web Application (.NET Framework) called “getUser1”. Then I added a GridView and a SQL connection string to link to the GridView to the database table. Here is the code I am using in the ASP.NET Web Application.

Default.aspx Page:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="getUser1._Default" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">


   <div>
       <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" DataKeyNames="id" Width="328px"  
           OnRowUpdating="GridView1_RowUpdating" OnRowDeleting="GridView1_RowDeleted" OnRowDataBound="GridView1_RowDataBound">
           <Columns>                
               <asp:CommandField ShowEditButton="True" />               
               <asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True" SortExpression="id" />
               <asp:BoundField DataField="someText" HeaderText="someText" SortExpression="someText" />
               <asp:BoundField DataField="userName" HeaderText="userName" SortExpression="userName" />
               <asp:TemplateField ShowHeader="true" HeaderText="Delete" HeaderStyle-ForeColor="White" ItemStyle-HorizontalAlign="Center">
                <ItemTemplate>
                    <asp:LinkButton ID="LinkButton1"  runat="server" CausesValidation="False" 
                        CommandName="Delete" ForeColor="DarkRed" Text="Delete" ToolTip="Delete">
                        <img src="Images/icon-delete.gif" />
                    </asp:LinkButton>
                </ItemTemplate>
                <HeaderStyle ForeColor="White"></HeaderStyle>
                <ItemStyle HorizontalAlign="Center"></ItemStyle>
                </asp:TemplateField>
           </Columns>
       </asp:GridView>

       <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:conString %>" 
           SelectCommand="SELECT * FROM [userEntry]"
           UpdateCommand="UPDATE [userEntry] Set [someText]=@someText, [userName]=@userName Where [id]=@id"
            DeleteCommand="DELETE FROM [userEntry] Where [id]=@id"></asp:SqlDataSource>
   </div>

</asp:Content>

Default.aspx.cs Page:

using System;
using System.Web.UI;
using System.Security.Principal;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

namespace getUser1
{
    public partial class _Default : Page
    {
        

        public void Page_Load(object sender, EventArgs e)
        {
            
        }
        
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            // string strCurrentUser = WindowsIdentity.GetCurrent().Name;
            string strcurrentUser = WindowsIdentity.GetCurrent().Name;
            e.NewValues["userName"] = strcurrentUser;

        }

        //SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);

        protected void GridView1_RowDelete(object sender, GridViewDeleteEventArgs e)
        {
            //con.Open();
            //SqlCommand cmd = con.CreateCommand();
            //cmd.CommandType = CommandType.Text;
            //cmd.CommandText = "insert into userEntry VALUES('" + e.Values["id"] + "', '" + e.Values["someText"] + "', '" + WindowsIdentity.GetCurrent().Name + "')";
                //cmd.CommandText = "insert into userEntry.[userName] VALUES('" + WindowsIdentity.GetCurrent().Name + "')";
            //cmd.ExecuteNonQuery();
            //con.Close();

        }

        protected void GridView1_RowDeleted(object sender, GridViewDeleteEventArgs e)
        {
            
            //if (e.Values["userName"] != null)
            //{
            //    string strdeleteUser = WindowsIdentity.GetCurrent().Name;
            //    e.Values["userName"] = strdeleteUser;
            //}
            //else
            //{
            //    string strnewUser = WindowsIdentity.GetCurrent().Name;
            //    e.Values["userName"] = strnewUser;
            //}

        }        
    }
}

 

So, the sections that are commented out in the “Default.aspx.cs” page are some of the variants I have tried along with adding the "if (!IsPostBack)" section to the code behind for the "Default.aspx.cs" page. But it doesn't seem to be working. Obviously I have no idea how to get the current user name in the “userName” column when a GridView row is deleted by that user.

In short, when someone deletes a row, I need that current user name to populate the “userName” column on that row just before it deletes the row.

Is this even possible? I wonder because I can get this to work on the “edit” function but then, the delete function is not an edit function in regards to editing a row but it is an edit function in regards to the GridView.

Any help would be greatly appreciated. Thank you.

 


Answers (2)