Tuesday, December 18, 2012

Add/Remove Startup Folder Shortcut to Your App


Introduction

This article shows how to create a shortcut file (.lnk) to your application in the Windows Startup folder (or any other folder). This is useful if you want your application to be started when a user logs in to Windows. The sample code also shows how to read the target file of a shortcut in order to determine if it points to your application. This is useful when you want to delete existing shortcuts to your application.
Using the code in this article, you will be able to add a checkbox with the label 'Start this application when Windows is started' to your application.
Starting your application on login by means of a Startup folder shortcut is more user friendly than starting the application as a service. It makes it visible to the user that the application is started on login, as opposed to the many update managers (from Adobe, Google, Apple) that are started in the background and can only be disabled by special tools like msconfig.

Background

There is no direct API in the .NET Framework for creating and editing shortcut files in Windows. You will have to use COM APIs exposed by the Windows Shell and Windows Script Host. Also, the shortcut file format is not documented by Microsoft.
The article shows how to create and read shortcut files from a C# application using COM interop.

Using the code

The sample code is a simple Windows Forms application with two buttons: Create Shortcut and Delete Shortcuts that allows you to test the functionality. The sample application is a Visual Studio 2010 solution.
Screenshot
The first thing you need to do is to add two references to your project. Select Add Reference, select the COM tab, and select these two components:
  • Microsoft Shell Controls and Automation
  • Windows Script Host Object Model
Click OK, and you will have two new references highlighted below:
References
For each of these new references, open their Properties window in Visual Studio and change the property Embed Interop Types from True to False.
Properties
If you don't do this, you will get the compiler error: Interop type 'IWshRuntimeLibrary.WshShellClass' cannot be embedded. Use the applicable interface instead., when using the .NET 4.0 framework.
In the C# source code, we add these two usings:
using IWshRuntimeLibrary;
using Shell32;
The code that creates a shortcut file in the Startup Folder is shown below:
public void CreateStartupFolderShortcut()
{
  WshShellClass wshShell = new WshShellClass();
  IWshRuntimeLibrary.IWshShortcut shortcut;
  string startUpFolderPath = 
    Environment.GetFolderPath(Environment.SpecialFolder.Startup);

  // Create the shortcut
  shortcut = 
    (IWshRuntimeLibrary.IWshShortcut)wshShell.CreateShortcut(
      startUpFolderPath + "\\" + 
      Application.ProductName + ".lnk");

  shortcut.TargetPath = Application.ExecutablePath;
  shortcut.WorkingDirectory = Application.StartupPath;
  shortcut.Description = "Launch My Application";
  // shortcut.IconLocation = Application.StartupPath + @"\App.ico";
  shortcut.Save();
}
We are using the WshShellClass class to create a shortcut. The shortcut TargetPath is taken from the globalApplication object.
In order to determine if an existing shortcut file is pointing to our application, we need to be able to read theTargetPath from a shortcut file. This is done using the code below:
public string GetShortcutTargetFile(string shortcutFilename)
{
  string pathOnly = Path.GetDirectoryName(shortcutFilename);
  string filenameOnly = Path.GetFileName(shortcutFilename);

  Shell32.Shell shell = new Shell32.ShellClass();
  Shell32.Folder folder = shell.NameSpace(pathOnly);
  Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);
  if (folderItem != null)
  {
    Shell32.ShellLinkObject link = 
      (Shell32.ShellLinkObject)folderItem.GetLink;
    return link.Path;
  }

  return String.Empty; // Not found
}
The code that searches for, and deletes, existing shortcuts to our application is shown below:
public void DeleteStartupFolderShortcuts(string targetExeName)
{
  string startUpFolderPath = 
    Environment.GetFolderPath(Environment.SpecialFolder.Startup);

  DirectoryInfo di = new DirectoryInfo(startUpFolderPath);
  FileInfo[] files = di.GetFiles("*.lnk");

  foreach (FileInfo fi in files)
  {
    string shortcutTargetFile = GetShortcutTargetFile(fi.FullName);

    if (shortcutTargetFile.EndsWith(targetExeName, 
          StringComparison.InvariantCultureIgnoreCase))
    {
      System.IO.File.Delete(fi.FullName);
    }
  }
}
Using these methods in your application, you can now implement the code behind a checkbox with the label: Start application when Windows is started.

source : http://www.codeproject.com/Articles/146757/Add-Remove-Startup-Folder-Shortcut-to-Your-App

ClickOnce and Expiring Code Signing Certificates


There’s a really nasty bug in .NET 2.0′s ClickOnce deployment technology. If you deploy a smart client as availaible “off line” (launchable from the start menu) and you sign your manifest with a certificate from an official certificate authority (such as Thawte or VeriSign), you cannot renew your certificate and deploy to the same location! If you do, the next time someone starts your client it will barf up an error and won’t start. Examining the log will reveal the problem in the somewhat cryptic message “The deployment identity does not match the subscription”.
The problem is that the certificate authorities issue “renewed” certificates with a different private key. This makes up part of the ClickOnce app’s “identity” and ClickOnce validates this when starting an app to prevent tampering.
The only workaround is to uninstall and reinstall the app via the add/remove programs control panel applet. This really puts a kink in the whole “click once” thing, doesn’t it? I ran into this issue recently at work, as our code signing certificate was set to expire. Since I’m experienced enough to never trust Microsoft to do the right thing, I tested the “renewed” certificate in a test environment. Several Google searches later, I see that I’m not alone in discovering this problem.
To avoid having over 200 users fart around in the “add/remove programs” control panel applet, I came up with a kludge to have the client application uninstall itself and launch the ClickOnce installer, signed with the new certificate, from a new location. So after deploying the client signed with the new certificate, I deploy an update with the old certificate that contains the “reinstall” logic. Part of this trickery involves obtaining the “Public Key Token” for your app (I believe this comes from the certificate used to sign the ClickOnce manifest). The following snippet illustrates how to determine the public key token programmatically:
/// <summary>
/// Gets the public key token for the current ClickOnce app.
/// </summary>
private static string GetPublicKeyToken()
{
    ApplicationSecurityInfo asi =
        new ApplicationSecurityInfo(
                    AppDomain.CurrentDomain.ActivationContext);
    byte[] pk = asi.ApplicationId.PublicKeyToken;
    StringBuilder pkt = new StringBuilder();
    for (int i = 0; i < pk.GetLength(0); i++)
        pkt.Append(String.Format("{0:x}", pk[i]));
    return pkt.ToString();
}
Next, we need to find the uninstall string in the registry, based on the PublicKeyToken:
/// <summary>
/// Gets the uninstall string for the current ClickOnce app from the
/// Windows Registry.
/// </summary>
/// <param name="PublicKeyToken">The public key token of the app.
/// </param>
/// <returns>The command line to execute that will uninstall the app.
/// </returns>
private static string GetUninstallString(string PublicKeyToken, 
  out string DisplayName)
{
    string uninstallString = null;
    string searchString = "PublicKeyToken=" + PublicKeyToken;
    RegistryKey uninstallKey = Registry.CurrentUser.OpenSubKey(
        "SoftwareMicrosoftWindowsCurrentVersionUninstall");
    string[] appKeyNames = uninstallKey.GetSubKeyNames();
    DisplayName = null;
    foreach(string appKeyName in appKeyNames)
    {
        RegistryKey appKey = uninstallKey.OpenSubKey(appKeyName);
        uninstallString = (string)appKey.GetValue("UninstallString");
        DisplayName = (string)appKey.GetValue("DisplayName");
        appKey.Close();
        if(uninstallString.Contains(searchString))
            break;
    }
    uninstallKey.Close();
    return uninstallString;
}
I then launch the uninstaller, using the Process class, and use some Interop calls to the Win32 API to find the uninstaller window and automatically “push” the “OK” button (would have been nice if the was a /silent switch so I wouldn’t have to do this). Finally, I launch ClickOnce for the new version of the client, signed with the new certificate, to update the user’s workstation. A zip file with this source code can be found here:ClickOnceReinstall.zip Using these utility classes, I just insert the following code into the client’s startup routine to make it reinstall itself:
// Self-uninstall
Utils.DeploymentUtils.UninstallMe();
Utils.DeploymentUtils.AutoInstall(
  "http://host-name/deployment-folder/MyApp.application");
Application.Exit();
return;
source : http://www.jamesharte.com/blog/?p=11

Tuesday, December 11, 2012

function GetAgeDetailFull in sqlserver

สร้าง custom function ชื่อ  GetAgeDetailFull


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

Create FUNCTION [dbo].[GetAgeDetailFull]  
(  
 @BirthDay DATETIME,  
 @ApplyDay DATETIME  
)  
RETURNS VARCHAR(100)  
AS  
BEGIN
DECLARE @Return VARCHAR(100)

IF (@BirthDay IS NULL OR @BirthDay >= @ApplyDay)
BEGIN
SET @Return = '0Y 0M 0D'
END
ELSE
BEGIN
DECLARE @IntervalMonth INT  
DECLARE @IntervalDay INT  
DECLARE @ISTodayAfter INT  
 
SET @IntervalDay = DATEDIFF(DAY, @BirthDay, @ApplyDay)  
SET @IntervalMonth = DATEDIFF(MONTH, @BirthDay, @ApplyDay)  
SET @ISTodayAfter = CASE   
  WHEN  
DATEDIFF(DAY,  
DATEADD(YEAR, DATEDIFF(YEAR, @BirthDay, @ApplyDay), @BirthDay),  
@ApplyDay) < 0
  THEN -1  
  ELSE 0  
 END  
 
SET @Return = CASE   
WHEN @IntervalDay < 0 THEN ''
WHEN (DATEDIFF(YEAR, @BirthDay, @ApplyDay)+@ISTodayAfter) > -1 THEN       
CONVERT(VARCHAR(10), DATEDIFF(YEAR, @BirthDay, @ApplyDay)+@ISTodayAfter)+'Y '+
CONVERT(VARCHAR(10), DATEPART(MONTH, DATEDIFF(DAY, @BirthDay, @ApplyDay))-1)+'M '+
CONVERT(VARCHAR(10), DATEPART(DAY, DATEDIFF(DAY, @BirthDay, @ApplyDay))-1)  + 'D'
END 
END
RETURN @Return
END


วิธีเรียก Select GetAgeDetailFull({FieldName},{FieldName}) as Age 

Function GetAgeDetailFull in Crystal Report


สร้าง custom function ชื่อ  GetAgeDetailFull

Function (dateTimeVar p_BirthDay , dateTimeVar p_ApplyDay)
numberVar IntervalMonth ;
numberVar IntervalDay  ;
numberVar ISTodayAfter  ;
dateTimeVar BirthDay := p_BirthDay;
dateTimeVar ApplyDay := p_ApplyDay;
stringvar ReturnAge ;

IntervalDay := DATEDIFF('d', BirthDay, ApplyDay); 
IntervalMonth := DATEDIFF("m", BirthDay, ApplyDay);

if(DATEDIFF('d', DATEADD('y', DATEDIFF('y', BirthDay, ApplyDay), BirthDay), ApplyDay) > 0) then
      ISTodayAfter := -1 
else
      ISTodayAfter := 0 ;

if( IntervalDay < 0 ) THEN 
  ReturnAge := '' 
else if((DATEDIFF('y', BirthDay, ApplyDay)+ISTodayAfter) > -1 ) THEN       
  ReturnAge := totext(DATEDIFF('yyyy', BirthDay, ApplyDay)+ISTodayAfter,"##0")+'Y '+
               totext(datepart('m',datetime(tonumber(DATEDIFF('d',BirthDay , ApplyDay ))))-1,"#0")+'M '+
               totext(datepart('d',datetime(tonumber(DATEDIFF('d',BirthDay , ApplyDay ))))-1,"#0")+'D ';
  ReturnAge;


วิธีเรียก function GetAgeDetailFull({FieldName},CurrentDate);


Sunday, December 9, 2012

Checking All Checkboxes in a GridView and Change color Using jQuery



<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        function CheckUnCheckAll(chk) {
            $('#<%=gvHistoryDrug.ClientID %>').find("input:checkbox[Id*=chkHeader]").each(function () {
                if ($(this).is(':checked')) {

                    $('#<%=gvHistoryDrug.ClientID %>').find("input:checkbox[Id*=chkChild]").attr('checked', true);
                    $('#<%=gvHistoryDrug.ClientID %>').find("input:checkbox[Id*=chkChild]").parent().parent().addClass('highlightRow');
                }
                else {
                    $('#<%=gvHistoryDrug.ClientID %>').find("input:checkbox[Id*=chkChild]").attr('checked', false);
                    $('#<%=gvHistoryDrug.ClientID %>').find("input:checkbox[Id*=chkChild]").parent().parent().removeClass('highlightRow');
                }
            });
        }

        function CheckRow(chk) {
            
            $("#<%=gvHistoryDrug.ClientID%> input[id*='chkChild']:checkbox").click(function () {
                if ($(this).is(':checked')) {
                    $(this).parent().parent().addClass('highlightRow');
                }
                else {
                    $(this).parent().parent().removeClass('highlightRow');
                }
            });
        };
  //or
        $(document).ready(function () {

            $("#<%=gvHistoryDrug.ClientID %> input[id*='chkHeader']:checkbox").live('click', function () {
                if ($(this).is(':checked')) {

                    $('#<%=gvHistoryDrug.ClientID %>').find("input:checkbox[Id*=chkChild]").attr('checked', true);
                    $('#<%=gvHistoryDrug.ClientID %>').find("input:checkbox[Id*=chkChild]").parent().parent().addClass('highlightRow');
                }
                else {
                    $('#<%=gvHistoryDrug.ClientID %>').find("input:checkbox[Id*=chkChild]").attr('checked', false);
                    $('#<%=gvHistoryDrug.ClientID %>').find("input:checkbox[Id*=chkChild]").parent().parent().removeClass('highlightRow');
                }
            });

            $("#<%=gvHistoryDrug.ClientID %> input[id*='chkChild']:checkbox").live('click', function () {
                if ($(this).is(':checked')) {
                    $(this).parent().parent().addClass('highlightRow');
                }
                else {
                    $(this).parent().parent().removeClass('highlightRow');
                }
            });
        });
       
     
    </script>

    <style type="text/css">
        .highlightRow
        {
             background-color:Green;
             Color:White;
        }
   </style>
.
.
.
.



<asp:GridView ID="gvHistoryDrug" runat="server" AutoGenerateColumns="False" AllowSorting="True"
                        DataKeyNames="Id" CssClass="tablestyle" AllowPaging="True" OnRowDataBound="gvHistoryDrug_RowDataBound">
                        <AlternatingRowStyle CssClass="altrowstyle" />
                        <HeaderStyle CssClass="headerstyle" />
                        <RowStyle CssClass="normalrowstyle" Wrap="false" />
                        <EmptyDataRowStyle BackColor="#edf5ff" Height="25px" VerticalAlign="Middle" HorizontalAlign="Center" />
                        <EmptyDataTemplate>
                            No Records Found
                        </EmptyDataTemplate>
                        <Columns>
                            <asp:TemplateField HeaderStyle-Width="10%">
                                <HeaderTemplate>
                                    <asp:CheckBox ID="chkHeader" runat="server" onclick="javascript:CheckUnCheckAll(this);" />
                                </HeaderTemplate>
                                <ItemTemplate>
                                    <asp:CheckBox ID="chkChild" runat="server"  onclick="javascript:CheckRow(this)" />
                                </ItemTemplate>
                            </asp:TemplateField>
                            <%--<asp:BoundField SortExpression="Id" DataField="Id" HeaderText="Id" HeaderStyle-Width="10%" />--%>
                            <asp:BoundField SortExpression="MedicineName" DataField="MedicineName" HeaderText="Medicine"
                                HeaderStyle-Width="90%" />
                        </Columns>
                     
                    </asp:GridView>







Windows XP Control Panel shortcuts

The Control Panel centralises access to Windows’ multitudinous settings. From the Control Panel you can adjust and tweak Windows’ appearance, performance, network connections, hardware settings and a whole lot more.
While many of the settings in the Control Panel are also accessible in other ways – for instance, you can change the desktop appearance by right-clicking the desktop and choosing Properties from the pop-up menu or by opening the Display applet in the Control Panel – the Control Panel makes it easy to keep tabs on all your Windows settings.

Control Panel categories

In Windows XP, the Control Panel has two modes. The default mode, in the Home Edition, is the colourful and friendly Category View, which divvies up the Control Panel applets into nine categories: Appearance and Themes; Network and Internet Connections; Add or Remove Programs; Sounds, Speech, And Audio Devices; Performance and Maintenance; Printers and Other Hardware; User Accounts; Date, Time, Language and Regional Options; and Accessibility Options.
There’s actually a tenth category – easy to miss as it is only available via the task pane – called Other Control Panel Options. This is where Windows puts Control Panel applets installed by third-party applications, such as a QuickTime control or a special display control for your video card.
The other way to view the Control Panel is by the Classic View, familiar to anyone who has used the Control Panel in previous versions of Windows. In Classic View, all the applets are dumped into the one folder. It may be a little intimidating to start with, but it makes it much easier to track down all the Control Panel items and reduces the number of clicks required to access them.
You open the Control Panel by clicking Start -> Control Panel. If it’s not on your Start Menu, it’s easy to add:
  1. Right-click the Start button and choose Properties from the pop-up menu.
  2. On the Start Menu tab, make sure the first (non-classic) Start Menu option is selected and click Customize.
  3. Click the Advanced tab.
  4. In the Start Menu Items list under the Control Panel section, select either Display As Link or Display As Menu. The former (the default) simply displays a Control Panel option on the Start Menu; the latter displays the Control Panel option with a cascading menu providing direct access to each Control Panel applet. I prefer the former because I like to create shortcuts to only those applets I use often – I’ll show you how soon; I can do without the others cluttering up my Start Menu.
  5. Click OK twice to exit the dialogs.
Note, if you use the Display As Menu option for the Control Panel, you can still open the standard Control Panel window by clicking Start and then right-clicking the Control Panel option in the Start Menu and selecting Open from the pop-up menu.

Quick access

Some Control Panel applets are pretty esoteric and you’re unlikely to call on them often, if at all. For example, the Java Plug-in control, which makes an appearance in the Control Panel if you install any version of the Java Runtime Engine, is something most of us never need to touch.
Other applets, though, are so useful you’ll want to make them as easy to get at as possible. In last month’s column, I showed you how to create shortcuts to Control Panel applets such as Add Or Remove Programs by dragging them onto your Quick Launch bar. That gives you single-click access to your favourite applets.
If you have half a dozen Control Panel favourites, instead of cluttering up your Quick Launch bar you can always create a custom Control Panel folder which you can access either by the Start Menu or via the Quick Launch bar. This works much like the Display As Menu option described above, but in this case you get to pick and choose which applets appear in the menu (see the section Roll your own Control Panel below).
Display the Control Panel in My Computer
Want to see the Control Panel in My Computer? You can add it via the Folder Options dialog: open any folder, choose Folder Options from the Tools Menu, click the View tab and select the option.

Tab hopping

Another way to burrow down quickly to out-of-the-way Control Panel settings is to make a direct call to the specific Control Panel applet. Using this technique you can even open a Control Panel applet to a specific tab.
For instance, if you frequently tinker with the sounds events on your system, normally you get to these settings by clicking Start -> Control Panel -> Sounds, Speech and Audio Devices -> Change the Sound Scheme. Using a direct call, you can get there much faster.
First, a bit of background. Control Panel applets are stored in files with a .cpl extension. If you take a look in your Windows\System32 folder you’ll find them there. (It makes it easier to see them all if you right-click in a blank spot and choose Arrange Icons By -> Type, select the Details View, and then scroll down the list and look for Control Panel Extensions.) You can run any applet by double-clicking its cpl file.
A faster way to run any applet is to issue a direct command:
control applet.cpl
where applet is any Control Panel applet on your system. Table 1 shows a list of the most common ones. Simply typing control by itself opens the Control Panel.
Table 1. Common Control Panel applets
Accessibility Optionsaccess.cpl
Add New Hardware Wizardhdwwiz.cpl
Add/Remove Programsappwiz.cpl
Date and Time Propertiestimedate.cpl
Display Propertiesdesk.cpl
FindFastfindfast.cpl
Folder Properties *folders
Fonts Folder *fonts
Internet Propertiesinetcpl.cpl
Joystick Propertiesjoy.cpl
Keyboard Propertiesmain.cpl keyboard
Mouse Propertiesmain.cpl
Network Propertiesncpa.cpl
Password Propertiespassword.cpl
Phone and Modem optionstelephon.cpl
Power Management powercfg.cpl
Printers Folder *printers
Regional settingsintl.cpl
Scanners and Camerassticpl.cpl
Sound Propertiesmmsys.cpl sounds
Sounds and Audio Device Propertiesmmsys.cpl
System Propertiessysdm.cpl
User settingsnusrmgr.cpl
TweakUI tweakui.cpl
Note options marked with an * have special shortcut names which may be used instead of the usual control applet.cpl,applet_number format.

So, for example, to open the Sounds and Audio Device Properties dialog you click Start -> Run, type:
control mmsys.cpl
and click OK.
How, then, do you gain access to a specific tab in that dialog box? You use an extended form of the Control command:
control applet.cpl,@applet_number,tab_number
The applet_number is rarely required. There are a couple of cpl files which give access to multiple applets and in those cases you use the applet_number to identify which one you’re calling. For example, main.cpl provides access to both the Mouse and the Keyboard properties. The numbering starts at 0, so control main.cpl,@0 opens the Mouse Properties, control main.cpl,@1 opens the Keyboard Properties. If you don’t include an applet_number, @0 is assumed.
The tab_number is the number of the tab you want selected in the dialog box, with numbering starting from 0 from the left.
If you want to use a tab_number but want to omit the applet_number (or leave its value at 0), insert an extra comma before the tab_number to indicate the missing value. Thus:
control main.cpl,,3
opens the Mouse Properties dialog to its fourth tab.
So to open the Sounds and Audio Device Properties dialog with the Sounds tab already selected, click Start -> Run and enter the command:
control mmsys.cpl,,1

Tab shortcuts

Instead of typing these commands each time, create a desktop shortcut for your favourites and then stick them in the Quick Launch bar or wherever else you choose:
  1. Right-click the desktop and choose New -> Shortcut.
  2. Type the appropriate command in the Create Shortcut dialog and click Next. For example:
    control appwiz.cpl,,2 (this will open the Add Or Remove Programs dialog with the Add/Remove Windows Components section selected).
  3. Give your shortcut a descriptive name, such as Remove Windows Components, and click Finish.

Step-by-step: Roll your own Control Panel

1. It’s easy to create a Control Panel which contains only your most frequently used applets.
Start by right-clicking the Start button and choosing Open. This opens the \Documents and Settings\username\Start Menu folder (where username is your Windows logon name).Create your own Control Panel
2. Create a new folder within this folder and call it whatever you like – My Controls, for example. Then click Start -> Control Panel to open the original Control Panel and click Switch To Classic View if you’re not already in that mode. Position the two folders side by side.Create a My Controls folder
3. Right-click-and-drag your favourite applets from the Control Panel folder into your My Controls folder and choose Create Shortcut(s) Here when prompted, then close both folders.Create a folder shortcut
4. You can access the applets in this folder by clicking Start -> All Programs -> My Controls. You can also stick the folder on your Quick Launch bar:
  1. Click Start -> All Programs.
  2. Hold down the Ctrl key and drag the My Controls item onto the Quick Launch bar.
In this way, you can gain quick access to all your favourite applets while adding only a single icon to the Quick Launch bar.Add the shortcut to Quick Launch

Sunday, December 2, 2012

Autocomplete extender with gridview

asp.net page design


<asp:GridView ID="gvPatient" runat="server" AutoGenerateColumns="False" AllowSorting="True"
                    DataKeyNames="AN" CssClass="tablestyle" AllowPaging="True" OnSorting="gvPatient_Sorting"
                    OnDataBound="gvPatient_DataBound" OnRowDataBound="gvPatient_RowDataBound"
                    OnRowCreated="gvPatient_RowCreated" PageSize="25" Style="table-layout: fixed;"
                    Width="100%">
                    <AlternatingRowStyle CssClass="altrowstyle" />
                    <HeaderStyle CssClass="headerstyle" />
                    <RowStyle CssClass="rowstyle" Wrap="true" />
                    <EmptyDataRowStyle BackColor="#edf5ff" Height="300px" VerticalAlign="Middle" HorizontalAlign="Center" />
                    <EmptyDataTemplate>
                        No Records Found
                    </EmptyDataTemplate>
                    <Columns>
                        <asp:TemplateField HeaderText="Diagnosis">
                            <ItemTemplate>
                                <asp:TextBox ID="txtDiagnosis" runat="server" Width="87%" MaxLength="200" Text='<%#Eval("Diagnosis") %>' Height="30px" TextMode="MultiLine" Style="resize: none;"></asp:TextBox>
                                  <asp:ImageButton ID="ibtnSave" runat="server" ImageUrl="~/images/SaveSmall.png" ToolTip="Save Diag"  onclick="ibtnSave_Click" ImageAlign="NotSet" />
                                   <asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" MinimumPrefixLength="1"
                                     ServiceMethod="GetVendorList" TargetControlID="txtDiagnosis" UseContextKey="True"
                                     CompletionListCssClass="autocomplete_completionListElement" CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
                                     CompletionListItemCssClass="autocomplete_listItem" DelimiterCharacters=";, :"
                                     ShowOnlyCurrentWordInCompletionListItem="True"  CompletionInterval="1000"
                                     CompletionSetCount="10" />
                            </ItemTemplate>
                            <ItemStyle  VerticalAlign="Middle"  />
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>

code behide : 

 using AjaxControlToolkit;


 protected void gvPatient_RowDataBound(object sender, GridViewRowEventArgs e)
    {
   
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //config AutoCompleteExtender in gridview
            //find textbox
            TextBox txtDiagnosis = (TextBox)e.Row.FindControl("txtDiagnosis");
            //find autocomplete extender
            AutoCompleteExtender AutoComplete1 = (AutoCompleteExtender)e.Row.FindControl("AutoCompleteExtender1");
            //set target control id of autocomplete extender
            AutoComplete1.TargetControlID = txtDiagnosis.ID;

        }
    }




  [System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
    public static string[] GetVendorList(string prefixText, int count, string contextKey)
    {
        SqlConnection con = new SqlConnection(dbClass.NAVTestDBConn);
        con.Open();
        string sql = string.Format("SELECT top {0} '['+V.NO_+'] ('+V.[Search Name]+') '+V.Name " +
                       "FROM [Phuket International Hospital$Vendor] AS V  " +
                       "WHERE V.Name like @prefixText  or  [Search Name] like @prefixText or V.NO_ like @prefixText " +
                       "ORDER BY V.Name ASC ", count);
        SqlDataAdapter da = new SqlDataAdapter(sql, con);
        da.SelectCommand.Parameters.Add("@prefixText", SqlDbType.VarChar, 50).Value = "%" + prefixText + "%";
        DataTable dt = new DataTable();
        da.Fill(dt);
        string[] items = new string[dt.Rows.Count];
        int i = 0;
        foreach (DataRow dr in dt.Rows)
        {
            items.SetValue(dr[0].ToString(), i);
            i++;
        }
        return items;
     
    }