[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

ASP.NET gridview based on permissions?

Posted on 2011-04-26
6
Medium Priority
?
933 Views
Last Modified: 2012-05-11
I have asn ASP.NET Gridview that displays a Delete button and a DetailsView that displays an Edit button.  I would like to make these two buttons ONLY display if a user has access to perform Edit or Delete operations, with the information of who has access being contained in a database table.  How would I go about doing this?
0
Comment
Question by:melli111
  • 3
  • 2
6 Comments
 
LVL 17

Expert Comment

by:Carlos Villegas
ID: 35467751
Hi, I did this small example to give you an idea:
<%@ Import Namespace="System.Data" %>

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Check user permissions.

            // You need to check the current user name by using: Page.User.Identity.Name
            // string userName = Page.User.Identity.Name;

            // For demo purposes I will use Alice.
            string userName = "Alice";

            if (UserInRole(userName, "IsAdmin"))
            {
                // Show the delete and edit button to users in the IsAdmin role.
                GridView1.AutoGenerateDeleteButton = true;
                DetailsView1.AutoGenerateEditButton = true;
            }

            // Simulate data.
            DataTable dtt = new DataTable();
            dtt.Columns.Add("Record", typeof(int));
            dtt.Columns.Add("Date", typeof(DateTime));
            dtt.Columns.Add("Value", typeof(decimal));
            dtt.Rows.Add(1, DateTime.Now, 123);
            dtt.Rows.Add(2, DateTime.Now, 1234);
            dtt.Rows.Add(3, DateTime.Now, 1235);
            dtt.Rows.Add(4, DateTime.Now, 1236);
            dtt.AcceptChanges();

            GridView1.DataSource = dtt;
            GridView1.DataBind();

            DetailsView1.DataSource = dtt;
            DetailsView1.DataBind();
        }
    }

    private bool UserInRole(string userName, string roleName)
    {
        // Simulate your DB permission data for that user name.
        DataTable dtt = new DataTable();
        dtt.Columns.Add("UserName", typeof(string));
        dtt.Columns.Add("RoleName", typeof(string));
        dtt.Rows.Add("Alice", "IsAdmin");
        dtt.Rows.Add("Bob", "IsUser");
        dtt.Rows.Add("Jason", "IsAdmin");
        dtt.AcceptChanges();
        dtt.PrimaryKey = new DataColumn[] { dtt.Columns[0], dtt.Columns[1] };

        // Return true if the user have the permission.
        return dtt.Rows.Find(new object[] { userName, roleName }) != null;
    }


    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
    
    }

    protected void DetailsView1_ModeChanging(object sender, DetailsViewModeEventArgs e)
    {

    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" 
            onrowdeleting="GridView1_RowDeleting">
        </asp:GridView>
        <br />
        <asp:DetailsView ID="DetailsView1" runat="server" 
            onmodechanging="DetailsView1_ModeChanging">
        </asp:DetailsView>
    </div>
    </form>
</body>
</html>

Open in new window

You can download the aspx file here:
GridViewPermissions.aspx

The best way to check permissions is to use a role provider or implement your own authentication method to be able to use the Page.User.IsInRole("") method, but I did this example to give you a start.

I hope this help.
0
 
LVL 15

Author Comment

by:melli111
ID: 35468345
Thank you,  my next question is, I would like for the Delete button on the GridView to be in the very last column to the right.  After the statement "GridView1.AutoGenerateDeleteButton = true;", is there a way to specify which row to place the Delete button in?  It defaults to the very first row and I do not want it there.
0
 
LVL 17

Accepted Solution

by:
Carlos Villegas earned 2000 total points
ID: 35469153
Of course you can, but you must declare yours columns and avoid to use the autogeneratecolumns and AutoGenerateDeleteButton properties, here the example:
<%@ Import Namespace="System.Data" %>

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Check user permissions.

            // You need to check the current user name by using: Page.User.Identity.Name
            // string userName = Page.User.Identity.Name;

            // For demo purposes I will use Alice.
            string userName = "Alice";

            if (UserInRole(userName, "IsAdmin"))
            {
                // Show the delete and edit button to users in the IsAdmin role.
                //GridView1.AutoGenerateDeleteButton = true;
                DetailsView1.AutoGenerateEditButton = true;
            }
            else
            {
                // Remove the Delete command.
                GridView1.Columns.RemoveAt(GridView1.Columns.Count - 1);
            }


            // Simulate data.
            DataTable dtt = new DataTable();
            dtt.Columns.Add("Record", typeof(int));
            dtt.Columns.Add("Date", typeof(DateTime));
            dtt.Columns.Add("Value", typeof(decimal));
            dtt.Rows.Add(1, DateTime.Now, 123);
            dtt.Rows.Add(2, DateTime.Now, 1234);
            dtt.Rows.Add(3, DateTime.Now, 1235);
            dtt.Rows.Add(4, DateTime.Now, 1236);
            dtt.AcceptChanges();

            GridView1.DataSource = dtt;
            GridView1.DataBind();

            DetailsView1.DataSource = dtt;
            DetailsView1.DataBind();
        }
    }

    private bool UserInRole(string userName, string roleName)
    {
        // Simulate your DB permission data for that user name.
        DataTable dtt = new DataTable();
        dtt.Columns.Add("UserName", typeof(string));
        dtt.Columns.Add("RoleName", typeof(string));
        dtt.Rows.Add("Alice", "IsAdmin");
        dtt.Rows.Add("Bob", "IsUser");
        dtt.Rows.Add("Jason", "IsAdmin");
        dtt.AcceptChanges();
        dtt.PrimaryKey = new DataColumn[] { dtt.Columns[0], dtt.Columns[1] };

        // Return true if the user have the permission.
        return dtt.Rows.Find(new object[] { userName, roleName }) != null;
    }


    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
    }

    protected void DetailsView1_ModeChanging(object sender, DetailsViewModeEventArgs e)
    {
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" OnRowDeleting="GridView1_RowDeleting"
            AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField HeaderText="Record" DataField="Record" />
                <asp:BoundField HeaderText="Date" DataField="Date" />
                <asp:BoundField HeaderText="Value" DataField="Value" />
                <asp:CommandField ShowDeleteButton="true" />
            </Columns>
        </asp:GridView>
        <br />
        <asp:DetailsView ID="DetailsView1" runat="server" OnModeChanging="DetailsView1_ModeChanging">
        </asp:DetailsView>
    </div>
    </form>
</body>
</html>

Open in new window


Here the aspx file:
 GridViewPermissions.aspx
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 15

Author Comment

by:melli111
ID: 35470218
This worked great, thank you.  The very last thing I need, is that I want the Edit button on the DetailsView to be aligned on the right side.  Is there any way to do that?
0
 
LVL 17

Expert Comment

by:Carlos Villegas
ID: 35470388
Yes! this easy way ;)
<asp:DetailsView ID="DetailsView1" runat="server" OnModeChanging="DetailsView1_ModeChanging">
    <CommandRowStyle HorizontalAlign="Right" />
</asp:DetailsView>

Open in new window

0
 
LVL 7

Expert Comment

by:mr_nadger
ID: 35473791
I don't want to steal any of yv989c's credit here, as he's answered so well, but I just wanted to point out, in case you're using Visual Studio, that you can order the columns and set the alignment etc in the Edit Columns gui.
The styles can also be controlled using CSS files, examples below
.mGrid {    
    background-color: #fff;    
    margin: 5px 0 10px 0;    
    border: solid 1px #525252;    
    border-collapse:collapse;   
    vertical-align:top; 
}   
.mGrid td {    
    padding: 2px;    
    border: solid 1px #c1c1c1;    
    color: #717171;   
    vertical-align:top; 
}   
.mGrid th {    
    color: Black;    
    background: #424242 ;    
    font-size: 0.9em;
    text-align:center;    
}   
.mGrid .alt { background: #fcfcfc; }

Open in new window

0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Hello there! As a developer I have modified and refactored the unit tests which was written by fellow developers in the past. On the course, I have gone through various misconceptions and technical challenges when it comes to implementation. I would…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…
With just a little bit of  SQL and VBA, many doors open to cool things like synchronize a list box to display data relevant to other information on a form.  If you have never written code or looked at an SQL statement before, no problem! ...  give i…
Suggested Courses

873 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question