Different Gridview Operations

Thursday, December 18, 2008

We use gridview control for different purpose in our application. Here I am explanning some of the
most useful operations using gridview

Here I am showing the final results of the various samples. You can download the complete source in end of the article.

  • Search in Gridview

  • General Edit operations with Gridview.

  • Showing Image in gridview.

  • Showing Image in gridview from Databas

  • Gridview with checkboxes

  • Modalpopup with Gridview

  • Hovermenu with Gridview

  • Import Excel to Gridview

  • Import Gridview to Excel

  • Using Filters in Gridview



Search in Gridview
Some times we need search the inner details of a gridview. For this requirement we can use this functionality.


General Edit operations with Gridview.
This is very common operation. But really useful when we have few columns


Showing Image in gridview.
Some times we have to show Images inside gridview which are placed in one folder in server.


 <asp:TemplateField HeaderText="Image">

           <ItemTemplate>

            <img src="Images/<%# DataBinder.Eval(Container.DataItem, "Mobile")%>"

            width="200px"

            height="200px" />

           </ItemTemplate>

          </asp:TemplateField>





Showing Image in gridview from Databas
If the Images are stored in database, then we have to use Generic handler, by using this we can retrive the Images from database. You can find the source in download.

  <asp:TemplateField HeaderText="Image">

           <ItemTemplate>

            <asp:Image ID="imgproduct" runat="server" Width="100px" Height="100px"

            ImageUrl='<%# "Product.ashx?pid="+ Eval("PID") %>'  />

           </ItemTemplate>

          </asp:TemplateField>




Gridview with checkboxes
In many requirements we will have checkboxes in our grid. check here how to get the selected checkbox values inide the gridview



Modalpopup with Gridview
In gridview we can show the Ajax Modalpopup, when user clicks on button which placed inside a gridview.

  if (e.CommandName == "view")

        {

            string idval = e.CommandArgument.ToString();

            DataSet ds = (DataSet)Session["dbsample"];

            DataRow[] gvw = ds.Tables[0].Select("ID = '" + idval + "'");

            if (gvw.Length > 0)

            {

                txtname.Text = gvw[0]["Name"].ToString();

                txtdept.Text = gvw[0]["Department"].ToString();

                txtdesig.Text = gvw[0]["Designation"].ToString();

                txtemail.Text = gvw[0]["Email"].ToString();

                txtphone.Text = gvw[0]["Phone"].ToString();

                txtaddress.Text = gvw[0]["Address"].ToString();

            }

           

            ModalPopupExtender1.Show();

        }





Hovermenu with Gridview
Check out this example, how to integrate a hovermenu with the gridview

   protected void grdImage_RowDataBound(object sender, GridViewRowEventArgs e)

    {

        if (e.Row.RowType == DataControlRowType.DataRow)

        {

            AjaxControlToolkit.HoverMenuExtender hme = e.Row.FindControl("HoverMenuExtender1") as AjaxControlToolkit.HoverMenuExtender;

            e.Row.ID = "row" + e.Row.RowIndex.ToString();

            Panel hf = e.Row.FindControl("pnl1") as Panel;

            hme.TargetControlID = e.Row.ID;

        }

    }





Import Excel to Gridview
Check how to Import a XL file and bind it grid view


Import Gridview to Excel
Export the selected rows in gridview to Excel


Using Filters in Gridview
Check here how to use the filters in gridview



Source Code

Alphabetic User Control

Sunday, December 14, 2008
In some situations we may have a requirement to search the records Alphabetic wise. For these type of requirement we have to take 26 alphabets and when we have to generate click events to know which alphabet clicked. Its not a good way to generate 26 button click events. Instead of that we can take Command Name and we will call the same function. And if we make a user control, this control can used many times in our project.
First Add a Webuser control to your project and name it as “Alphabetic_Control.ascx”. Then add 26 link buttons. Each button has “Command Name” and “onclick” events.
“Command Name” contains the text of the link button like A, B, etc. and all “onclick” events of 26 link button calls “SelectList_Alpha” function.
The final user control code is:











  1. <asp:LinkButton ID="lnkA" runat="server" CommandName="A" Text="A" OnClick="SelectList_Alpha"></asp:LinkButton> -





  2. <asp:LinkButton ID="lnkB" runat="server" CommandName="B" Text="B" OnClick="SelectList_Alpha"></asp:LinkButton> -





  3. <asp:LinkButton ID="lnkC" runat="server" CommandName="C" Text="C" OnClick="SelectList_Alpha"></asp:LinkButton> -





  4. <asp:LinkButton ID="lnkD" runat="server" CommandName="D" Text="D" OnClick="SelectList_Alpha"></asp:LinkButton> -





  5. <asp:LinkButton ID="lnkE" runat="server" CommandName="E" Text="E" OnClick="SelectList_Alpha"></asp:LinkButton> -





  6. <asp:LinkButton ID="lnkF" runat="server" CommandName="F" Text="F" OnClick="SelectList_Alpha"></asp:LinkButton> -





  7. <asp:LinkButton ID="lnkG" runat="server" CommandName="G" Text="G" OnClick="SelectList_Alpha"></asp:LinkButton> -





  8. <asp:LinkButton ID="lnkH" runat="server" CommandName="H" Text="H" OnClick="SelectList_Alpha"></asp:LinkButton> -





  9. <asp:LinkButton ID="lnkI" runat="server" CommandName="I" Text="I" OnClick="SelectList_Alpha"></asp:LinkButton> -





  10. <asp:LinkButton ID="lnkJ" runat="server" CommandName="J" Text="J" OnClick="SelectList_Alpha"></asp:LinkButton> -





  11. <asp:LinkButton ID="lnkK" runat="server" CommandName="K" Text="K" OnClick="SelectList_Alpha"></asp:LinkButton> -





  12. <asp:LinkButton ID="lnkL" runat="server" CommandName="L" Text="L" OnClick="SelectList_Alpha"></asp:LinkButton> -





  13. <asp:LinkButton ID="lnkM" runat="server" CommandName="M" Text="M" OnClick="SelectList_Alpha"></asp:LinkButton> -





  14. <asp:LinkButton ID="lnkN" runat="server" CommandName="N" Text="N" OnClick="SelectList_Alpha"></asp:LinkButton> -





  15. <asp:LinkButton ID="lnkO" runat="server" CommandName="O" Text="O" OnClick="SelectList_Alpha"></asp:LinkButton> -





  16. <asp:LinkButton ID="lnkP" runat="server" CommandName="P" Text="P" OnClick="SelectList_Alpha"></asp:LinkButton> -





  17. <asp:LinkButton ID="lnkQ" runat="server" CommandName="Q" Text="Q" OnClick="SelectList_Alpha"></asp:LinkButton> -





  18. <asp:LinkButton ID="lnkR" runat="server" CommandName="R" Text="R" OnClick="SelectList_Alpha"></asp:LinkButton> -





  19. <asp:LinkButton ID="lnkS" runat="server" CommandName="S" Text="S" OnClick="SelectList_Alpha"></asp:LinkButton> -





  20. <asp:LinkButton ID="lnkT" runat="server" CommandName="T" Text="T" OnClick="SelectList_Alpha"></asp:LinkButton> -





  21. <asp:LinkButton ID="lnkU" runat="server" CommandName="U" Text="U" OnClick="SelectList_Alpha"></asp:LinkButton> -





  22. <asp:LinkButton ID="lnkV" runat="server" CommandName="V" Text="V" OnClick="SelectList_Alpha"></asp:LinkButton> -





  23. <asp:LinkButton ID="lnkW" runat="server" CommandName="W" Text="W" OnClick="SelectList_Alpha"></asp:LinkButton> -





  24. <asp:LinkButton ID="lnkX" runat="server" CommandName="X" Text="X" OnClick="SelectList_Alpha"></asp:LinkButton> -





  25. <asp:LinkButton ID="lnkY" runat="server" CommandName="Y" Text="Y" OnClick="SelectList_Alpha"></asp:LinkButton> -





  26. <asp:LinkButton ID="lnkZ" runat="server" CommandName="Z" Text="Z" OnClick="SelectList_Alpha"></asp:LinkButton>








Write the “SelectList_Alpha” function in the code behind. The complete code is..
The User control designing is completed, Now we have to generate a “Click” events to this User Control. The reason to create “Click” event is when we take this user control to other page it will not fire the click event. We have to create a “Click” event explicitly. For this we need to create a “Delegate” and “Event Handler”. It can shown as..











  1. public delegate void ClickEventHandler(object sender, EventArgs e);





  2. public event ClickEventHandler Click;










  3. protected void SelectList_Alpha(object sender, EventArgs e)





  4. {





  5. LinkButton lnk = (LinkButton)sender;





  6. Click(sender, e);





  7. }



Now create new page as “AlphaTest.aspx” in this page go to “design” view and drag the user control which we created.
Now go the code behind of “AlphaText.aspx”. In the page_load event create a delegate. The delegate can be created as.












  1. Alphabetic_Control1.Click += new Alphabetic_Control.ClickEventHandler(Alphabetic_Control1_Click);




The above code can be achieved as, First the ID of the User control, i.e, AplhaBeticcontrol1. when we put a “.” Inside that it will show all the methods and events. In that one select “Click”. Then put a “+”and “=” automatically designer will tell you to press the “Tab” button. Press 2 times it will generate the “Click” event.
In the click event write the fallowing code..











  1. protected void Alphabetic_Control1_Click(object sender, EventArgs e)





  2. {





  3. LinkButton lnkbtn = (LinkButton)sender;





  4. Response.Write("You Selected : " + lnkbtn.CommandName.ToString());





  5. }




Now run the "AlphaTest.aspx" page, when ever you click on the user control a event will be fired.


Download Sample Code

Forms Authentication with Active Directory in ASP.Net2.0

Saturday, November 22, 2008


What Is Active Directory
An active directory is a directory structure used on Microsoft Windows based computers and servers to store information and data about networks and domains.
ASP.Net 2.0 has membership feature which we can use for forms authentication. This feature provides an abstraction for the underlying data store that is used to maintain user credentials like as user name, password. The membership feature includes an API that helps you to easily validate user credentials and manage the user database.
To use Active Directory (AD) in ASP.Net, First we have to create “Instance For ADAM” and configuration of it. Then I will create a sample application and explain how to interact ADAM with ASP.Net.
Creating Instance and Configuration:
Install ADAM software. Then select “Create an ADAM Instance” in the start menu.

Select “A Unique Instance”, then give some name to the Instance

Give a Port number, leave default SSL port number.



Select “Yes, to create an application directory partition”.

Here O,DC are the LDAP attributes.
Leave default values for location of data file and backup file.

Provide the account under which this account runs.

It will prompt for confirmation,select “YES”. Then select System

Import all LDIF Files.


Copy contents and paste in a file(notepad, etc)

Click Next which will Instantiate new Instance.

Click Finish. And open ADAM ADSI Edit in start menu.

Right click on ADSI root node and click connect to. And enter the details as.


Right click on Distinguished name and select New -> Object in that one select “Organizational Unit” which for Admin.


Click on Finish. Now right click on the Organizational Unit which is created and select Properties, in that properties select distinguished name property and copy into a notepad.


Right click on new OU(Organizational Unit) and create a new User


Now right click on CN=TestAdminUser and select properties, in that properties change the User Principal Name as

And make the “Don’tExpirePassword” property to false.


Now right click on TestAdminUser and reset the password.

Go to CN=Roles and choose CN=Administrators and choose properties and go to member property.


Click on Add ADAM Account and add the user created above.
Create another Organizational Unit (OU) for the user to create login account programmatically.

Go to Roles and choose CN=Readers and choose properties and then select “member” property. Add ADAM account.



Now open ADAM command prompt and run command “dsmgmt.exe”


Now configure ADAM schema – Password policy setting. Type as “mmc /a”.

Click on File – Add/Remove snap – In and then click on ADD and select ADAM Schema

Select ok, ok. Right Click on ADAM Schema and change the server details. Enter the details of ADAM Instance.


Right click on Attributes and click on create attribute.





Go to Classes Node in the Adam Schema, select User and right click and choose properties and select Attributes tab.



Add all the properties created above.
Go to ADAM ADSI Edit , select the instance and right click on it. In that select Update Schema Now.

Note:I created a document of "ADAM Instance Creation" with all of screen shots. You can find below.
Interacting with ADAM with ASP.Net
Step 1: Create a website and add three pages to the application with name Registration.aspx, Login.aspx, Welcome.aspx.
Step 2: Open Registration.aspx page. Drag “CreateUserWizard” control and set the “ContinueDestinationPageUrl” as “~/login.aspx”.
Step 3: Now open login.aspx page. Drag “Login” control and set the “DestinationPageUrl” property to welcome.aspx. and set “DisplayRememberMe” to false.
Step 4: Now open the web.config file and add the blow mentioned code.




  1. <appSettings>

  2.         <add key="connectionUsername" value="CN=TestAdminUser,OU=TestAdmin,O=Admtest,DC=Testing,DC=COM"/>

  3.         <add key="connectionPassword" value="hello"/>

  4.         <add key="connectionServer" value="localhost"/>

  5.         <add key="connectionPortNumber" value="50001"/>

  6.         <add key="connectionRoot" value="O=Aest,DC=Testing,DC=COM"/>

  7.         <add key="connectionUsersContainer" value="TestUsers"/>

  8.         <add key="defaultRoles" value="Readers"/>

  9.         <add key="connectionRolesContainer" value="Roles"/>

  10.         <add key="connectionAdminsContainer" value="TestAdmin"/>

  11.     </appSettings>




  1. <appSettings>

  1. <connectionStrings>

  •         <add name="TestCon" connectionString="LDAP://localhost:50001/OU=TestUsers,O=Aest,DC=Testing,DC=COM"/>

  •     </connectionStrings>





    1. <appSettings>

    1.  <machineKey validationKey="51AF1A8093A19043C4AAEC218BC36D9C3299C06AA823DDDAC5877431E7AFE90C1B053057EA760CA4DCC15D3CED15035588BB1B461C959434DE68B8381CDF99AA" decryptionKey="BCE825E1668990B11CE01AFF01C4AFE8D63AE300958A85EC" validation="SHA1"/>

    2.         <membership defaultProvider="MyADAMMembershipProvider">

    3.             <providers>

    4.                 <add name="MyADAMMembershipProvider"

    5.          type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a"

    6.           connectionStringName="TestCon"

    7.           connectionUsername="CN=TestAdminUser,OU=TestAdmin,O=Aest,DC=Testing,DC=COM"

    8.           connectionPassword="hello"

    9.           connectionProtection="None"

    10.           enableSearchMethods="true"

    11.           requiresUniqueEmail="false"

    12.           enablePasswordReset="true"

    13.           requiresQuestionAndAnswer="true"

    14.           attributeMapPasswordQuestion="PasswordQuestion"

    15.           attributeMapPasswordAnswer="PasswordAnswer"

    16.           attributeMapFailedPasswordAnswerCount="BadPasswordAnswerCount"

    17.           attributeMapFailedPasswordAnswerTime="BadPasswordAnswerTime"

    18.           attributeMapFailedPasswordAnswerLockoutTime="BadPasswordAnswerLockoutTime"

    19.         minRequiredNonalphanumericCharacters="0"

    20.       passwordStrengthRegularExpression = "(?=.{7,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@`~$%^+=!*])"/>

    21.             </providers>

    22.         </membership>





    Once you modified web.config as like above. Then run the registration page and create a User. If user created succesfully you can find a file created with user name in "TestUsers" section of ADAM.
    Note:Add "System.DirectoryServices" assembly reference to your application.
    Download ADAM

    Download creating ADAM Instance Step by step Document.

    Download Sample Application