20

Ajax ModalPopUpExtender Example

In this post i'm showing Ajax ModalPopUpExtender Example In Asp.Net 2.0,3.5,4.0 Using C# VB.NET to open popup on mouseover. For this to work u need to download and install ajaxcontroltoolkit

Ajax ModalPopUpExtender Example In Asp.Net
I have also implement ModalPopUpExtender In Gridview to show master detail data.

Create a new website in visual studio

Add one hyperlink on the page and write html markup of ModalPopExtender to open popup on mouse over on hyperlink on aspx page as shown below.

Put AjaxControlToolkit.dll in BIN folder and register assembly in page directive of ur aspx page.

<%@ Register Assembly="AjaxControlToolkit" 
Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>

Add this javascript method between <head></head> section of page

<script type="text/javascript">
function MouseHover() 
{
$find("modelPopupExtender1").show();
}
</script>

Add new StyleSheet to solution and write below mentioned css style in it.

body { 
    BACKGROUND: #fff;FONT: 12px/1.25 "Helvetica Neue", Arial, sans-serif; 
    COLOR: #222;
}
.confirm-dialog { 
    BACKGROUND: url(img/box.png) no-repeat left top; 
    MARGIN: 0px auto;WIDTH: 330px;PADDING-TOP: 14px; 
    POSITION: relative;
}
.confirm-dialog .inner { 
    PADDING-RIGHT: 20px;PADDING-LEFT: 20px; 
    PADDING-BOTTOM: 11px;BACKGROUND: url(img/box.png) no-repeat left bottom; 
    FLOAT: left;MARGIN: 0px 0px -20px 0px;WIDTH: 290px;PADDING-TOP: 0px;
} 
.confirm-dialog .base { 
    BORDER-TOP: #ddd 1px solid;BACKGROUND: url(img/base.png) no-repeat left bottom; 
    PADDING-BOTTOM: 4px;MARGIN-LEFT: -11px;MARGIN-RIGHT: -11px; 
    PADDING-TOP: 4px;TEXT-ALIGN: center;
}
.confirm-dialog H2 { 
    FONT-WEIGHT: bold;FONT-SIZE: 1.25em;COLOR: #f60;TEXT-ALIGN: center;
} 
.confirm-dialog input { 
    WIDTH:50px;
}     
.close { 
    DISPLAY: block;BACKGROUND: url(img/close.png) no-repeat 0px 0px; 
    LEFT: -5px;WIDTH: 26px;TEXT-INDENT: -1000em;POSITION: absolute; 
    TOP: -7px;HEIGHT: 26px; 
}   
.modalBackground {
    background-color:Gray;filter:alpha(opacity=70);opacity:0.7;
} 


HTML SOURCE
<Ajax:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"/>
<p style="background-color: #9999FF; width: 95%;">
Example of using a ModalPopupExtender with with Mouse Over
<br/></p><br/>
Hover over the hyperlink 
 
<asp:HyperLink ID="HyperLink1" runat="server" 
               onmouseover="MouseHover();" 
               Font-Underline="True" ForeColor="Blue">
               <b>Mouse Over Here to Open PopUp</b>
</asp:HyperLink> to open pop up
            
<Ajax:ModalPopupExtender runat="server" 
                   BehaviorID="modalPopupExtender1" 
                   TargetControlID="HyperLink1"
                   PopupControlID="popUpPanel" 
                   OkControlID="btnOk" 
                   BackgroundCssClass="modalBackground" >
</Ajax:ModalPopupExtender>
 
<asp:Panel ID="popUpPanel" runat="server" CssClass="confirm-dialog">
<div class="inner">
<h2>Thanks For Visiting This Site</h2>
<div class="base">
<asp:Button ID="btnOk" runat="server" Text="Ok"/>
<asp:LinkButton ID="LinkButton1" runat="server" CssClass="close" 
OnClientClick="$find('modelPopupExtender1').hide(); return false;"/>
</div></div>
</asp:Panel>


Download Sample Code


20

Import Gmail Contacts In Asp.Net

Import Gmail Contacts In Asp.Net 2.0,3.5,4.0 Using Google Data API C# And VB.NET. Several times we need to create web applications which require to import or fetch Gmail Contacts or address book. This example will explain how to fetch or import Gmail contacts in Asp.net web applications.

Import Gmail Contacts In Asp.Net
For Importing Gmail Contacts in asp.net application we need to download Google Data API and install on system to get the desired dlls.

Create a new website and visual studio and put these 3 dlls in BIN folder of application from the location google data API has been installed on ur system.

1. Google.GData.Client
2. Google.GData.Contacts
3. Google.GData.Extensions


Add references to these dlls in your application by right clicking on solution explorer and select add reference.

Add two text box and one list box on aspx page and design it to look better.

Add one button to the page for importing the Gmail contacts or address book in Click Event.


HTML Markup Of Page
<form id="form1" runat="server">
    <div>
    
        <b>Email Address : </b>
        <br />
        <asp:TextBox ID="txtEmail" runat="server">
        </asp:TextBox>
        <br />
        <br />
        <b>Password : </b>
        <br />
        <asp:TextBox ID="txtPassword" runat="server" 
                     TabIndex="1" TextMode="Password">
        </asp:TextBox>
        <br />
        <br />
        <asp:Button ID="btnContacts" runat="server"  
                    onclick="btnContacts_Click" 
                    TabIndex="2" Text="Import Contacts" 
                    Width="125px" />
        <br />
        <br />
        <br />
        <b>Contacts:<br />
        </b>
        <asp:ListBox ID="lstContacts" runat="server" 
                     Height="176px" 
                     Width="229px">
        </asp:ListBox>
        <br />
        <br />
    
    </div>
    </form>

Go to code behind of aspx page and add directives mentioned below
using Google.Contacts;
using Google.GData.Client;
using Google.GData.Contacts;
using Google.GData.Extensions;

Now in design view of page double click on button to generate Click event and write below mentioned code in click event of button to fetch or import gmail contacts in list box

C# Code Behind
protected void btnContacts_Click(object sender, EventArgs e)
    {
        //Provide Login Information
        RequestSettings rsLoginInfo = new RequestSettings("", txtEmail.Text, txtPassword.Text);
        rsLoginInfo.AutoPaging = true;

        // Fetch contacts and dislay them in ListBox
        ContactsRequest cRequest = new ContactsRequest(rsLoginInfo);
        Feed <contact> feedContacts = cRequest.GetContacts();
        foreach (Contact gmailAddresses in feedContacts.Entries)
        {
            Console.WriteLine("\t" + gmailAddresses.Title);
            lstContacts.Items.Add(gmailAddresses.Title);
            foreach (EMail emailId in gmailAddresses.Emails)
            {
                Console.WriteLine("\t" + emailId.Address);
                lstContacts.Items.Add(" " + emailId.Address);
            }
        }

    }

VB.NET Code Behind
Protected Sub btnContacts_Click(sender As Object, e As EventArgs)
 'Provide Login Information
 Dim rsLoginInfo As New RequestSettings("", txtEmail.Text, txtPassword.Text)
 rsLoginInfo.AutoPaging = True

 ' Fetch contacts and dislay them in ListBox
 Dim cRequest As New ContactsRequest(rsLoginInfo)
 Dim feedContacts As Feed(Of Contact) = cRequest.GetContacts()
 For Each gmailAddresses As Contact In feedContacts.Entries
  Console.WriteLine(vbTab + gmailAddresses.Title)
  lstContacts.Items.Add(gmailAddresses.Title)
  For Each emailId As EMail In gmailAddresses.Emails
   Console.WriteLine(vbTab + emailId.Address)
   lstContacts.Items.Add(" " + emailId.Address)
  Next
 Next

End Sub


Now this should show contacts in list box

Hope this helps


Download sample code attached


41

Resize Image Before/And Upload To Databse ASP.NET

Resize Image Before/And Upload To SqlServer Databse In ASP.NET 2.0,3.5,4.0 Using C# VB.NET. For this i am using FileUpload control to upload the image in datbase after resizing, and displaying Images in Gridview.

Resize Image And Upload To SqlServer Databse In ASP.NET


HTML SOURCE OF PAGE
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:FileUpload ID="FileUpload1" runat="server" /><br />
<br />
<asp:Button ID="btnUpload" runat="server" 
            OnClick="btnUpload_Click" Text="Upload" />
<br />
<br />
<asp:Label ID="lblMessage" runat="server"></asp:Label>

<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" DataKeyNames="ID"
              DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" 
                InsertVisible="False" ReadOnly="True"
                               SortExpression="ID" />
<asp:BoundField DataField="ImageName" HeaderText="ImageName" 
                               SortExpression="ImageName" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" 
           ImageUrl='<%# "Handler.ashx?ID=" + Eval("ID")%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ID], [ImageName], [Image] 
              FROM [Images]"></asp:SqlDataSource>
    
    </div>
    </form>


C# CODE
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data.SqlClient;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing;


public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
protected void btnUpload_Click(object sender, EventArgs e)
{
 string strImageName = txtName.Text.ToString();
 if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
 {
    string strExtension = System.IO.Path.GetExtension(FileUpload1.FileName);
    if ((strExtension.ToUpper() == ".JPG") | (strExtension.ToUpper() == ".GIF"))
    {
     // Resize Image Before Uploading to DataBase
      System.Drawing.Image imageToBeResized = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
      int imageHeight = imageToBeResized.Height;
      int imageWidth = imageToBeResized.Width;
      int maxHeight = 240;
      int maxWidth = 320;
      imageHeight = (imageHeight * maxWidth) / imageWidth;
      imageWidth = maxWidth;

              if (imageHeight > maxHeight)
                {
                    imageWidth = (imageWidth * maxHeight) / imageHeight;
                    imageHeight = maxHeight;
                }

                Bitmap bitmap = new Bitmap(imageToBeResized, imageWidth, imageHeight);
                System.IO.MemoryStream stream = new MemoryStream();
                bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                stream.Position = 0;
                byte[] image = new byte[stream.Length + 1];
                stream.Read(image, 0, image.Length);



                // Create SQL Connection 
                SqlConnection con = new SqlConnection();
                con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

                // Create SQL Command 

                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "INSERT INTO Images(ImageName,Image) VALUES (@ImageName,@Image)";
                cmd.CommandType = CommandType.Text;
                cmd.Connection = con;

                SqlParameter ImageName = new SqlParameter("@ImageName", SqlDbType.VarChar, 50);
                ImageName.Value = strImageName.ToString();
                cmd.Parameters.Add(ImageName);

                SqlParameter UploadedImage = new SqlParameter("@Image", SqlDbType.Image, image.Length);
                UploadedImage.Value = image;
                cmd.Parameters.Add(UploadedImage);
                con.Open();
                int result = cmd.ExecuteNonQuery();
                con.Close();
                if (result > 0)
                    lblMessage.Text = "File Uploaded";
                GridView1.DataBind();
            }
        }
    }
}


VB.NET
Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.IO
Imports System.Data.SqlClient
Imports System.Drawing.Imaging
Imports System.Drawing.Drawing2D
Imports System.Drawing


Public Partial Class _Default
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        
    End Sub
    Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim strImageName As String = txtName.Text.ToString()
        If FileUpload1.PostedFile IsNot Nothing AndAlso FileUpload1.PostedFile.FileName <> "" Then
            Dim strExtension As String = System.IO.Path.GetExtension(FileUpload1.FileName)
            If (strExtension.ToUpper() = ".JPG") Or (strExtension.ToUpper() = ".GIF") Then
                ' Resize Image Before Uploading to DataBase
                Dim imageToBeResized As System.Drawing.Image = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream)
                Dim imageHeight As Integer = imageToBeResized.Height
                Dim imageWidth As Integer = imageToBeResized.Width
                Dim maxHeight As Integer = 240
                Dim maxWidth As Integer = 320
                imageHeight = (imageHeight * maxWidth) / imageWidth
                imageWidth = maxWidth
                
                If imageHeight > maxHeight Then
                    imageWidth = (imageWidth * maxHeight) / imageHeight
                    imageHeight = maxHeight
                End If
                
                Dim bitmap As New Bitmap(imageToBeResized, imageWidth, imageHeight)
                Dim stream As System.IO.MemoryStream = New MemoryStream()
                bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg)
                stream.Position = 0
                Dim image As Byte() = New Byte(stream.Length) {}
                stream.Read(image, 0, image.Length)
                
                
                
                ' Create SQL Connection 
                Dim con As New SqlConnection()
                con.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
                
                ' Create SQL Command 
                
                Dim cmd As New SqlCommand()
                cmd.CommandText = "INSERT INTO Images(ImageName,Image) VALUES (@ImageName,@Image)"
                cmd.CommandType = CommandType.Text
                cmd.Connection = con
                
                Dim ImageName As New SqlParameter("@ImageName", SqlDbType.VarChar, 50)
                ImageName.Value = strImageName.ToString()
                cmd.Parameters.Add(ImageName)
                
                Dim UploadedImage As New SqlParameter("@Image", SqlDbType.Image, image.Length)
                UploadedImage.Value = image
                cmd.Parameters.Add(UploadedImage)
                con.Open()
                Dim result As Integer = cmd.ExecuteNonQuery()
                con.Close()
                If result > 0 Then
                    lblMessage.Text = "File Uploaded"
                End If
                GridView1.DataBind()
            End If
        End If
    End Sub
End Class
Hope this helps

Download sample code attached



15

SqlServer Shared Memory Provider Error233 No Process Is On Other End Of Pipe

Sql Server Shared Memory Provider Error 233 No Process Is On The Other End Of The Pipe, Cannot connect to SQLEXPRESS.
A connection was successfully established with the server, but then an error occurred during the login process. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.) (Microsoft SQL Server, Error: 233)

If you are getting this error while connecting to sql express server then you need to make changes mentioned below.

1. Click on Start menu > Programs > Microsoft Sql Server > Configuration Tools

2. Select Sql Server Surface Area Configuration.

3. Now click on Surface Area configuration for services and connections

4. On the left pane of pop up window click on Remote Connections and Select Local and Remote connections radio button.

5. Select Using both TCP/IP and named pipes radio button.

6. click on apply and ok.


Now when try to connect to sql server using sql username and password u'll get the error mentioned below

Cannot connect to SQLEXPRESS.

ADDITIONAL INFORMATION:

Login failed for user 'username'. The user is not associated with a trusted SQL Server connection. (Microsoft SQL Server, Error: 18452)
ation
To fix this error follow steps mentioned below

1. connect to sql server using window authentication.

2. Now right click on your server name at the top in left pane and select properties.

3. Click on security and select sql server and windows authentication mode radio button.

3. Click on OK.

4. restart sql server servive by right clicking on server name and select restart.

Now your problem should be fixed and u'll be able to connect using sql server username and password.

Have fun.

52

Send Email With Attachment In Asp.Net

This example shows how to Send Email With Attachment In Asp.Net 2.0,3.5,4.0 C# And VB.NET Using FileUpload Control. I am saving the uploaded file into memory stream rather then saving it on server.

Send Email With Attachment in Asp.Net
For this example i m using Gmail SMTP server to send mail, this code also works fine with any SMTP Server.

For sending E-mail, first of all we need to add Syatem.Net.Mail namespace in code behind of aspx page. 

In my previous article i describe how to send mail using gmail in asp.net 

Create the page as shown in the image above, put textbox for message and FileUpload Control for adding the file attachment.

Write following code in click event of Send button in Code behind of page

C#
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSend_Click(object sender, EventArgs e)
    {
        MailMessage mail = new MailMessage();
        mail.To.Add(txtTo.Text);
        //mail.To.Add("amit_jain_online@yahoo.com");
        mail.From = new MailAddress(txtFrom.Text);
        mail.Subject = txtSubject.Text;
        mail.Body = txtMessage.Text;
        mail.IsBodyHtml = true;

        //Attach file using FileUpload Control and put the file in memory stream
        if (FileUpload1.HasFile)
        {
            mail.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
        }
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
        smtp.Credentials = new System.Net.NetworkCredential
             ("YourGmailID@gmail.com", "YourGmailPassword");
        //Or your Smtp Email ID and Password
        smtp.EnableSsl = true;
        smtp.Send(mail);

    }
}


VB.NET
Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.Net.Mail

Public Partial Class _Default
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        
    End Sub
    Protected Sub btnSend_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim mail As New MailMessage()
        mail.[To].Add(txtTo.Text)
        'mail.To.Add("amit_jain_online@yahoo.com");
        mail.From = New MailAddress(txtFrom.Text)
        mail.Subject = txtSubject.Text
        mail.Body = txtMessage.Text
        mail.IsBodyHtml = True
        
        'Attach file using FileUpload Control and put the file in memory stream
        If FileUpload1.HasFile Then
            mail.Attachments.Add(New Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName))
        End If
        Dim smtp As New SmtpClient()
        smtp.Host = "smtp.gmail.com"
        'Or Your SMTP Server Address
        smtp.Credentials = New System.Net.NetworkCredential("YourGmailID@gmail.com", "YourGmailPassword")
        'Or your Smtp Email ID and Password
        smtp.EnableSsl = True
            
        smtp.Send(mail)
    End Sub
End Class

Build and run the application to test the code

26

ASP.NET Open PopUp Window Update Refresh Values

This example explains how to Open PopUp Window In Asp.Net And Update Refresh Parent Child Values using ClientScript And RegisterStartupScript.
I am opening popup window from aspx page and updating values in parent window from child or popup window using javascript and ClientScript.RegisterStartupScript.

Open PopUp Window In Asp.Net
I have added to labels in Default.aspx page and one button to open popup window.

I've also added a PopUp.aspx page which is having two textboxes and a button to update lable values of parent page.

The textboxes in popup window are populated with Text values of lables in parent page (Default.aspx), after making changes in textbox values i'm updating values back in parent page.

HTML source Parent page
<form id="form1" runat="server">
<div>
First Name :
<asp:Label ID="lblFirstName" runat="server" Text="amiT">
</asp:Label><br />
 <br />
Last Name:&nbsp;
<asp:Label ID="lblLastName" runat="server" Text="jaiN">
</asp:Label><br />
<br />
<asp:Button ID="btnPop" runat="server" Text="Click To Edit Values" />
</div>
</form>


Write following JavaScript in Head section of page.
   1:  <script type="text/javascript">
   2:  function openPopUp()
   3:  {
   4:   var popUrl = 'PopUp.aspx?fn=' + document.getElementById('<%= lblFirstName.ClientID %>').innerHTML + '&ln=' + document.getElementById('<%= lblLastName.ClientID %>').innerHTML;
   5:   var name = 'popUp';
   6:   var appearence ='dependent=yes,menubar=no,resizable=no,'+
   7:                   'status=no,toolbar=no,titlebar=no,' +
   8:                   'left=5,top=280,width=230px,height=140px';
   9:  var openWindow = window.open(popUrl, name, appearence);
  10:  openWindow.focus();
  11:  }
  12:  </script>


In this i m getting values of lables and passing them to popuup page as querystrings

Write this code in Page_Load event of Default.aspx (parent) page
C# CODE
protected void Page_Load(object sender, EventArgs e)
{
 string updateValuesScript = 
@"function updateValues(popupValues)
{
 document.getElementById('lblFirstName').innerHTML=popupValues[0];
 document.getElementById('lblLastName').innerHTML=popupValues[1];
}";
        
this.ClientScript.RegisterStartupScript(Page.GetType(), 
"UpdateValues", updateValuesScript.ToString(), true);
btnPop.Attributes.Add("onclick", "openPopUp('PopUp.aspx')");
}

VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    Dim updateValuesScript As String = "function updateValues(popupValues)" & vbCr & vbLf & "{" & vbCr & vbLf & " document.getElementById('lblFirstName').innerHTML=popupValues[0];" & vbCr & vbLf & " document.getElementById('lblLastName').innerHTML=popupValues[1];" & vbCr & vbLf & "}"
    
    Me.ClientScript.RegisterStartupScript(Page.[GetType](), "UpdateValues", updateValuesScript.ToString(), True)
    btnPop.Attributes.Add("onclick", "openPopUp('PopUp.aspx')")
End Sub

HTML SOURCE OF PopUp.aspx(child) page

<form id="form1" runat="server">
<div>
First Name :
<asp:TextBox ID="txtPopFName" runat="server" Width="113px">
</asp:TextBox><br />
<br />
Last Name:<asp:TextBox ID="txtPopLName" runat="server" 
                       Width="109px">
</asp:TextBox><br />
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" 
            Text="Button" /></div>
</form>


C# CODE PopUp.aspx
protected void Page_Load(object sender, EventArgs e)
{
 string updateParentScript = 
 @"function updateParentWindow()
 {                                                                               
   var fName=document.getElementById('txtPopFName').value;     
   var lName=document.getElementById('txtPopLName').value;   
   var arrayValues= new Array(fName,lName);
   window.opener.updateValues(arrayValues);       
   window.close(); 
 }";
 this.ClientScript.RegisterStartupScript(this.GetType(), 
     "UpdateParentWindow", updateParentScript, true);
 if (!IsPostBack)
 {
   txtPopFName.Text = Request["fn"];
   txtPopLName.Text = Request["ln"];
 }
   Button1.Attributes.Add("onclick", "updateParentWindow()");
}

VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    Dim updateParentScript As String = "function updateParentWindow()" & vbCr & vbLf & " {                                                                               " & vbCr & vbLf & "   var fName=document.getElementById('txtPopFName').value;     " & vbCr & vbLf & "   var lName=document.getElementById('txtPopLName').value;   " & vbCr & vbLf & "   var arrayValues= new Array(fName,lName);" & vbCr & vbLf & "   window.opener.updateValues(arrayValues);       " & vbCr & vbLf & "   window.close(); " & vbCr & vbLf & " }"
    Me.ClientScript.RegisterStartupScript(Me.[GetType](), "UpdateParentWindow", updateParentScript, True)
    If Not IsPostBack Then
        txtPopFName.Text = Request("fn")
        txtPopLName.Text = Request("ln")
    End If
    Button1.Attributes.Add("onclick", "updateParentWindow()")
End Sub

Hope this helps

Download sample code attached



26

AutoCompleteExtender TextBox CompletionList Width Ajax ASP.NET

Set AutoCompleteExtender TextBox CompletionList Width And Style With CSS Ajax ASP.NET. In this example i am setting Width of Completion List in Ajax AutoComplete Extender TextBox.

The default behavior of completion list takes width equal to the width of textbox. we can change this behavior by applying some CSS style to set the width we want. default width is as shown below in the Image.

 AutoCompleteExtender TextBox CompletionList Width And Style With CSS
I have also explained how to implement AutoComplete Extender TextBox In EditItemTemplate Of GridView

I have also created example to Add Progress Image in Ajax AutoComplete TextBox




In AutoComplete Extender default width of completion list is equals to the width of textbox, to fix this issue write the CSS script mentioned below in Head section of html source of page
<head runat="server">
    <title>Progress Image in AutoComplete TextBox</title>
<style>
        .AutoExtender
        {
            font-family: Verdana, Helvetica, sans-serif;
            font-size: .8em;
            font-weight: normal;
            border: solid 1px #006699;
            line-height: 20px;
            padding: 10px;
            background-color: White;
            margin-left:10px;
        }
        .AutoExtenderList
        {
            border-bottom: dotted 1px #006699;
            cursor: pointer;
            color: Maroon;
        }
        .AutoExtenderHighlight
        {
            color: White;
            background-color: #006699;
            cursor: pointer;
        }
        #divwidth
        {
          width: 150px !important;    
        }
        #divwidth div
       {
        width: 150px !important;   
       }
 </style>
</head>
The code in bold is setting the width of completion list, you can change the dimensions according to your needs.

Now Put a div with id "divwidth" above the html source of autocomplete extender
<div ID="divwidth"></div>

and add this line in autocomplete extender HTML source

CompletionListElementID="divwidth"

The complete html source of AutoComplete Extender will look like
<asp:TextBox ID="txtAutoComplete" runat="server" Width="252px">
</asp:TextBox>   
<div ID="divwidth"></div>
<ajaxToolkit:AutoCompleteExtender runat="server" 
             ID="AutoComplete1"
             BehaviorID="autoComplete"
             TargetControlID="txtAutoComplete"
             ServicePath="AutoComplete.asmx" 
             ServiceMethod="GetCompletionList"
             MinimumPrefixLength="1" 
             CompletionInterval="10"
             EnableCaching="true"
             CompletionSetCount="12"
             CompletionListCssClass="AutoExtender"
             CompletionListItemCssClass="AutoExtenderList"
             CompletionListHighlightedItemCssClass
             ="AutoExtenderHighlight"
             CompletionListElementID="divwidth">
<ajaxToolkit:AutoCompleteExtender>

And this is how the AutoComplete TextBox will look like
AutoComplete List Width CSS style


Hope this helps


24

Detect Page Refresh In ASP.NET

This post explains how to Detect Page Refresh In ASP.NET 2.0,3.5,4.0 Using C# And VB.NET. If you have created a aspx page and have put a button on it, And in Click event of this button if you are inserting some data in database, after click if user refresh the page than click event gets fired again resulting data insertion to database again.

To stop events on the page getting fired on browser refresh we need to write bit of code to avoid it

In this example i've put a Label and a Button on the page, on click the label Text becomes Hello and when i refresh the page label's text again becomes Hello.

HTML SOURCE OF PAGE


<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server"
Text="Label"></asp:Label><br />
<br />
<asp:Button ID="Button1" runat="server"
OnClick="Button1_Click"
Text="Button" /></div>
</form>
</body>
</html>

In Page_Load event i m creating a Session Variable and assigning System date and time to it , and in Page_Prerender event i am creating a Viewstate variable and assigning Session variable's value to it
Than in button's click event i am checking the values of Session variable and Viewstate variable if they both are equal than page is not refreshed otherwise it has been refreshed
C# Code Bihind
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["CheckRefresh"] =
Server.UrlDecode(System.DateTime.Now.ToString());
}

}
protected void Button1_Click(object sender, EventArgs e)
{
if (Session["CheckRefresh"].ToString() ==
ViewState["CheckRefresh"].ToString())
{
Label1.Text = "Hello";
Session["CheckRefresh"] =
Server.UrlDecode(System.DateTime.Now.ToString());
}
else
{
Label1.Text = "Page Refreshed";
}
}

protected void Page_PreRender(object sender, EventArgs e)
{
ViewState["CheckRefresh"] = Session["CheckRefresh"];
}
}


Download the Sample Code



Find More Articles