Content feed Comments Feed

The Official ASATO Site

Hi, welcome to my blog. ASP,asp.net,Health,Javascript,JQUERY

How to Bind an ArrayList to Dropdownlist (asp.net)

Posted by admin On August - 5 - 2010

The ArrayList object is a collection of items containing a single data value.
Items are added to the ArrayList with the Add() method.
Create an ArrayList

?View Code CSHARP
1
2
3
4
5
ArrayList list = new ArrayList();
  list.Add("none");
  list.Add("Canada Post");
  list.Add("UPS");
  list.Insert(1,"FedEx");

An ArrayList can also be sorted alphabetically or numerically with the Sort() method:

?View Code CSHARP
1
  list.Sort()

Data Binding to an ArrayList:
ArrayList object may automatically generate the text and values to the following controls:
1 asp:RadioButtonList
2 asp:CheckBoxList
3 asp:DropDownList
4 asp:Listbox

The following code Bind an ArrayList to Dropdownlist:

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
CS file:
<script runat="server">
    void Page_Load()
    {
         ArrayList list = new ArrayList();
         list.Add("microsoft");
         list.Add("Canada Post");
         list.Add("google");
         list.Insert(1,"FedEx");
         MyDDL.DataSource = list;
         MyDDL.DataBind();
    }
 
</script>

HTML file:

?View Code CSHARP
1
2
3
  <form id="Form1" method="post" runat="server">
      <asp:dropdownlist id="MyDDL" runat="server"></asp:dropdownlist>
  </form>

The DataSource property of the dropdownlist control is set to the ArrayList and it defines the data source of the dropdownlist control. The DataBind() method of the dropdownlist control binds the data source with the dropdownlist control.

WebService Class Introduce

Posted by admin On April - 28 - 2010

Defines the optional base class for XML Web services, which provides direct access to common ASP.NET objects, such as application and session state.
Namespace:  System.Web.Services
Assembly:  System.Web.Services (in System.Web.Services.dll)

Examples
The example below creates an XML Web service, deriving from WebService, in order to use the Context property to obtain the time of the request on the server.
<%@ WebService Language=”C#” Class=”Util” %>
using System;
using System.Web.Services;

public class Util: WebService {
   [ WebMethod(Description="Returns the time as stored on the Server",
   EnableSession=false)]
   public string Time() {
      return Context.Timestamp.TimeOfDay.ToString();
   }
}

How to upload File use a C# Web Service?

Posted by admin On April - 28 - 2010
Download Files:
UploadAnyfilePack.zip

 

Introduction

This article shall describe an approach that may be used to upload any sort of a file through a web service from a Windows Forms application. The approach demonstrated does not rely on the ASP.NET file uploader control and allows the developer the opportunity to upload files programmatically and without user intervention. Such an approach may be useful for doing something like processing out the contents of a local message queue when internet service is available (if the user base were mobile and had only intermittent connectivity). The article also addresses the use of a file size check as a precursor to allowing a file to upload through the service.

Figure 1: Test Application Shown Uploading a File.

Figure 2: Mixed bag of different file types in transient storage folder.

Getting Started

The solution contains two projects; one is an ASP.NET Web Service project (Uploader) and the other is a Win Forms test application (TestUploader) used to demonstrate uploading files through the web method provided in the web service project.

The web service project contains only a single web service (FileUploader) which in turn contains only a single Web Method (UploadFile). The Win Forms application contains only a single form which contains the controls (one textbox and two buttons used in conjunction with an OpenFileDialog control) and code necessary to select and upload files through the web service.

Figure 3: Solution Explorer with the both Projects Visible.

Code:  Uploader Web Service Project

The Uploader web service project is an ASP.NET web service project containing a single web service called, “FileUploader“; this web service exposes a single web method called, “UploadFile“.

The code for this web service begins with the following:

using System;

using System.Data;

using System.Web;

using System.Collections;

using System.Web.Services;

using System.Web.Services.Protocols;

using System.ComponentModel;

using System.IO; 

namespace Uploader

{

    /// <summary>

    /// This web method will provide an web method to load any

    /// file onto the server; the UploadFile web method

    /// will accept the report and store it in the local file system.

    /// </summary>

    [WebService(Namespace = "http://tempuri.org/")]

    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

    [ToolboxItem(false)]

    public class FileUploader : System.Web.Services.WebService

    {

The class starts out with the default imports; I added System.IO to the defaults to support the use of file and memory streams. The web service namespace is left as the default http://tempuri.org/ which of course will have to updated if the service were deployed.

The remainder of the code supplied in this class is used to define the web method used to upload the file; the code is annotated. The essential process is that, files converted to byte arrays are passed along with the full name of the file (not the path) including the extention as arguments to the UploadFile web method. The byte array is passed to a memory stream, and a file stream is opened pointing to a newly created file (named the name of the original file) within the target folder used to store the files. Once the file stream has been created, the memory stream is written into the file stream and then the memory stream and file stream are disposed of. 

The web method is setup to return a string; if all goes well, the string returned will read, “OK”, if not, the error message encountered will be returned to the caller.

[WebMethod]

public string UploadFile(byte[] f, string fileName)

{

    // the byte array argument contains the content of the file

    // the string argument contains the name and extension

    // of the file passed in the byte array

    try

    {

        // instance a memory stream and pass the

        // byte array to its constructor

        MemoryStream ms = new MemoryStream(f);

        // instance a filestream pointing to the

        // storage folder, use the original file name

        // to name the resulting file

        FileStream fs = new FileStream(System.Web.Hosting.HostingEnvironment.MapPath

                    (“~/TransientStorage/”) +fileName, FileMode.Create); 
        // write the memory stream containing the original

        // file as a byte array to the filestream

        ms.WriteTo(fs); 
        // clean up

        ms.Close();

        fs.Close();

        fs.Dispose(); 
        // return OK if we made it this far

        return “OK”;

    }

    catch (Exception ex)

    {

        // return the error message if the operation fails

        return ex.Message.ToString();

    }

}
 

Code:  Test Uploader Win Forms Application

The test application contains a single Windows Form class; this form contains a text box used to display the name of the file selected for upload, a browse button used to launch an open file dialog box which is used to navigate to and select a file for upload, and an upload button which is used to pass the file to web service so that the selected file may be stored on the server.

The code for this class begins with the following:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.IO;
 

namespace TestUploader

{

    /// <summary>

    /// A test form used to upload a file from a windows application using

    /// the Uploader Web Service

    /// </summary>

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        } 

        private void Form1_Load(object sender, EventArgs e)

        {

            // do nothing

        }

Aside from the default imports, I have added only System.IO to the list. This being necessary to support working with files. The namespace and class declarations are in the default configuration. In addition to System.IO, the project also adds in a web reference pointing to the File Uploader web service, the reference is given the alias of Uploader.

The next bit of code in the class is private method used to prepare the file for submittal to the web service and to actually make that submittal. The code below is annotated to describe the activity but the essential parts of the operation are to check the file size to see if the web service will accept the file (by default, the web server will accept uploads smaller than 4 MB in size, the web config file must be updated in order to support larger uploads), and to convert the file to a byte array. When everything is ready, the byte array and the name of the file including the extension is passed to an instance of the web service web method. 

Note that, when setting up the demo, you will have remove and add the web reference back into the project in order for it to work for you.

/// <summary>

/// Upload any file to the web service; this function may be

/// used in any application where it is necessary to upload

/// a file through a web service

/// </summary>

/// <param>Pass the file path to upload</param>

private void UploadFile(string filename)

{

    try

    {

        // get the exact file name from the path

        String strFile = System.IO.Path.GetFileName(filename);

        // create an instance fo the web service

        TestUploader.Uploader.FileUploader srv = new

        TestUploader.Uploader.FileUploader();

        // get the file information form the selected file

        FileInfo fInfo = new FileInfo(filename);

        // get the length of the file to see if it is possible

        // to upload it (with the standard 4 MB limit)

        long numBytes = fInfo.Length;

        double dLen = Convert.ToDouble(fInfo.Length / 1000000);

        // Default limit of 4 MB on web server

        // have to change the web.config to if

        // you want to allow larger uploads

        if (dLen < 4)

        {

            // set up a file stream and binary reader for the

            // selected file

            FileStream fStream = new FileStream(filename,

            FileMode.Open, FileAccess.Read);

            BinaryReader br = new BinaryReader(fStream);

            // convert the file to a byte array

            byte[] data = br.ReadBytes((int)numBytes);

            br.Close();

            // pass the byte array (file) and file name to the web service

            string sTmp = srv.UploadFile(data, strFile);

            fStream.Close();

            fStream.Dispose();

            // this will always say OK unless an error occurs,

            // if an error occurs, the service returns the error message

            MessageBox.Show(“File Upload Status: ” + sTmp, “File Upload”);

        }

        else

        {

             // Display message if the file was too large to upload

             MessageBox.Show(“The file selected exceeds the size limit for uploads.”, “File Size”);

         }

    }

    catch (Exception ex)

    {

         // display an error message to the user

         MessageBox.Show(ex.Message.ToString(), “Upload Error”);

    }

}

Following the UploadFile method, the next bit of code is used to handle the browse button’s click event. This code is used merely to display an open file dialog to the user and to take the file selected through that dialog and display the file name in the form’s file name text box.

/// <summary>

/// Allow the user to browse for a file

/// </summary>

/// <param></param>

/// <param></param>

private void btnBrowse_Click(object sender, EventArgs e)

{

    openFileDialog1.Title = “Open File”;

    openFileDialog1.Filter = “All Files|*.*”;

    openFileDialog1.FileName = “”;

    try

    {

        openFileDialog1.InitialDirectory = “C:\\Temp”;

    }

    catch

    {

        // skip it

    }

    openFileDialog1.ShowDialog();

    if (openFileDialog1.FileName == “”)

        return;

    else

        txtFileName.Text = openFileDialog1.FileName; 

}

The class wraps up with the button click event handler for the Upload button. This handler merely checks for text in the file name text box and, if something is there, it sends the value to the Upload method.

/// <summary>

/// If the user has selected a file, send it to the upload method,

/// the upload method will convert the file to a byte array and

/// send it through the web service

/// </summary>

/// <param></param>

/// <param></param>

private void btnUpload_Click(object sender, EventArgs e)

{

    if (txtFileName.Text != string.Empty)

        UploadFile(txtFileName.Text);

    else

        MessageBox.Show(“You must select a file first.”, “No File Selected”);

}
 

That wraps up all of the client and server side code necessary to upload any sort of file to a server from a Win Forms application.

Summary

This article was intended to demonstrate an easy approach to uploading any sort of a file to a web server from a Win Forms application. This example uses the default upload size of 4096 KB, if you need to upload larger files, you will need to alter this value by changing the httpRuntime maxRequestLength property to the desired value; at the same time you may need to increase the executionTimeout property to a greater value as well in order to support longer upload times. Take care when altering the values as Microsoft has established the default 4 MB limit to provide some safety against attempts to upload extremely large files that may hamper access to the server. 

  Download Files:
UploadAnyfilePack.zip              

How to get mimetype Windows

Posted by admin On April - 28 - 2010

What are MIME types?
Similar to file extensions but more universally accepted, “MIME types” are used to identify the type of information that a file contains. While the file extension .html is informally understood to mean that the file is an HTML page, there is no requirement that it mean this, and many HTML pages have different file extensions.
Here are some examples of common mime types seen on the web:
Type Common                 File Extension              Purpose
text/html             .html                Web Page
image/png          .png                   PNG-format image
image/jpeg         .jpeg                  JPEG-format image
audio/mpeg       .mp3                 MPEG AudioFile

How to get mimetypes?
private string MimeType(string Filename)
{
     string mime = “application/octetstream”;
     string ext = System.IO.Path.GetExtension(Filename).ToLower();
     Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
     if (rk != null && rk.GetValue(“Content Type”) != null)
          mime = rk.GetValue(“Content Type”).ToString();
     return mime;
}

Note:
This function needs permission to read from registry – so it might not be suited in a web scenario.

How to Upload multiple files in asp.net

Posted by admin On March - 23 - 2010

In asp.net 2.0, if you want to upload a file, you can use FileUpload server control in your in your applications.like this:
ASPX code:

?View Code CSHARP
1
2
3
4
<div>
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click"  Text="Upload--File" />
        <asp:Label ID="Label1" runat="server"></asp:Label></div>

ASPX.CS code:

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
            try
            {
                FileUpload1.SaveAs("G:\\Uploads\\" +  FileUpload1.FileName);
                Label1.Text = "File name: " +
                     FileUpload1.PostedFile.FileName + "<br>" +
                     FileUpload1.PostedFile.ContentLength + " kb<br>" +
                     "Content type: " +
                     FileUpload1.PostedFile.ContentType;
            }
            catch (Exception ex)
            {
                Label1.Text = "ERROR: " + ex.Message.ToString();
            }
        else
        {
            Label1.Text = "You have not specified a file.";
        }
    }

But, if we want to Upload multiple files, how can we do ?
aspx:

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>Upload multiple files</title>
 
  <script type="text/javascript">
    function addFiles() {
      var div = document.createElement("div");
      var f = document.createElement("input");
      f.setAttribute("type", "file")
      f.setAttribute("name", "File")
      f.setAttribute("size", "40")
      div.appendChild(f)
      var d = document.createElement("input");
      d.setAttribute("type", "button")
      d.setAttribute("onclick", "deteFile(this)");
      d.setAttribute("value", "remove")
      div.appendChild(d)
      document.getElementById("_container").appendChild(div);
    }
 
    function deteFile(o) {
      while (o.tagName != "DIV") o = o.parentNode;
      o.parentNode.removeChild(o);
    }
  </script>
</head>
<body>
  <form id="form1" runat="server" method="post" enctype="multipart/form-data">
  <h3>Upload multiple files</h3>
   <div id="_container">
    <input type="file" size="50" name="File" />
  </div>
  <div>
    <input type="button" value="Add" onclick="addFiles()" />
  </div>
  <div style="padding:10px 0">
    <asp:Button runat="server" Text="Upload files" ID="UploadButton" onclick="UploadButton_Click"></asp:Button>
  </div>
  <div>
    <asp:Label ID="Label1" runat="server"  Width="500px" BorderStyle="None" BorderColor="White"></asp:Label>
  </div>
  </form>
</body>
</html>

aspx.cs:

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
protected void UploadButton_Click(object sender, EventArgs e)
    {
      ///foreach File form
      HttpFileCollection files = HttpContext.Current.Request.Files;
      strMsg.Append("file list is:<hr color='red'/>");
      try
      {
        for (int iFile = 0; iFile < files.Count; iFile++)
        {
          HttpPostedFile postedFile = files[iFile];
          string fileName, fileExtension;
          fileName = System.IO.Path.GetFileName(postedFile.FileName);
          if (fileName != "")
          {
            fileExtension = System.IO.Path.GetExtension(fileName);
            strMsg.Append("type:" + postedFile.ContentType.ToString() + "<br>");
            strMsg.Append("client dress:" + postedFile.FileName + "<br>");
            strMsg.Append("file name:" + fileName + "<br>");
            strMsg.Append("fileExtension :" + fileExtension + "<br><hr>");
            postedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath("photoshops/") + fileName);
          }
        }
        Label1.Text = strMsg.ToString();
      }
      catch (System.Exception Ex)
      {
        Label1.Text = Ex.Message;
      }
    }

Note: the form must set enctype=”multipart/form-data”

What is List and How to bind List to GridView?

Posted by admin On March - 12 - 2010

C# List Examples
Lists are dynamic arrays in the C# language. They can grow as needed when you add elements. They are called generic collections and constructed types.You need to use < and > in the List declaration.
Represents a strongly typed list of objects that can be accessed by index. Provides methods to search, sort, and manipulate lists.

Examples 1

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
        List<string> dinosaurs = new List<string>();
        dinosaurs.Add("one");
        dinosaurs.Add("two");
        dinosaurs.Add("three");
        dinosaurs.Add("four");
        dinosaurs.Add("five");
        foreach(string din in dinosaurs)
        {
            Console.WriteLine(dinosaur);
        }

Examples 2
This example shows how you can create a new List of unspecified size, and add object to it.

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Client
{
    public Client(string Name, int Age)
    {
        _Name = Name;
        _Age = Age;
    }
    private int _Age;
    public int Age
    {
        get { return _Age; }
        set { _Age = value; }
    }
    private string _Name;
    public string Name
    {
        get { return _Name; }
        set { _Name = value; }
    }
}
?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
List<Client> lst = new List<Client>();
lst.Add(new Client("Mike", 20));
lst.Add(new Client("Tom", 22));
foreach(Client cit in lst)
{
     Console.WriteLine(cit.Name);
     Console.WriteLine("------------");
     Console.WriteLine(cit.Age);
     Console.WriteLine(cit.Name);
}

How to bind List<> to GridView?

?View Code CSHARP
1
2
GridView1.DataSource = lst;
GridView1.DataBind();

in this article,wo will learn how to convert images to byte arrays, how to convert byte[] back into images:

first:
convert images to byte arrays

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
        /// <summary>
        /// convert image to byte[]
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public byte[] PhotoToBytes(string filePath) {
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);
            try {
                byte[] photo = br.ReadBytes((int)fs.Length);
                br.Close();
                fs.Close();
                return photo;
            }
            catch {
                return null;
            }
        }

next: convert byte[] back into images

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
        /// <summary>
        /// byte[] back into Image
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public Image BytesToPhoto(byte[] Bytes) {
 
            MemoryStream stream = null;
 
            Image img = null;
 
            try {
                stream = new MemoryStream(Bytes);
 
                img = Image.FromStream(stream, true);
 
                return img;
 
            }
            catch {
 
                return null;
 
            }
            finally {
                stream.Close();
 
                img.Dispose();
 
            }
        }

How to bind datatable to a TreeView control?

Posted by admin On May - 8 - 2009

TreeView control is a powerful server-control for rendering TreeView UI.I will bind a datatable to a treeview contriol,here is the code:
aspx:

?View Code CSHARP
1
2
<asp:TreeView ID="TV_Department" runat="server"  OnSelectedNodeChanged="TV_Department_SelectedNodeChanged"  ExpandDepth="6"   width="240px" BorderWidth="0px" BorderColor="White" BackColor="White" LineImagesFolder="~/TreeLineImages" NodeWrap="True" ImageSet="Msdn" NodeIndent="10">
</asp:TreeView>

cs:

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
protected void Page_Load(object sender, EventArgs e)
{
 
        if (!IsPostBack)
        {
            BindTree(isTheme.DeptID); 
 
        }
}
 
/// <summary>
///  
/// </summary>
void BindTree(int DeptID)
{
        DataTable dt = getlist.GetList(" * ", "").Tables[0];// we can get the datatable from MSSQL XML and so on.
        DataView dv = new DataView(dt);
        dv.RowFilter = "DeptID =" + DeptID;
        TV_Department.Nodes.Clear();
        if (dt.Rows.Count > 0)
        {
            foreach (DataRowView drv in dv)
            {
                TreeNode node = new TreeNode();
                node.Text = drv["DeptShortName"].ToString();
                node.Value = drv["DeptID"].ToString();
                node.Expanded = true;
                node.SelectAction = TreeNodeSelectAction.Select;
                TV_Department.Nodes.Add(node);
                AddReplies(dt, node);
            }
            TV_Department.SelectedNodeStyle.BackColor = System.Drawing.Color.FromArgb(242, 255, 253);
        }
 
}
/// <summary>
/// get the children 
/// <param name="dt"></param>
/// <param name="node"></param>
private void AddReplies(DataTable dt, TreeNode node)
{
        DataView dv = new DataView(dt);
        dv.RowFilter = "PID='" + node.Value + "'";
        foreach (DataRowView row in dv)
        {
            TreeNode replyNode = new TreeNode();
            replyNode.Text = row["DeptShortName"].ToString();
            replyNode.Value = row["DeptID"].ToString();
            replyNode.Expanded = true;
            replyNode.SelectAction = TreeNodeSelectAction.Select;
            node.ChildNodes.Add(replyNode);
            AddReplies(dt, replyNode);
        }
 }

How to find control inside Repeater

Posted by admin On April - 8 - 2009

Sometimes,wo need to find some control inside a repeater,and give it some values.

wo can using this code:

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
StringBuilder sb = new StringBuilder();
foreach (RepeaterItem item in Rep.Controls) {
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem) 
{
     Literal questionid = (Literal)item.FindControl("questionid");
     HtmlTextArea hta = (HtmlTextArea)item.FindControl("txtJisuan");
     sb.Append(Server.HtmlEncode(hta.Value));
     sb.Append("$$");
}
}

if you want to find some control inside  HeaderTemplate of Repeater,you kan do this:

?View Code CSHARP
1
2
3
4
5
6
7
8
foreach (RepeaterItem item in Rep.Controls) 
{
if (item.ItemType == ListItemType.Header) 
{
Label lbSelTotal = (Label)item.FindControl("lbSelTotal");
break;
}
}

you need pay attention to the red words.

Uisng Jquery select DataGrid CheckBox Multiple Rows Column

Posted by admin On March - 30 - 2009

Multiple Rows selection in a web is a requirement. and in asp.net web you can using checkbox(runnet-server) control,A checkbox column must of course be accompanied with a CheckAll / UnCheckAll functionality.

we can ussing Jquery select CheckBox Multiple Rows Column.
here is the code:

<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script><script type="text/javascript">
<!--
    $(function(){
      $("#chk").click(function(){

                if($(this).attr(“checked”)==true){
                    $(“input[name='chk_list']“).each(function(){
                        $(this).attr(“checked”,true);
                    });
                }
                else{
                   $(“input[name='chk_list']“).each(function(){
                        $(this).attr(“checked”,false);
                    });
                }
            });
        });
     });
// –></script>


<asp:TemplateColumn>
          <HeaderTemplate>
                    <input type=checkbox id="chk" />check all
                </HeaderTemplate>
       <HeaderStyle Width="10%" CssClass="zi1B" BackColor="#EFEFEF" Height="22"></HeaderStyle>
       <ItemTemplate>
        <asp:CheckBox  id="chk_list" name="chk_list" Runat="server"  value='<%# DataBinder.Eval(Container.DataItem, "SchemeID") %>'></asp:CheckBox>
       </ItemTemplate>
       <ItemStyle HorizontalAlign="Center" />
      </asp:TemplateColumn>

you must pay attention the red color words.