Home > other >  How to populate a GridView column with current user
How to populate a GridView column with current user

Time:04-27

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. My end goal is to populate that “userName” column in a database with the user that edited the “userEntry” column in the same Gridview. 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">
           <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" />
           </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;
    namespace getUser1
    {
        public partial class _Default : Page
        {
            public object DataField { get; private set; }
    
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    DataField.userName.Text = WindowsIdentity.GetCurrent().Name;
                } 
            }
        }
    }

Web.config Page:

<connectionStrings>
    <add name="conString" connectionString="Data Source=dsouthres18v;Initial Catalog=sampleDB;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>

So, this is what I have tried (adding the "if (!IsPostBack)" section to the code behind for the "Default.aspx" page. But it doesn't seem to be working. Obviously I have no idea how to get the user in the “userName” column when the GridView is edited by a user and they click the “update” button in GridView.

I can get this to work on a simple text box creating a new entry, but I can't figure out to do the same with an "asp:BoundField DataField" in a GridView. I hope that makes sense and I hope someone can get me on the right track to figure this out. Thanks in advance.

CodePudding user response:

Ok, right click on the Gridview in the design view , bring up property sheet.

This one:

enter image description here

You can double click in that area to create a event.

Then, say this code:

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

    }
  • Related