thought this sounded like a pretty standard requirement so I figured there would be a nice snippet on msdn or in an msdn publication describing the official Microsoft solution. I couldn’t find that, or any other approach that I was happy with. I ran across a few sites that looked promising, but didn’t quite meet my requirements – I had to either override a page level method and do nothing (here) or else turn off event validation (here and here). It also generally appeared that the people using these solutions were also running into a variety of issues with grids that allow sorting and paging - all of the grids I am working with allow both.

The approach I settled on is very similar to the above links, but without the limitations of having to turn off event validation or override any page methods. This gives me the freedom to put these methods were I want them (in my case within a static GridViewExportUtil class) without having to worry about the page that hosts the GridView doing anything special.

Download code | View live demo here | View GridViewExportUtil.cs | View GridViewExportUtil.vb

[Update: 7/7/2007]

Fred van den Berg converted the sample web site to VB.NET.  You can download it here.  You can also just view the VB version of the export utility class here.  Thanks Fred!

[Update: 6/26/2007]

Shane, you can use the GridLines proeprty of the Table to show or hide the GridLines.  I have updated the demo and sample to include copying over this property to the Table before exporting.

//  Create a table to contain the grid
Table table = new Table();
//  include the gridline settings
table.GridLines = gv.GridLines;

[Update: 6/22/2007]

I updated the demo to include an option for specifing the nuber of rows that should be exported.  The available options are 'Current Page', 'All Pages', or just the 'Top 100 Rows'. 

For the case where I actually wanted all rows exported, I turned off paging and rebound the grid before sending the control to the export utility.  For exporting just the first 100 rows, I set the PageSize property to 100 and then rebound.  You should probably use care when exporting the complete GridView just in case your grid has a few more rows that you are expecting.  Here is the code for the export button click handler

/// <summary>
/// 
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
protected void BtnExportGrid_Click(object sender, EventArgs args)
{
    if (this.rdoBtnListExportOptions.SelectedIndex == 1)
    {
        //  the user wants all rows exported, turn off paging
        //  and rebing the grid before sending it to the export
        //  utility
        this.gvCustomers.AllowPaging = false;
        this.gvCustomers.DataBind();
    }
    else if (this.rdoBtnListExportOptions.SelectedIndex == 2)
    {
        //  the user wants just the first 100,
        //  adjust the PageSize and rebind
        this.gvCustomers.PageSize = 100;
        this.gvCustomers.DataBind();
    }

    //  pass the grid that for exporting ...
    GridViewExportUtil.Export("Customers.xls", this.gvCustomers);
}

Also, I moved the GridView to a content page to test terry's comment about making sure this approach works from content pages.  I haven't run into any issues yet.

** Disclaimer **

GridViewExportUtil

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
/// <summary>
/// Summary description for Class1
/// </summary>
public class GridViewExportUtil
{
    /// <summary>
    ///
    /// </summary>
    /// <param name="fileName"></param>
    /// <param name="gv"></param>
    public static void Export(string fileName, GridView gv)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader(
            "content-disposition", string.Format("attachment; filename={0}", fileName));
        HttpContext.Current.Response.ContentType = "application/ms-excel";

        using (StringWriter sw = new StringWriter())
        {
            using (HtmlTextWriter htw = new HtmlTextWriter(sw))
            {
                //  Create a table to contain the grid
                Table table = new Table();

                //  include the gridline settings
                table.GridLines = gv.GridLines;

                //  add the header row to the table
                if (gv.HeaderRow != null)
                {
                    GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
                    table.Rows.Add(gv.HeaderRow);
                }

                //  add each of the data rows to the table
                foreach (GridViewRow row in gv.Rows)
                {
                    GridViewExportUtil.PrepareControlForExport(row);
                    table.Rows.Add(row);
                }

                //  add the footer row to the table
                if (gv.FooterRow != null)
                {
                    GridViewExportUtil.PrepareControlForExport(gv.FooterRow);
                    table.Rows.Add(gv.FooterRow);
                }

                //  render the table into the htmlwriter
                table.RenderControl(htw);

                //  render the htmlwriter into the response
                HttpContext.Current.Response.Write(sw.ToString());
                HttpContext.Current.Response.End();
            }
        }
    }

    /// <summary>
    /// Replace any of the contained controls with literals
    /// </summary>
    /// <param name="control"></param>
    private static void PrepareControlForExport(Control control)
    {
        for (int i = 0; i < control.Controls.Count; i++)
        {
            Control current = control.Controls[i];
            if (current is LinkButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
            }
            else if (current is ImageButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
            }
            else if (current is HyperLink)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
            }
            else if (current is DropDownList)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
            }
            else if (current is CheckBox)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
            }

            if (current.HasControls())
            {
                GridViewExportUtil.PrepareControlForExport(current);
            }
        }
    }
}

http://mattberseth.com/blog/2007/04/export_gridview_to_excel_1.html

WebCustomControl1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication2
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:WebCustomControl1 runat=server></{0}:WebCustomControl1>")] 
    public class WebCustomControl1 : WebControl
    {
        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public string Text
        {
            get
            {
                String s = (String)ViewState["Text"];
                return ((s == null) ? "["+this.ID+"]" : s);
            }

            set
            {            
                if (txtbl != null)
                {
                    this.Text = value;
                }
                else {
                    ViewState["Text"] = value;    
                }
            }
        }

        protected override void RenderContents(HtmlTextWriter output)
        {
            this.EnsureChildControls(); //하위 컨트롤 찾음CreateChildControls() 실행
            output.WriteBeginTag("table");
            output.Write(">");
            output.WriteBeginTag("tr");
            output.Write(">");
            output.WriteBeginTag("td");
            output.Write(">");
txtbl.RenderControl(output); //하위컨트롤 뿌려줌

            output.WriteEndTag("td");
            output.WriteEndTag("tr");
            output.WriteEndTag("table");
        }
        private TextBox txtbl;
        protected override void CreateChildControls()
        {
            txtbl = new TextBox();
            this.Controls.Add(txtbl);
        }

    }
}

 

아이프레임 또는 프레임이 나눠져 있는상태에서 아작스 툴킷에 있는 달력이 안뜰때 있음 이럴떄

 

 

<script type="text/javascript">document.domain="도메인주소";</script>

 

 

페이지에 도메인을 설정하면 여러가지  해결방법중에 하나인거 같아욤~ 

string.Format("{0:#,#}",ac_new.InsuVal);

 

 


      double value;

      value = 1.2;
      Console.WriteLine(value.ToString("0.00", CultureInfo.InvariantCulture));
      // Displays 1.20
      Console.WriteLine(value.ToString("00.00", CultureInfo.InvariantCulture));
      // Displays 01.20
      Console.WriteLine(value.ToString("00.00", 
                        CultureInfo.CreateSpecificCulture("da-DK")));
      // Displays 01,20

      value = .086;
      Console.WriteLine(value.ToString("#0.##%", CultureInfo.InvariantCulture)); 
      // Displays 8.6%

      value = 86000;
      Console.WriteLine(value.ToString("0.###E+0", CultureInfo.InvariantCulture));
       // Displays 8.6E+4

<html>
<script>
function dectectDotnet(){
var ag = navigator.userAgent;
if (ag.indexOf("IE") == -1){
    return false;
}
if (ag.indexOf("NET CLR") == -1){
    return false;
}
if (ag.indexOf("NET CLR 2") != -1){
    return true;
}
}
</script>

<body>
<script>
var r = dectectDotnet();
if (r != true){
  var a = confirm(".NET 2.0 런타임이 필요합니다.\r\n설치하시겠습니까?");
  if (a){
     window.open("http://www.microsoft.com/downloads/details.aspx?FamilyID=0856eacb-4362-4b0d-8edd-aab15c5e04f5&DisplayLang=ko");
  }
}
</script>
<body>
</html>

[C#]
private void CreateMyListView()
{
    // Create a new ListView control.
    ListView listView1 = new ListView();
    listView1.Bounds = new Rectangle(new Point(10,10), new Size(300,200));
    // Set the view to show details.
    listView1.View = View.Details;
    // Allow the user to edit item text.
    listView1.LabelEdit = true;
    // Allow the user to rearrange columns.
    listView1.AllowColumnReorder = true;
    // Display check boxes.
    listView1.CheckBoxes = true;
    // Select the item and subitems when selection is made.
    listView1.FullRowSelect = true;
    // Display grid lines.
    listView1.GridLines = true;
    // Sort the items in the list in ascending order.
    listView1.Sorting = SortOrder.Ascending;
    // Create three items and three sets of subitems for each item.
    ListViewItem item1 = new ListViewItem("item1",0);
    // Place a check mark next to the item.
    item1.Checked = true;
    item1.SubItems.Add("1");
    item1.SubItems.Add("2");
    item1.SubItems.Add("3");

    ListViewItem item2 = new ListViewItem("item2",1);
    item2.SubItems.Add("4");
    item2.SubItems.Add("5");
    item2.SubItems.Add("6");
    ListViewItem item3 = new ListViewItem("item3",0);
    // Place a check mark next to the item.
    item3.Checked = true;
    item3.SubItems.Add("7");
    item3.SubItems.Add("8");
    item3.SubItems.Add("9");
    // Create columns for the items and subitems.
    listView1.Columns.Add("Item Column", -2, HorizontalAlignment.Left);
    listView1.Columns.Add("Column 2", -2, HorizontalAlignment.Left);
    listView1.Columns.Add("Column 3", -2, HorizontalAlignment.Left);
    listView1.Columns.Add("Column 4", -2, HorizontalAlignment.Center);
    //Add the items to the ListView.
          listView1.Items.AddRange(new ListViewItem[]{item1,item2,item3});
    // Create two ImageList objects.
    ImageList imageListSmall = new ImageList();
    ImageList imageListLarge = new ImageList();
    // Initialize the ImageList objects with bitmaps.
    imageListSmall.Images.Add(Bitmap.FromFile("C:\\MySmallImage1.bmp"));
    imageListSmall.Images.Add(Bitmap.FromFile("C:\\MySmallImage2.bmp"));
    imageListLarge.Images.Add(Bitmap.FromFile("C:\\MyLargeImage1.bmp"));
    imageListLarge.Images.Add(Bitmap.FromFile("C:\\MyLargeImage2.bmp"));
    //Assign the ImageList objects to the ListView.
    listView1.LargeImageList = imageListLarge;
    listView1.SmallImageList = imageListSmall;
    // Add the ListView to the control collection.
    this.Controls.Add(listView1);
}

 

설명

ListView 컨트롤을 사용하면 항목 텍스트를 사용하여 항목 목록을 표시할 수 있으며 선택적으로 항목의 형식을 식별하는 아이콘을 표시할 수 있습니다. 예를 들어, Windows 탐색기의 파일 목록은 ListView 컨트롤의 모양과 비슷합니다. 탐색기는 트리에서 현재 선택한 파일과 폴더 목록을 표시합니다. 각 파일 및 폴더는 해당 항목과 연결된 아이콘을 표시하므로 파일 또는 폴더의 형식을 쉽게 확인할 수 있습니다. ListViewItem 클래스는 ListView 컨트롤 내에 있는 항목을 나타냅니다.

목록에 항목을 표시할 때 네 개의 서로 다른 보기를 사용하여 표시할 수 있습니다. 큰 아이콘, 작은 아이콘 또는 세로 목록의 작은 아이콘으로 항목을 표시할 수 있습니다. 또한 항목에는 부모 항목과 관련된 정보가 들어 있는 하위 항목이 있을 수 있습니다.

넷째 보기 스타일인 자세히 보기를 사용하면 하위 항목에 표시되는 정보를 식별하는 열 머리글이 있는 표 형식으로 항목과 하위 항목을 표시할 수 있습니다. ListView 는 단일 또는 다중 선택을 지원합니다.

다중 선택 기능을 사용하면 ListBox 컨트롤에서 사용하는 방법과 유사한 방법으로 항목 목록에서 선택할 수 있습니다. 또한, 선택한 항목을 활성화하여 작업을 수행할 수 있습니다. 예를 들어, ListView 컨트롤을 사용하면 응용 프로그램에서 열어 이용할 수 있도록 파일 목록을 표시할 수 있습니다. 열 파일을 선택하고 두 번 클릭하여 활성화하면 해당 파일을 응용 프로그램에서 열 수 있습니다. 또한 CheckBoxes 속성을 사용하면 ListView에서 작업할 항목을 선택할 수 있는 확인란을 표시할 수 있습니다. ListView 컨트롤을 다양한 방법으로 사용할 수 있습니다. 이 컨트롤을 사용하여 응용 프로그램, 데이터베이스 또는 텍스트 파일 정보를 표시할 수 있습니다. 또한 ListView를 사용하여 처리할 일련의 파일을 선택하는 것과 같은 사용자로부터의 정보를 얻을 수 있습니다.

ListView 에는 모양과 동작에 융통성을 제공하는 많은 속성이 있습니다. View 속성을 사용하면 항목이 표시되는 방법을 변경할 수 있습니다. LargeImageList, SmallImageListStateImageList 속성을 사용하면 항목에 대해 표시되는 이미지가 들어 있는 ImageList 개체를 지정할 수 있습니다. StateImageList의 경우 CheckBoxes 속성이 true 이면 확인란이 표시됩니다.

CheckedItems 속성을 사용하여 ListView.CheckedListViewItemCollection 컬렉션에 액세스하면 어떤 항목이 선택되었는지 확인할 수 있습니다. Columns 속성을 사용하면 ListView.ColumnHeaderCollection에 액세스할 수 있습니다.

이 컬렉션에는 컨트롤의 View 속성이 View.Details로 설정된 경우 표시되는 열 머리글이 저장되어 있습니다. ListView 항목은 Items 속성을 사용하여 추가하거나 제거합니다. Items 속성을 사용하면 컨트롤에 있는 항목을 조작하는 메서드를 제공하는 컨트롤의 ListView.ListViewItemCollection에 액세스할 수 있습니다.

LabelEdit 속성을 사용하면 항목 텍스트를 편집할 수 있도록 할 수 있습니다. 컨트롤에 많은 수의 항목이 들어 있는 경우 항목을 정렬된 목록으로 표시하는 것이 더 편리할 수 있습니다. Sorting 속성을 사용하여 항목을 사전순으로 정렬할 수 있습니다.

ListView 컨트롤의 많은 속성은 컨트롤의 View 속성이 View.Details로 설정된 경우 사용됩니다. AllowColumnReorder 속성을 사용하면 런타임에 ListView 컨트롤의 열 순서를 다시 구성할 수 있습니다. FullRowSelect 속성을 사용하면 항목만이 아니라 항목과 해당 항목의 하위 항목을 모두 선택할 수 있습니다. GridLines 속성을 사용하면 자세히 보기에 모눈선을 표시하여 ListView에서 항목과 하위 항목의 경계를 구분할 수 있습니다. HeaderStyle 속성을 사용하면 표시할 열 머리글의 형식을 지정할 수 있습니다.

ListView 컨트롤에 사용할 수 있는 많은 속성 이외에도 응용 프로그램에서 ListView에 추가 기능을 제공하는데 사용할 수 있는 메서드와 이벤트가 있습니다. BeginUpdateEndUpdate 메서드를 사용하면 항목을 추가할 때마다 컨트롤을 다시 그리지 않고 많은 항목을 ListView에 추가할 수 있습니다. 따라서, 속도가 빨라집니다.

ListView 컨트롤에 항목과 하위 항목이 표시되면 하위 항목을 마우스 오른쪽 단추로 클릭할 때 기능을 제공해야 할 경우가 있습니다. GetItemAt 메서드를 사용하면 클릭한 하위 항목이 속한 항목을 확인할 수 있습니다. 항목이 편집된 후 항목의 유효성 검사를 수행할 경우 변경할 특정 항목을 표시할 수 있습니다. 특정 항목이 컨트롤의 보이는 영역에 있도록 하려면 EnsureVisible 메서드를 호출합니다.

LabelEdit 속성이 true로 설정되어 있으면 BeforeLabelEditAfterLabelEdit 이벤트에 대한 이벤트 처리기를 만들어 텍스트가 변경되기 전과 변경된 후에 텍스트의 유효성을 검사하는 등의 작업을 수행할 수 있습니다.

ListView에 표시된 항목을 편집할 수 있도록 파일을 열거나 대화 상자를 표시하려면 ItemActivate 이벤트에 대한 이벤트 처리기를 만듭니다. ListView에서 열 머리글을 클릭하면 항목이 정렬되게 하려면 ColumnClick에 대한 이벤트 처리기를 만들어 정렬을 수행합니다. CheckBoxes 속성이 true로 설정되어 있는 경우 ItemCheck 이벤트를 사용하여 항목의 확인란 상태가 변경되는 시기를 결정할 수 있습니다.

 

event

따블클릭해서 셀렉트한 아이템 불러오기~

  private void listView1_DoubleClick(object sender, System.EventArgs e)
  {
   if( this.listView1.FocusedItem.Selected)
   {
    this.label1.Text = this.listView1.SelectedItems[0].Text;
   }

  }

수정할려는 부분이 DropDownList일때 기본적으로 선택하는방법

  protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        try
        {

           int index = GridView1.EditIndex;
           GridViewRow row = GridView1.Rows[index];
            Control ddl = ((GridView)sender).Rows[e.RowIndex].FindControl("DropDownList1");
            if (ddl != null) {

                e.NewValues["big_cate"] =((DropDownList) ddl).SelectedValue;
            }         

        }
        catch (System.Exception es) {

            Response.Write(es.ToString());
        }  

    }

간단한방법

ImageButtonSearchBtn 이미지버튼

TextBoxSearchText 텍스트 박스

TextBoxSearchText.Attributes.Add("onkeypress", "if (event.keyCode == 13) {" +this.Page.GetPostBackEventReference(ImageButtonSearchBtn) + "; return false;}");

.CS

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

        if (!IsPostBack) {
        }

//테스트박스에서 키를 눌렀을때 자바스크립트로  이벤트코드를 캐취해서
13을 뒤져서 실행시킴   

this.SearchC.Attributes.Add("onkeydown", "CheckSubmit('"+this.ImageButton1.ClientID+"')");
    }

//실행될 버튼

    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("/Search/Search.aspx?query="+ Server.UrlEncode( this.SearchC.Value ) );
    }
}

.ASPX

//SearchSubmitID 이미지 버튼

function CheckSubmit(SearchSubmitID ){
            if (event.keyCode == 13) {            
                    document.getElementById(SearchSubmitID).focus();      
     }else{
             return;
     }
}

서버 또는 응용 프로그램의 fileEncoding 특성 설정이 UTF-16을 사용하도록 구성되어 있고 UTF-16이 구성 파일의 범위에서 .aspx 페이지에 사용되는 인코딩이 아니면 클라이언트 브라우저로 보내는 출력이 손상되고 페이지의 소스 코드가 표시될 수도 있습니다. 구성된 fileEncoding 값이 페이지에 사용되는 인코딩과 일치하는지 확인하십시오.

응용 프로그램의 전역화 설정을 구성합니다.

<configuration> 요소
system.web 요소(ASP.NET 설정 스키마)
globalization 요소(ASP.NET 설정 스키마)

culture

선택적 특성입니다.

들어오는 웹 요청을 처리하기 위한 기본 culture를 지정합니다.

올바른 culture 문자열을 보려면 System.Globalization.CultureInfo를 참조하십시오.

이 특성을 auto로 설정할 수도 있습니다.

enableClientBasedCulture

선택적 특성입니다.

이 특성은 현재 사용되고 있지 않습니다.

fileEncoding

선택적 특성입니다.

.aspx, .asmx 및 .asax 파일 구문 분석에 대한 기본 인코딩을 지정합니다. byte order mark 접두사를 사용하여 저장한 유니코드 및 UTF-8 파일은 이 특성의 값에 관계없이 자동으로 인식됩니다.

requestEncoding

선택적 특성입니다.

게시된 데이터와 쿼리 문자열을 포함하여 들어오는 각 요청이 암호화되었다고 지정합니다.

요청이 Accept-Charset 특성을 포함하는 요청 헤더와 함께 전달되면 구성에서 이 특성이 재정의됩니다.

기본 인코딩은 .NET Framework를 설치할 때 만들어진 Machine.config 파일의 globalization 섹션에 지정된 UTF-8입니다. Machine.config 또는 Web.config 파일에 요청 인코딩이 지정되어 있지 않으면 인코딩은 기본값으로 컴퓨터의 국가별 옵션 로캘 설정으로 지정됩니다.

단일 서버 응용 프로그램에서는 이 특성과 responseEncoding 특성이 같아야 합니다. 일반적이지는 않지만 기본 서버 인코딩이 각각 다른 다중 서버 응용 프로그램의 경우에는 로컬 Web.config 파일을 사용하여 요청 및 응답 인코딩을 다르게 지정할 수 있습니다.

responseEncoding

선택적 특성입니다.

응답의 내용 인코딩을 지정합니다.

기본 인코딩은 .NET Framework를 설치할 때 만들어진 Machine.config 파일의 globalization 섹션에 지정된 UTF-8입니다. Machine.config 또는 Web.config 파일에 응답 인코딩이 지정되어 있지 않으면 인코딩은 기본값으로 컴퓨터의 국가별 옵션 로캘 설정으로 지정됩니다.

단일 서버 응용 프로그램에서는 이 특성과 requestEncoding 특성이 같아야 합니다. 일반적이지는 않지만 기본 서버 인코딩이 각각 다른 다중 서버 응용 프로그램의 경우에는 로컬 Web.config 파일을 사용하여 요청 및 응답 인코딩을 다르게 지정할 수 있습니다.

uiCulture

선택적 특성입니다.

로캘 종속 리소스 검색을 처리하기 위한 기본 culture를 지정합니다. 올바른 culture 문자열을 보려면 System.Globalization.CultureInfo를 참조하십시오.

이 특성을 auto로 설정할 수도 있습니다.

 
사용예제
<globalization requestEncoding="utf-8" 
               responseEncoding="utf-8" 
               fileEncoding="" 
               culture="" 
               uiCulture="" 
               enableClientBasedCulture="false" 
               responseHeaderEncoding="utf-8" 
               resourceProviderFactoryType="" 
               enableBestFitResponseEncoding="false" />

ClientScriptManager

비하인드 코드에서 자바스크립트 사용하기

ClientScriptManager 클래스는 클라이언트측 스크립트를 관리하고 웹 응용 프로그램에 추가하는 데 사용됩니다. Page 개체의 ClientScript 속성에서 ClientScriptManager 클래스에 대한 참조를 가져올 수 있습니다.

페이지의 HTML 태그에 스크립트를 포함시켜 웹 페이지에 클라이언트측 스크립트를 선언적으로 추가할 수 있습니다. 그러나 클라이언트측 스크립트를 동적으로 추가해야 하는 경우도 있습니다. 스크립트를 동적으로 추가하려면 스크립트를 추가할 시기와 방법에 따라 RegisterClientScriptBlock 메서드, RegisterClientScriptInclude 메서드, RegisterStartupScript 메서드 또는 RegisterOnSubmitStatement 메서드를 사용합니다. 자세한 내용은 방법: ASP.NET 웹 페이지에 동적으로 클라이언트 스크립트 추가를 참조하십시오.

ClientScriptManager 클래스에서는 String 키와 Type으로 스크립트를 고유하게 식별합니다. 키 및 형식이 같은 스크립트는 중복된 것으로 간주됩니다. 페이지에서 사용할 수 있는 여러 사용자 정의 컨트롤의 유사한 스크립트를 서로 혼동하지 않도록 하는 데 도움이 됩니다.

ClientScriptManager 클래스는 다시 게시를 수행하지 않고 클라이언트에서 서버 코드를 실행하는 편이 나은 경우에 클라이언트 콜백을 호출하는 데 사용됩니다. 클라이언트 콜백 호출은 서버에 대한 out-of-band 콜백을 수행하는 것을 의미합니다. 클라이언트 콜백에서 클라이언트 스크립트 함수는 ASP.NET 웹 페이지로 비동기 요청을 보냅니다. 웹 페이지에서는 해당 페이지의 정상 수명 주기의 수정된 버전을 실행하여 콜백을 처리합니다. 호출될 경우 클라이언트에서 서버측 이벤트를 다시 호출하도록 하는 클라이언트측 함수에 대한 참조를 가져오려면 GetCallbackEventReference 메서드를 사용합니다. 자세한 내용은 ASP.NET 웹 페이지에서 다시 게시하지 않는 클라이언트 콜백 구현을 참조하십시오.

다음 코드 예제에서는 ClientScriptManager 클래스의 RegisterClientScriptBlock 메서드를 사용하는 방법을 보여 줍니다. 페이지에는 두 개의 클라이언트측 스크립트가 정의되는데, 하나는 페이지가 로드될 때 클라이언트측 경고 메시지를 표시하는 PopupScript이고 다른 하나는 HTML 단추의 onClick 이벤트에 대한 클라이언트측 처리기를 정의하는 ButtonClickScript입니다.

<%@ Page Language="C#"%>
<script runat="server">
  public void Page_Load(Object sender, EventArgs e)
  {
    // Define the name and type of the client scripts on the page.
    String csname1 = "PopupScript";
    String csname2 = "ButtonClickScript";
    Type cstype = this.GetType();
    // Get a ClientScriptManager reference from the Page class.
    ClientScriptManager cs = Page.ClientScript;

    // Check to see if the startup script is already registered.
    if (!cs.IsStartupScriptRegistered(cstype, csname1)) //스크립트가 등록되어져 있는지 체크
    {
      String cstext1 = "alert('Hello World');";
cs.RegisterStartupScript(cstype, csname1, cstext1, true); //onLoad  일때 실행됩니다.
    }

    // Check to see if the client script is already registered.
    if (!cs.IsClientScriptBlockRegistered(cstype, csname2))
    {
      StringBuilder cstext2 = new StringBuilder();
      cstext2.Append("<script type=text/javascript> function DoClick() {");
      cstext2.Append("Form1.Message.value='Text from client script.'} </");
      cstext2.Append("script>");
cs.RegisterClientScriptBlock(cstype, csname2, cstext2.ToString(), false);

//false  이면 스크립트 블로 주위로 <script></script>안붙는다는 얘기~
    }
  }
</script>
<html>
  <head>
    <title>ClientScriptManager Example</title>
  </head>
  <body>
  <form id="Form1"
         runat="server">
  <input type="text" id="Message"> <input type="button" value="ClickMe" onclick="DoClick()">
  </form>
  </body>
</html>

+ Recent posts