Explanation:
In this tutorial we will discuss about creating a latest
registred users/members list in a website.
We are going to perform this step by step:
- Add a Class GetUsersDatato your Folder
App_Data this is where all non-compiled code goes.
- Add a new Class GetAllUsersDataTable()
to it.
- Make it a static
Class. This will make us easy to access the function. To learn more about static
classes and static functions read our other article
Static Classes and Static Class Members.
- Now our Function look like this;
Public static
DataView GetAllUsersDataTable()
{
MembershipUserCollection mc = new
MembershipUserCollection();
mc = Membership.GetAllUsers();
DataTable dt = new
DataTable("LastUsers");
dt.Columns.Add("UserName", typeof(string));
dt.Columns.Add("Rdate", typeof(DateTime));
string name = string.Empty;
foreach (MembershipUser st
in mc)
{
name = st.UserName;
dt.Rows.Add(new Object[]
{ name, st.CreationDate });
}
dt.AcceptChanges();
DataView dv = new
DataView(dt);
return dv;
}
You noticed that 1st we defined a DataTable
and later after filling it we changed it to a DataView. This is because DataView
will give us better controle over Data Operations rather then a DataTable.
Now save your work in the new created Class and go the
Page (.aspx) where actually you want Display the Lates users List.
Add a Table Control to the Page. It would be better idea
to create a new DataPlaceHolder if you are using a Mater Page.
Name the Table “LatestUsersTable”. Don’t
add any thing to the Table. Your Table will look like this now;
<asp:Table ID="LatestUsersTable"
runat="server">
</asp:Table>
Now, add the following code to your Page_Load event.
DataView tView = GetUsersData.GetAllUsersDataTable();
tView.Sort
= "Rdate DESC";
This will sort the DataView Desecendingly on users Registration
Date. By default the date enterd was in accending.
Now, it depends how many user you want to show in the
latest user list. We are showing last 5 members. We enterd the upper limit 5 in
or For Loop.
for (int i = 0; i < 5; i++)
{
TableRow Row = new
TableRow();
TableCell C1 = new
TableCell();
C1.Text
= @"<a href=Members/User.aspx?userN="
+
tView[i]["UserName"].ToString() + ">" +
tView[i]["UserName"].ToString() + "</a>";
Row.Cells.Add(C1);
LatestUsersTable.Rows.Add(Row);
}
TableRow
Row4 = new TableRow();
TableCell C4 = new
TableCell();
C4.Text = @"<a href=Members/UsersWidPics.aspx><b><
All Members ></b></a>";
Row4.Cells.Add(C4);
LatestUsersTable.Rows.Add(Row4);
In the Loop at first a row created, after that a cell
is cerated for each user and evantually it is added to the current row of our Table.
The actual trick lies in “tView[i]["UserName"]”.
This way we are getting the 1st five rows of our DataView.
When the loop is finished we added one more row at the
bottom of the Table, so when a user want to see the complete list of users he/she
will just click on it and it will navigate them to our “Members/Users.aspx”
Page.
|