0

DropDownList Validation Using JQuery JavaScript In Asp.Net

This post explains DropDownList validation Using Jquery and JavaScript in Asp.Net where DropDown is either bind with SqlDataSource or listItems.

Place one drop down and button on the page in design view and add JQuery javascript file in solution and add it's reference in head section of page. write following JQuery script in head section of page.

   1:  <head runat="server">
   2:  <title></title>
   3:   
   4:  <script src="Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>  
   5:  <script type="text/javascript" language="javascript">
   6:     $(document).ready(function() {
   7:        $('#Button1').on('click', function(e) {
   8:        var selectedText = $('#DropDownList1     option:selected').text().toLowerCase();
   9:         if (selectedText == 'select') 
  10:          {
  11:            alert('Please select any language.');
  12:            e.preventDefault();
  13:          }
  14:          else
  15:                  alert('You selected ' + selectedText);
  16:          })
  17:          
  18:            
  19:   })
  20:      
  21:  </script>
  22:      
  23:  </head>


HTML Source of Drop Down And Button

   1:  <asp:DropDownList ID="DropDownList1" runat="server">
   2:  <asp:ListItem>Select</asp:ListItem>
   3:  <asp:ListItem>C#</asp:ListItem>
   4:  <asp:ListItem>VB</asp:ListItem>
   5:  <asp:ListItem>Java</asp:ListItem>
   6:  <asp:ListItem>C</asp:ListItem>
   7:   </asp:DropDownList>
   8:          
   9:  <asp:Button ID="Button1" runat="server" Text="Button" />


Now if DropDownList is getting populated from DataBase by SqlDataSource then we need to set AppendDataBoundItems property of dropdown to true and add one list item with text Select at 0th index in Page_Load event.

   1:  <asp:DropDownList ID="DropDownList2" runat="server" 
   2:                    AppendDataBoundItems="True" 
   3:                    DataSourceID="SqlDataSource1" 
   4:                    DataTextField="ProductName" 
   5:                    DataValueField="ProductID">
   6:  </asp:DropDownList>
   7:  <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
   8:  ConnectionString="<%$ ConnectionStrings:TestDbConnectionString %>" 
   9:  SelectCommand="SELECT [ProductID], [ProductName] FROM [Products]">
  10:  </asp:SqlDataSource>
  11:      
  12:  <asp:Button ID="Button2" runat="server" Text="Button" />


write following code in code behind.

protected void Page_Load(object sender, EventArgs e)
    {
        DropDownList2.Items.Add(new ListItem("select", "0"));
    }


And write following JQuery code in head section of html source of page.

   1:  <script type="text/javascript" language="javascript">
   2:  $(document).ready(function() {
   3:                 
   4:     $('#Button2').on('click', function(e) {
   5:        var selectedValue = $('#DropDownList2').val();
   6:        if (selectedValue == 0) 
   7:         {
   8:            alert('Please select any product.');
   9:            e.preventDefault();
  10:         }
  11:              else
  12:                 alert('you selected product with ID ' + selectedValue);
  13:          })
  14:      
  15:      })
  16:      
  17:  </script>


If we want to use JavaScript Instead of Jquery then write code in following way

   1:  <script type="text/javascript">
   2:         
   3:   function Validation() {
   4:       var selectedValue =       document.getElementById('<%=DropDownList2.ClientID%>').value;
   5:        if (selectedValue == "0") 
   6:        {
   7:            alert("Please Select Product");
   8:        }
   9:        else {
  10:                  alert("You selected " + selectedValue);
  11:              }
  12:          }
  13:  </script>


Call this function in OnClientClick Event of button

   1:  <asp:Button ID="Button2" runat="server" Text="Button" OnClientClick="Validation()"  />


0

Validate DropDownList Using Required Field Validator Asp.Net

This post explains How to Validate DropDownList Using RequiredFieldValidator In Asp.Net when either Dropdown is populated using SqlDataSource or when Drop Down is populated using List Items.

Place one dropdown list, button and requiredfieldvalidator controls in design view of page and add list items in HTML source of page as mentioned below.

   1:  <asp:DropDownList ID="ddlLanguage" runat="server">
   2:  <asp:ListItem>--Select--</asp:ListItem>
   3:  <asp:ListItem>C#</asp:ListItem>
   4:  <asp:ListItem>VB</asp:ListItem>
   5:  <asp:ListItem>Java</asp:ListItem>
   6:  </asp:DropDownList>


Set ControlToValidate, InitialValue, Error Message properties of required field validator as follows.

   1:  <asp:RequiredFieldValidator ID="rfvDdl" runat="server" 
   2:     ControlToValidate="ddlLanguage" 
   3:     ErrorMessage="Please Select a Language" 
   4:     InitialValue="--Select--" 
   5:     SetFocusOnError="True">
   6:  </asp:RequiredFieldValidator>


If dropdownlist is getting populated by SqlDataSource or ObjectDataSource at runtime then we need to set AppendDataBoundItems property of dropdown to true and add one list item at 0 or -1 index in Page_Load event of page.

   1:  <asp:DropDownList ID="ddlProducts" runat="server" 
   2:          AppendDataBoundItems="True" 
   3:          DataSourceID="SqlDataSource1" 
   4:          DataTextField="ProductName" 
   5:          DataValueField="ProductID">
   6:  </asp:DropDownList>
   7:   
   8:  <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
   9:          ConnectionString="<%$ ConnectionStrings:TestDbConnectionString %>" 
  10:          SelectCommand="SELECT [ProductName], [ProductID] FROM [Products]">
  11:  </asp:SqlDataSource>
  12:   
  13:  <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
  14:          ControlToValidate="ddlProducts" 
  15:          ErrorMessage="Please select a product" 
  16:          InitialValue="0" SetFocusOnError="True">
  17:  </asp:RequiredFieldValidator>


Write following code in Page_Load Event in code behind.

protected void Page_Load(object sender, EventArgs e)
    {
        ddlProducts.Items.Insert(0,new ListItem("Choose Product","0"));
    }


Build and run the code.

0

ASP.NET TextBox Remaining Character Counter JavaScript

This example illustrate how to count and show remaining characters in TextBox using JavaScript in Asp.Net.
Create a new website in Visual Studio and place one TextBox and Label on the default.aspx page in design mode.

Go to HTML source of page and write a JavaScript function named Count in head section of page to count remaining characters in TextBox.

Set the MaxLength property of TextBox to 10 chars.


   1:  <head runat="server">
   2:  <title>Remaining Characters Counter</title>
   3:  <script type="text/javascript">
   4:  function Count() {
   5:   
   6:  var i = document.getElementById("TextBox1").value.length;
   7:  document.getElementById("Label1").innerHTML = 10 - i;
   8:          }
   9:  </script>
  10:  </head>

Call this javascript function in onkeyup event of textbox.
   1:  <asp:TextBox ID="TextBox1" runat="server" 
   2:          MaxLength="10" onkeyup="Count()">
   3:  </asp:TextBox>


0

Configure Unique Document IDs Feature In SharePoint 2010

This post explains how to Enable Activate Or Configure Unique Document IDs Feature In SharePoint 2010 For better Document Management.

Open your site collection in browser and login with administrator account

Click on Site Actions > Site Settings

Unique Document ID In SharePoint 2010


Select Site collection features from Site Collection Administration section
sharepoint 2010 document id

Activate Document ID Service
After activation it will look like shown in image 

Now go back to Site Actions > Site Settings and select Document ID Settings 

Document ID Settings
Here you can customize the document ID to begin with characters you want 


Now you can see the document ID by selecting the document and clicking on View Properties icon on top ribbon 



Alternatively you can add document id column to be displayed 

check the document, Click on Library > Modify View and check the Document ID Checkbox and finish it 





Hope this helps

1

Asp.Net Bind Populate DropDownList With JQuery And XML

In this example i'm explaining How To Populate Or Bind DropDownList With JQuery And XML In Asp.Net.
bind populate dropdownlist with jquery and xml

Add jquery library reference in head section and place one dropdown on the page.

Add one list item with select as it's value.

   1:  <asp:DropDownList ID="DropDownList1" runat="server">
   2:  <asp:ListItem>Select</asp:ListItem>
   3:  </asp:DropDownList>
   4:   
   5:  <asp:Label ID="Label1" runat="server" Text=""/>


Following is the Cities.xml file i'm using to bind dropdownlist using jquery.


  
    Mumbai
    1
  
    
    Delhi
      2
  
  
    Banglore
    3
  
  
    Chennai
    4
  

Add this script in head section of page.

  

Build and run the code.

0

AjaxFileUpload AsyncFileUpload In ModalPopUp Extender Asp.Net

This example shows how to use AjaxFileUpload Control Or AsyncFileUpload In ModalPopUp Extender Using C# VB Asp.Net.

Place ToolkitScriptManager and a button inside UpdatePanel on the page, we will open ModalPopup in click event of this button to upload files.

Create one panel on the page and add AjaxFileUpload or Ajax AsyncFileUpload in it.

Async Ajax FileUpload In ModalPopUp Extender


HTML Source
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"/>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="btnUpload" runat="server" 
            Text="Upload File" onclick="btnUpload_Click"/>
            
<asp:ModalPopupExtender runat="server" 
                        ID="modelPopupExtender1" 
                        TargetControlID="btnUpload"
                        PopupControlID="popUpPanel" 
                        OkControlID="btOK" 
                        BackgroundCssClass="modalBackground">
</asp:ModalPopupExtender>
 
 <asp:Panel ID="popUpPanel" runat="server" CssClass="pnl">
 <div style="font-weight: bold; border: Solid 3px Aqua; 
                                background-color: AliceBlue">
 
 <asp:AjaxFileUpload ID="AjaxFileUpload1" runat="server" 
                     OnUploadComplete="UploadComplete" 
                     OnClientUploadComplete="Success" 
                     ThrobberID="loader" Width="400px"/>
 <asp:Image ID="loader" runat="server" 
            ImageUrl ="~/loading.gif" 
            Style="display:None"/>
 </div><br /><br />
 <asp:Label ID="lblMessage" runat="server"/><br /><br />
 <asp:Button ID="btOK" runat="server" Text="OK" />
 <asp:LinkButton ID="LinkButton1" runat="server" CssClass="close" 
 OnClientClick="$find('modelPopupExtender1').hide(); return false;"/>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>


If you are using AsyncFileUpload Control then don't forget to set UploaderStyle property to Traditional, other wise it will throw invalid argument error.

<ajax:AsyncFileUpload ID="AsyncFileUpload1" runat="server" 
                      UploadingBackColor="Blue" 
                      CompleteBackColor="WhiteSmoke"
                      OnUploadedComplete="SaveUploadedFile" 
                      OnClientUploadComplete="Success" 
                      OnClientUploadError="Error"
                      UploaderStyle="Traditional"/>


Add following Javascript and CSS in head section of page.



Write following code in OnUploadComplete event to save file on server.

protected void UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
    {
        string path = Server.MapPath("~/Uploads/") + e.FileName;
        AjaxFileUpload1.SaveAs(path);
    }


Build and run the code.

Download Sample Code


0

Allow Enable Anonymous Access In SharePoint 2010 Sites

This Post explains How To Allow Or Enable Anonymous Access In SharePoint 2010 Sites Collections.

1. Open SharePoint 2010 Central Administration, Go to Manage Web Applications

Allow Anonymous Access In SharePoint 2010 SItes


Select Your Site and click on Authentication Providers icon in the top ribbon bar 

SharePoint 2010 Enable Anonymous Access


Click on Default Zone and Check the Enable Anonymous Access CheckBox and save it

Anonymous Access



2. Select your site and click on Anonymous Policy Icon In ribbon

Anonymous Policy


Select Default Zone from dropdown and select the permissions option you want to grant to anonymous users Selecting None - No Policy is recommended )



3. Close Central Administration and open your site collection in browser with administrator account (Site for which you just had set anonymous access)

Click on Site Actions and select Site Permissions

Site Permissions


Click on Anonymous Access Icon on the top ribbon



Select Entire Web Site Option and click on OK



Now you can browse your site Anonymously without login.



Hope this helps.

4

Ajax AutoCompleteExtender In Master Page Asp.Net

This Example shows How To Use Ajax AutoCompleteExtender TextBox In Master Page In Asp.Net.

Open Visual Studio and create new website, add master page in it and design it as you want.

Create a BIN folder in application and add AjaxControlToolkit.dll in it.

I have use Northwind database to fetch names for AutoCompletion list.

Add Connection String in web.config file

<connectionStrings>
<add name="NorthwindConnectionString" 
     connectionString="Data Source=AMITJAIN\SQL;
                       Initial Catalog=Northwind;
                       User ID=amit;Password=password"
providerName="System.Data.SqlClient"/>
</connectionStrings>


Place ToolkitScriptManager on Master Page inside form tag, one textbox and Add Ajax AutoComplete Extender from Toolbox.

HTML SOURCE OF MASTER PAGE
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"/>
 
<asp:TextBox ID="txtAutoComplete" runat="server"/>
                               
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" 
                          runat="server" 
                          DelimiterCharacters="" 
                          Enabled="True" 
                          ServicePath="~/AutoComplete.asmx" 
                          ServiceMethod="GetCompletionList"
                          TargetControlID="txtAutoComplete"
                          MinimumPrefixLength="1" 
                          CompletionInterval="10" 
                          EnableCaching="true"
                          CompletionSetCount="12">
</asp:AutoCompleteExtender>
                
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
 
</form>
</body>
</html>


We can set CompletionList WIdth and styles using CSS or use AutoCompleteExtender In GridView or Windows Forms Application.

Add new webservice, name it AutoComplete.asmx and write following code in it's code behind.

C#
using System.Collections.Generic;
using System.Web.Services;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class AutoComplete : System.Web.Services.WebService {

    public AutoComplete () 
    {
    }

    [WebMethod]
    public string[] GetCompletionList(string prefixText, int count)
    {
        if (count == 0)
        {
            count = 10;
        }
        DataTable dt = GetRecords(prefixText);
        List items = new List(count);

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            string strName = dt.Rows[i][0].ToString();
            items.Add(strName);
        }
        return items.ToArray();
    }

    public DataTable GetRecords(string strName)
    {
        string strConn = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(strConn);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.Parameters.AddWithValue("@Name", strName);
        cmd.CommandText = "Select FirstName from Employees where FirstName like '%'+@Name+'%'";
        DataSet objDs = new DataSet();
        SqlDataAdapter dAdapter = new SqlDataAdapter();
        dAdapter.SelectCommand = cmd;
        con.Open();
        dAdapter.Fill(objDs);
        con.Close();
        return objDs.Tables[0];
    }
}

VB.NET
Imports System.Collections.Generic
Imports System.Web.Services
Imports System.Data.SqlClient
Imports System.Data
Imports System.Configuration

 _
 _
 _
Public Class AutoComplete
 Inherits System.Web.Services.WebService

 Public Sub New()
 End Sub

  _
 Public Function GetCompletionList(prefixText As String, count As Integer) As String()
  If count = 0 Then
   count = 10
  End If
  Dim dt As DataTable = GetRecords(prefixText)
  Dim items As New List(Of String)(count)

  For i As Integer = 0 To dt.Rows.Count - 1
   Dim strName As String = dt.Rows(i)(0).ToString()
   items.Add(strName)
  Next
  Return items.ToArray()
 End Function

 Public Function GetRecords(strName As String) As DataTable
  Dim strConn As String = ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString
  Dim con As New SqlConnection(strConn)
  Dim cmd As New SqlCommand()
  cmd.Connection = con
  cmd.CommandType = System.Data.CommandType.Text
  cmd.Parameters.AddWithValue("@Name", strName)
  cmd.CommandText = "Select FirstName from Employees where FirstName like '%'+@Name+'%'"
  Dim objDs As New DataSet()
  Dim dAdapter As New SqlDataAdapter()
  dAdapter.SelectCommand = cmd
  con.Open()
  dAdapter.Fill(objDs)
  con.Close()
  Return objDs.Tables(0)
 End Function
End Class


Build and run the application.

1

Validation Of ViewState MAC Failed Error Asp.Net

If you are receiving Validation Of ViewState MAC Failed Error In Asp.Net web application.

This occurs if you are using controls like Gridview or Detailsview with DataKeyNames on the page and page takes long time in loading.

This issue has been fixed in .Net framework 2.0 SP2 and .Net framework 3.5 SP1. so upgrading to service packs is best option to fix validation of viewstate mac failed error.

Other workarounds can be

1. Set enableEventValidation to false and viewStateEncryptionMode to Never in web.config.
   1:  <pages enableeventvalidation="false" 
   2:         viewstateencryptionmode="Never">


5

Custom Login Web Part In SharePoint 2010 Forms Based

This post explains How To Create Custom Login Web Part In SharePoint 2010 For Forms Based Authentication FBA.

Before creating Login WebPart we need to setup and configure Membership Provider Database and Forms Based Authentication(FBA) In SharePoint 2010 and can optionally Allow Anonymous Access to sharepoint web application and sites collection.

1. Create Visual Web Part In Visual Studio 2010
Open VS 2010 and create new project by selecting New > Project from File Menu

Create Custom Login WebPart In SharePoint 2010 For Forms Based Authentication FBA


Choose SharePoint 2010 in left pane and select Empty SharePoint Project, name it LoginWebPart.

Select Deploy as a farm solution option from next screen and click on finish

Right click on solution explorer and select Add > New Item

Visual Web Part For Login In SharePoint 2010


Choose Visual Web Part from the list and name it LoginWebPart

2. Add Reference To Assemblies
2a. Add reference to Microsoft.SharePoint.IdentityModel.dll
Right click on Refrences in solution explorer, select add reference and browse to
C:\Windows\assembly\GAC_MSIL\Microsoft.SharePoint.IdentityModel\14.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.IdentityModel.dll 

2b. Add reference to Microsoft.IdentityModel.dll
Select add reference and browse to
C:\Program Files\Reference Assemblies\Microsoft\Windows Identity Foundation\v3.5\Microsoft.IdentityModel.dll

2c. Add reference toSystem.IdentityModel.dll
Browse to C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.0\System.IdentityModel.dll

2d. Add Microsoft.SharePoint.IdentityModel assembly reference in Page Directive of LoginWebPartUserControl.ascx

Assembly reference to Microsoft.IdentityModel.dll


3. Place Login Control on the LoginWebPartUserControl

HTML SOURCE
<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
 
<%@ Assembly Name="Microsoft.SharePoint.IdentityModel, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
 
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 
 
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" 
             Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 
 
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" 
             Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
 
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" 
             Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
 
<%@ Import Namespace="Microsoft.SharePoint" %> 
 
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" 
             Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
 
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="LoginWebPartUserControl.ascx.cs" 
            Inherits="LoginWebPart.LoginWebPart.LoginWebPartUserControl" %>
 
 
<asp:Login ID="Login1" runat="server" 
           FailureText="<%$ Resources:wss,login_pageFailureText %>" 
           onauthenticate="Login1_Authenticate">
</asp:Login>


4. Go to Code behind of user control and add following reference
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.IdentityModel;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System.IdentityModel.Tokens;


Write following code in Login1_Authenticate Event of Login Control

protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
        {
            string membership = "MembershipProvider";
            string role = "RoleProvider";

            e.Authenticated = SPClaimsUtility.AuthenticateFormsUser(new Uri(SPContext.Current.Web.Url),Login1.UserName,Login1.Password);

            if (!e.Authenticated) return;

            SecurityToken token = SPSecurityContext.SecurityTokenForFormsAuthentication(new Uri(SPContext.Current.Web.Url), membership, role, Login1.UserName, Login1.Password);
            if (token == null)
            {

                e.Authenticated = false;
                return;
            }
            else
            {

                SPFederationAuthenticationModule module = SPFederationAuthenticationModule.Current;
                module.SetPrincipalAndWriteSessionToken(token);
                e.Authenticated = true;

                SPUtility.Redirect(SPContext.Current.Web.Url, SPRedirectFlags.Trusted, this.Context);

            }
        }


Build and Deploy Solution by clicking on Build Menu and select Deploy Solution From Visual Studio

5. Open SharePoint site in browser and login with administrator account

Click on Site Actions and Select Edit Page



Click on Insert and select Web Part from the top ribbon



Select Custom from Categories And select LoginWebPart, Click on Add and Save And Close





Hope this helps

7

Asp.Net AjaxFileUpload Control With Drag Drop And Progress Bar

This Example explains how to use AjaxFileUpload Control With Drag Drop And Progress Bar Functionality In Asp.Net 2.0 3.5 4.0 C# And VB.NET.

May 2012 release of AjaxControlToolkit includes a new AjaxFileUpload Control which supports Multiple File Upload, Progress Bar and Drag And Drop functionality.

These new features are supported by Google Chrome version 16+, Firefox 8+ , Safari 5+ and Internet explorer 10 + , IE9 or earlier does not support this feature.

AjaxFileUpload Control Example with Drag Drop And Progress Bar

To start with it, download and put latest AjaxControlToolkit.dll in Bin folder of application, Place ToolkitScriptManager and AjaxFileUpload on the page.

HTML SOURCE
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"/>
          
<asp:AjaxFileUpload ID="AjaxFileUpload1" runat="server" 
                    OnUploadComplete="UploadComplete" 
                    ThrobberID="loader"/>
 
<asp:Image ID="loader" runat="server" 
           ImageUrl ="~/loading.gif" Style="display:None"/>


ThrobberID is used to display loading image instead of progress bar in unsupported browsers.

Type of files uploaded can be restricted by using AllowedFileTypes property with comma separated list such as "zip,doc,pdf".

Write following code in OnUploadComplete event to save the file.

C#
protected void UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
    {
        string path = Server.MapPath("~/Uploads/") + e.FileName;
        AjaxFileUpload1.SaveAs(path);
    }
VB.NET
protected void UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
    {
        string path = Server.MapPath("~/Uploads/") + e.FileName;
        AjaxFileUpload1.SaveAs(path);
    }
Build and run the code.

Download Sample Code


0

Ajax ConfirmButtonExtender With ModalPopUp In GridView Asp.Net

This example implements Ajax ConfirmButtonExtender With ModalPopUp Extender In Asp.Net GridView to show Delete Confirmation before deleting records.

Populate GridView using SqlDataSource and add one LinkButton inside TemplateField in Columns.

   1:  <asp:TemplateField HeaderText="Delete">
   2:  <ItemTemplate>
   3:  <asp:LinkButton ID="lnkDel" runat="server" 
   4:                  CommandName="Delete" Text="Delete"/>


Place ToolkitScriptManager and UpdatePanel on the page and add ConfirmButton, ModalPopUpExtender and Panel to pop inside Template field we added earlier.

HTML SOURCE
<div>
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"/>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
        
<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" 
              DataKeyNames="ProductID" 
              DataSourceID="SqlDataSource1"
              onrowdeleted="GridView1_RowDeleted">
<Columns>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton ID="lnkDel" runat="server" 
                CommandName="Delete" Text="Delete"/>
                
<asp:ConfirmButtonExtender ID="ConfirmButtonExtender1" 
                           runat="server" 
                           TargetControlID="lnkDel"
                           DisplayModalPopupID="ModalPopupExtender1"/>
                                        
<asp:ModalPopupExtender ID="ModalPopupExtender1" 
                        runat="server"
                        TargetControlID="lnkDel"
                        PopupControlID="pnlModal"
                        BackgroundCssClass="Background"
                        OkControlID="btnYes"
                        CancelControlID="btnNo"
                        X="80"
                        Y="80"/>
 
<asp:Panel runat="Server" ID="pnlModal" CssClass="Pnl">
<br />         
Do you want to delete this record
<br /><br />
<asp:Button ID="btnYes" runat="server" Text="Yes"/>
<asp:Button ID="btnNo" runat="server" Text="No"/>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
 
<asp:BoundField DataField="ProductID" HeaderText="ProductID"/>
<asp:BoundField DataField="ProductName" HeaderText="ProductName"/> 
<asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice"/> 
<asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock"/> 
</Columns>
</asp:GridView>
 
<asp:Label ID="lblMessage" runat="server" Text=""/>
</ContentTemplate>
</asp:UpdatePanel>
 
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" 
DeleteCommand="DELETE FROM [Products] 
               WHERE [ProductID] = @ProductID" 
SelectCommand="SELECT [ProductID], [ProductName], 
              [UnitPrice], [UnitsInStock] FROM [Products]" 
        
<DeleteParameters>
<asp:Parameter Name="ProductID" Type="Int32" />
</DeleteParameters>
</asp:SqlDataSource>
</div>


Add following CSS style in Head section of the page.
  

Build and run the code

AJax ConfirmButtonExtender With ModalPopUp In GridView Asp.Net

Download Sample Code




1

Populate Bind DropDownList From XML File In Asp.Net

This Example explains how to Populate Or Bind DropDownList With XML File Data In Asp.Net In 3/n Tier Architecture Using C# And VB.

Populate Bind DropDownList From XML File
Place one DropdownList on the page.

<asp:DropDownList ID="DropDownList1" 
                  runat="server" 
                  onselectedindexchanged
  ="DropDownList1_SelectedIndexChanged">


XML Data Can be in various formats, i'll use 3 different ones shown below.


Sample 1.
   1:  <?xml version="1.0" encoding="utf-8" ?>
   2:  <Employees>
   3:    <Detail>
   4:      <ID>1</ID>
   5:      <Name>Csharp</Name>
   6:    </Detail>
   7:    <Detail>
   8:      <ID>2</ID>
   9:      <Name>AspNet</Name>
  10:    </Detail>
  11:    <Detail>
  12:      <ID>3</ID>
  13:      <Name>Articles</Name>
  14:    </Detail>
  15:  </Employees>

Another format can be
   1:  <?xml version="1.0" encoding="utf-8" ?>
   2:  <Employees>
   3:    <Detail ID="1" Name="Csharp"></Detail>
   4:    <Detail ID="2" Name="AspNet"></Detail>
   5:    <Detail ID="3" Name="Articles"></Detail>
   6:  </Employees>

Writing following code in Page_Load event is enough to bind dropdownlist from these types of XML data.

C#
using System.Data;
using System.Xml;
protected void Page_Load(object sender, EventArgs e)
{
        DataSet dsXml = new DataSet();
        dsXml.ReadXml(Server.MapPath("~/XMLFile2.xml"));
        DropDownList1.DataSource = dsXml;
        DropDownList1.DataTextField = "Name";
        DropDownList1.DataValueField = "ID";
        DropDownList1.DataBind();
        DropDownList1.AutoPostBack = true;
}

VB.NET
Protected Sub Page_Load(sender As Object, e As EventArgs)
 Dim dsXml As New DataSet()
 dsXml.ReadXml(Server.MapPath("~/XMLFile2.xml"))
 DropDownList1.DataSource = dsXml
 DropDownList1.DataTextField = "Name"
 DropDownList1.DataValueField = "ID"
 DropDownList1.DataBind()
 DropDownList1.AutoPostBack = True
End Sub


If XML format is mix of above two.
   1:  <?xml version="1.0" encoding="utf-8" ?>
   2:  <Details>
   3:    <Name ID="1">Amit</Name>
   4:    <Name ID="2">Jain</Name>
   5:    <Name ID="3">Csharp</Name>
   6:    <Name ID="4">AspNet</Name>
   7:    <Name ID="5">Articles</Name>
   8:  </Details>

We need to loop through nodes to fine value of ID attribute.

C#
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(Server.MapPath("~/XMLFile.xml"));
            XmlNodeList list = doc.GetElementsByTagName("Name");
            foreach (XmlNode node in list)
            {
                ListItem lItem = new ListItem(node.InnerText, node.Attributes["ID"].Value);
                DropDownList1.Items.Add(lItem);
            }
            DropDownList1.Items.Insert(0, "--Select--");
            DropDownList1.SelectedIndex = 0;
            DropDownList1.AutoPostBack = true;
        }
    }

VB
Protected Sub Page_Load(sender As Object, e As EventArgs)
 If Not IsPostBack Then
  Dim doc As New XmlDocument()
  doc.Load(Server.MapPath("~/XMLFile.xml"))
  Dim list As XmlNodeList = doc.GetElementsByTagName("Name")
  For Each node As XmlNode In list
   Dim lItem As New ListItem(node.InnerText, node.Attributes("ID").Value)
   DropDownList1.Items.Add(lItem)
  Next
  DropDownList1.Items.Insert(0, "--Select--")
  DropDownList1.SelectedIndex = 0
  DropDownList1.AutoPostBack = True
 End If
End Sub


To Bind DropDownList in 3 tier architecture environment, add to new class files in App_Code folder of application and name them DataLayer.cs and BusinessLayer.cs

Write Following code in these class respectively.

Data Access Layer (DAL)
using System.Web;
using System.Xml;
public class DataLayer
{
 public DataLayer()
 {
 }
    public XmlDocument GetXmlData()
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(HttpContext.Current.Server.MapPath("~/XMLFile.xml"));
        return doc;
    }
}

Business Access Layer (BAL)
using System.Web.UI.WebControls;
using System.Xml;
public class BusinessLayer
{
 public BusinessLayer()
 {
    }
    public ListItemCollection BindDropDownList()
    {
        ListItemCollection ddlItems = new ListItemCollection();
        DataLayer objDAL = new DataLayer();
        XmlNodeList list = objDAL.GetXmlData().GetElementsByTagName("Name");
        foreach (XmlNode node in list)
        {
           ListItem item = new ListItem(node.InnerText, node.Attributes["ID"].Value);
           ddlItems.Add(item);
            
        }
        return ddlItems;
    }
}

Write code in Page_Load event of aspx page (Presentation Layer)
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BusinessLayer objBAL = new BusinessLayer();
            DropDownList1.DataSource = objBAL.BindDropDownList();
            DropDownList1.DataBind();
            DropDownList1.Items.Insert(0, "--Select--");
            DropDownList1.SelectedIndex = 0;
            DropDownList1.AutoPostBack = true;
        }
    }


Find More Articles