天天看點

ASP.NET筆記(本人收集整理)

ASP.NET筆記

字元轉日期

string strDate;

DateTime FmtDate=Convert.ToDateTime(this.TxtGetDate.Text);

strDate = FmtDate.ToString("yyyy/MM/dd hh:mm:ss");

今天日期

string strDate=null;

strDate = DateTime.Now.ToShortDateString();

簡繁轉換

'源串  

  dim   strText   as   string   ="要?往?片機的字元串"  

  '要導出的字  

  dim   arrbytOut()   as   byte    

  '??  

  arrbytOut   =   System.Text.Encoding.GetEncoding("GB2312").GetBytes(strText)

2》

string   tmp   =   "";  

  byte[]   tmpBy   =   System.Text.Encoding.UTF8.GetBytes(tmp);    

  byte[]   newBy=System.Text.Encoding.Convert(System.Text.Encoding.UTF8,System.Text.Encoding.Default,tmpBy);

3》

改webconfig不就行了  

  <?xml   version="1.0"   encoding="utf-8"   ?>  

    <globalization   requestEncoding="utf-8"   responseEncoding="utf-8"   />  

改成  

 <?xml   version="1.0"   encoding="gb2312"   ?>  

 <globalization   requestEncoding="gb2312"   responseEncoding="gb2312"   />

文本框

Asp.net中TextBox的TextChanged為什麼不起作用?

把AutoPostBack設定為true, 也要敲一下回車才能激活事件.

在DropDownList中邦定了資料源後,我還要追一個item?

Dropdwonlist1.Items.Insert(0,new   ListItem("--請您選擇--",""));

Dropdwonlist1.Items.Insert(0,new   ListItem("--請選擇--","-1"));

實例:

在ASP.NET 2.0中,可以在資料綁定時,通過設定DropDownList的AppendDataBoundItems屬性為true,在資料綁定之前添加一個新的項目,并且這個新加的項目會儲存在ViewState之中。下面就是一個實作的例子:

C#代碼

<%[email protected] Page Language="C#" %>

<%[email protected] Import Namespace="System.Data" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">...

  ICollection CreateDataSource()

  {

    DataTable dt = new DataTable();

    DataRow dr;

    dt.Columns.Add(new DataColumn("id", typeof(Int32)));

    dt.Columns.Add(new DataColumn("text", typeof(string)));

    for (int i = 0; i < 6; i++)

    {

      dr = dt.NewRow();

      dr[0] = i;

      dr[1] = "清單項目 " + i.ToString();

      dt.Rows.Add(dr);

    }

    DataView dv = new DataView(dt);

    return dv;

  }

  protected void Button1_Click(object sender, EventArgs e)

  {

    Response.Write("<li>DropDownList1 您選擇的項目:" + DropDownList1.SelectedValue

      + " ; " + DropDownList1.SelectedItem.Text);

    Response.Write("<li>DropDownList2 您選擇的項目:" + DropDownList2.SelectedValue

      + " ; " + DropDownList2.SelectedItem.Text);

  }

  protected void Page_Load(object sender, EventArgs e)

  {

    if (!IsPostBack)

    {

      DropDownList1.AppendDataBoundItems = true;

      DropDownList1.Items.Add(new ListItem("-- 請選擇一個選擇項 --", ""));

      DropDownList2.DataSource = DropDownList1.DataSource = CreateDataSource();

      DropDownList2.DataTextField = DropDownList1.DataTextField = "text";

      DropDownList2.DataValueField = DropDownList1.DataValueField = "id";

      DropDownList1.DataBind();

      DropDownList2.DataBind();

    }

  }

</script>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

  <title>DropDownList 補充例子</title>

</head>

<body>

<form id="form1" runat="server">

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

  </asp:DropDownList>

  <asp:DropDownList ID="DropDownList2" runat="server" AppendDataBoundItems="true">

  <asp:ListItem Text="請選擇" Value=""></asp:ListItem>

  </asp:DropDownList>

  <asp:Button ID="Button1" runat="server" Text="得到選擇的值" OnClick="Button1_Click" />

</form>

</body>

</html>

VB.NET代碼

<%[email protected] Page Language="VB" AutoEventWireup="true" %>

<%[email protected] Import Namespace="System.Data" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">...

  Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)

    Response.Write("<li>DropDownList1 您選擇的項目:" + DropDownList1.SelectedValue + _

      " ; " + DropDownList1.SelectedItem.Text)

    Response.Write("<li>DropDownList2 您選擇的項目:" + DropDownList2.SelectedValue + _

      " ; " + DropDownList2.SelectedItem.Text)

  End Sub

  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

    If Not IsPostBack Then

      DropDownList1.AppendDataBoundItems = True

      DropDownList1.Items.Add(New ListItem("-- 請選擇一個選擇項 --", ""))

      DropDownList2.DataSource = CreateDataSource()

      DropDownList1.DataSource = CreateDataSource()

      DropDownList2.DataTextField = "text"

      DropDownList1.DataTextField = "text"

      DropDownList2.DataValueField = "id"

      DropDownList1.DataValueField = "id"

      DropDownList1.DataBind()

      DropDownList2.DataBind()

    End If

  End Sub

  Function CreateDataSource() As ICollection

    Dim dt As DataTable = New DataTable()

    Dim dr As DataRow

    dt.Columns.Add(New DataColumn("id", GetType(System.Int32)))

    dt.Columns.Add(New DataColumn("text", GetType(String)))

    For i As Integer = 0 To 6

      dr = dt.NewRow()

      dr(0) = i

      dr(1) = "清單項目 " + i.ToString()

      dt.Rows.Add(dr)

    Next

    Dim dv As DataView = New DataView(dt)

    Return dv

  End Function

</script>

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

  <title>DropDownList 補充例子</title>

</head>

<body>

  <form id="form1" runat="server">

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

    </asp:DropDownList>

    <asp:DropDownList ID="DropDownList2" runat="server" AppendDataBoundItems="true">

      <asp:ListItem Text="請選擇" Value=""></asp:ListItem>

    </asp:DropDownList>

    <asp:Button ID="Button1" runat="server" Text="得到選擇的值" OnClick="Button1_Click" />

  </form>

</body>

</html>

    另外,還可以使用下面的方法添加:

protected void DropDownList1_DataBound(object sender, EventArgs e)

{

DropDownList1.Items.Insert(0,new ListItem("--請選擇--", ""));

}

在ASP.NET中用三個DropDownList控件友善的選擇年月日【原創】

aspx頁面上有三個DropDownList控件,

DropDownList1 表示年,DropDownList2表示月,DropDownList3表示天;

注意用将這三個DropDownList控件的AutoPostBack屬性設為True。

使用者可以友善地選擇年月日,并且每月的日期會随着使用者選擇不同的年,月而發生相應的變化

其背景cs檔案代碼如下:

  private void Page_Load(object sender, System.EventArgs e)

  {

   DateTime tnow=DateTime.Now;//現在時間

   ArrayList  AlYear=new ArrayList();

   int i;

   for(i=2002;i<=2010;i++)

   AlYear.Add(i);

   ArrayList  AlMonth=new ArrayList();

   for(i=1;i<=12;i++)

   AlMonth.Add(i);

   if(!this.IsPostBack )

   {

   DropDownList1.DataSource=AlYear;

   DropDownList1.DataBind();//綁定年

   //選擇目前年

   DropDownList1.SelectedValue=tnow.Year.ToString();

      DropDownList2.DataSource=AlMonth;

      DropDownList2.DataBind();//綁定月

   //選擇目前月

    DropDownList2.SelectedValue=tnow.Month.ToString();

    int year,month;

    year=Int32.Parse(DropDownList1.SelectedValue);

    month=Int32.Parse(DropDownList2.SelectedValue);

   BindDays(year,month);//綁定天

    //選擇目前日期

    DropDownList3.SelectedValue=tnow.Day.ToString();

   }

  }

  //判斷閏年

  private bool CheckLeap(int year)

  {

   if((year%4==0)&&(year%100!=0)||(year%400==0))

            return true;

   else return false; 

  }

  //綁定每月的天數

  private void BindDays( int year,int month)

  {   int i;

   ArrayList  AlDay=new ArrayList();

    switch(month)

    {

     case 1:

     case 3:

     case 5:

     case 7:

     case 8:

     case 10:

     case 12:

         for(i=1;i<=31;i++)

      AlDay.Add(i);

      break;

     case 2:

      if (CheckLeap(year))

      {for(i=1;i<=29;i++)

        AlDay.Add(i);}

      else

      {for(i=1;i<=28;i++)

        AlDay.Add(i);}

      break;

     case 4:

     case 6:

     case 9:

     case 11:

      for(i=1;i<=30;i++)

      AlDay.Add(i);

      break;

           }

   DropDownList3.DataSource=AlDay;

   DropDownList3.DataBind();

  }

//選擇年

  private void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)

  {

   int year,month;

   year=Int32.Parse(DropDownList1.SelectedValue);

   month=Int32.Parse(DropDownList2.SelectedValue);

   BindDays(year,month);

  }

//選擇月

  private void DropDownList2_SelectedIndexChanged(object sender, System.EventArgs e)

  {

   int year,month;

   year=Int32.Parse(DropDownList1.SelectedValue);

   month=Int32.Parse(DropDownList2.SelectedValue);

   BindDays(year,month);

  }

如何給DropDownList控件添加邊框[整理]

<span style="border-right: gray 1px solid; border-top: gray 1px solid;

                border-left: gray 1px solid; border-bottom: gray 1px solid;">

<asp:DropDownList ID="ddlSearch" runat="server">

                    <asp:ListItem Value="title">标題</asp:ListItem>

                    <asp:ListItem Value="content">内容</asp:ListItem>

                    <asp:ListItem Value="author">作者</asp:ListItem>

                </asp:DropDownList>

</span>

Asp.Net Table控件動态生成表格操作執行個體(代碼調試通過)

<form id="Form1" method="post" runat="server">

   <asp:Label id="Label1" style="Z-INDEX: 101; LEFT: 256px; POSITION:

absolute; TOP: 40px" runat="server">Asp.Net Table控件動态生成表格操作執行個體</asp:Label>

   <asp:Button id="Button1" style="Z-INDEX: 105; LEFT: 272px; POSITION:

absolute; TOP: 120px" runat="server"

    Text="生 成"></asp:Button>

   <asp:Table id="Table1" style="Z-INDEX: 104; LEFT: 272px; POSITION:

absolute; TOP: 160px" runat="server"

    GridLines="Both"></asp:Table>

   <asp:DropDownList id="DropDownList2" style="Z-INDEX: 103; LEFT:

344px; POSITION: absolute; TOP: 88px"

    runat="server">

    <asp:ListItem Value="1">1列</asp:ListItem>

    <asp:ListItem Value="2">2列</asp:ListItem>

    <asp:ListItem Value="3">3列</asp:ListItem>

    <asp:ListItem Value="4">4列</asp:ListItem>

    <asp:ListItem Value="5">5列</asp:ListItem>

   </asp:DropDownList>

   <asp:DropDownList id="DropDownList1" style="Z-INDEX: 102; LEFT:

280px; POSITION: absolute; TOP: 88px"

    runat="server">

    <asp:ListItem Value="1">1行</asp:ListItem>

    <asp:ListItem Value="2">2行</asp:ListItem>

    <asp:ListItem Value="3">3行</asp:ListItem>

    <asp:ListItem Value="4">4行</asp:ListItem>

    <asp:ListItem Value="5">5行</asp:ListItem>

   </asp:DropDownList>

  </form>

.aspx.cs

private void Button1_Click(object sender, System.EventArgs e)

  {

   int numrows;

   int numcells;

   int i=0;

   int j=0;

   int row=0;

   TableRow r;

   TableCell c;

   //産生表格

   numrows=Convert.ToInt32(DropDownList1.SelectedValue);

   numcells=Convert.ToInt32(DropDownList2.SelectedValue);

   for(i=0;i<numrows;i++)

   {

    r=new TableRow();

    if(row/2!=0)

    {

     r.BorderColor=Color.Red;

    }

    row+=1;

    for(j=0;j<numcells;j++)

    {

     c=new TableCell();

     c.Controls.Add(new LiteralControl

("row"+j+",cell"+i));

     r.Cells.Add(c);

    }

    Table1.Rows.Add(r);

   } 

  }

DropDownList 控件 DataTextField 和 DataValueField 分開綁定

<SCRIPT runat="server">

Sub Page_Load

  If Not Page.IsPostBack Then

    Dim URLs = New SortedList()

    URLs.Add("Google", "http://www.google.com")

    URLs.Add("MSN", "http://search.msn.com")

    URLs.Add("Yahoo", "http://www.yahoo.com")

    URLs.Add("Lycos", "http://www.lycos.com")

    URLs.Add("AltaVista", "http://www.altavista.com")

    URLs.Add("Excite", "http://www.excite.com")

    '-- Bind SortedList to controls

    RadioButtons.DataSource = URLs

    RadioButtons.DataTextField = "Key"

    RadioButtons.DataValueField = "Value"

    RadioButtons.DataBind()

    CheckBoxes.DataSource = URLs

    CheckBoxes.DataTextField = "Key"

    CheckBoxes.DataValueField = "Value"

    CheckBoxes.DataBind()

    DropDownList.DataSource = URLs

    DropDownList.DataTextField = "Key"

    DropDownList.DataValueField = "Value"

    DropDownList.DataBind()

    ListBox.DataSource = URLs

    ListBox.DataTextField = "Key"

    ListBox.DataValueField = "Value"

    ListBox.DataBind()

  End If

End Sub

</SCRIPT>

使用清單控件的 SelectedIndex 和 SelectedItem 屬性通路有關所選項的資訊。

示例

// The index:

int ListItemIndex;

// Value of the item:

string ListItemValue;

ListItemIndex = ListBox1.SelectedIndex;

ListItemValue = ListBox1.SelectedItem.Value.ToString();

在ASP.NET使用javascript的一點小技巧

我們在進行ASP.NET開發時,經常會用到一些javascript腳本,比如:

private void Button1_Click(object sender, System.EventArgs e)

{

Response.Write( "") ;

}

經常是重複的書寫這些腳本,如果我們能做成一個相應的函數就好了,直接就可以拿來使用。很多人都有自己的一些javascript的函數,但是大部分向這樣的:

///

/// 伺服器端彈出alert對話框

///

/// 提示資訊,例子:"請輸入您姓名!"

/// Page類

public void Alert(string str_Message,Page page)

{

if(!page.IsStartupScriptRegistered ("msgOnlyAlert"))

{

page.RegisterStartupScript("msgOnlyAlert","");

}

}

但是,用的時候,每次都要繼承這個類,用起來還是有些麻煩,如果函數是靜态的函數,類是靜态的類的話,我們不要繼承就可以使用。但是我們怎麼寫呢?

看看這段代碼

#region public static void MessageBox( Page page, string msg )

///

/// 彈出對話框

///

/// 目前頁面的指針,一般為this

/// 消息

public static void MessageBox( Page page, string msg )

{

StringBuilder StrScript = new StringBuilder();

StrScript.Append( "" );

if ( ! page.IsStartupScriptRegistered( "MessageBox" ) )

{

page.RegisterStartupScript( "MessageBox", StrScript.ToString() );

}

}

#endregion

這樣的話我們就能友善使用很多已有的js腳本。

PS:其實很多常用的方法都能寫成靜态函數進行調用的。偶再附幾個例子作為一個參考。

MD5加密:

///

/// MD5 Encrypt

///

/// text

/// md5 Encrypt string

public string MD5Encrypt(string strText)

{

MD5 md5 = new MD5CryptoServiceProvider();

byte[] result = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(strText));

return System.Text.Encoding.Default.GetString(result);

}

取指定長度的随機數:

#region public static string GetRandNum( int randNumLength )

///

/// 取得随機數

///

/// 随機數的長度

///

public static string GetRandNum( int randNumLength )

{

System.Random randNum = new System.Random( unchecked( ( int ) DateTime.Now.Ticks ) );

StringBuilder sb = new StringBuilder( randNumLength );

for ( int i = 0; i < randNumLength; i++ )

{

sb.Append( randNum.Next( 0, 9 ) );

}

return sb.ToString();

}

#endregion

全局變量,在單擊按鈕會丟失值?:

public static string AddState;即可

asp.net頁面保持滾動條的位置

在asp.net中,postback非常常用。最近發現一個小技巧,可以在postback後保持滾動條的位置。

非常簡單。在<%@ Page %>中加入一個屬性:

SmartNavigation="true"

這樣在IE中可以做到保持滾動條位置,并且頁面不會閃。

如果還要Firfox支援,則可以在Page_Load()中加入:

Page.MaintainScrollPositionOnPostBack = true;

這個屬性是.Net2.0的,我把2個方法同時使用,經測試可以滿足要求。

用ASP.NET向Javascript傳遞變量

如果字元變量是字元型像alert()等要這樣用alert("<%=Num%>");

還有Num一定要是public申明

動易如何解決下拉菜單會被swf檔案遮住的問題?

問題:在下拉菜單下面添加了swf檔案後,下拉菜單會被swf檔案遮住,如何解決?

如:

解決:要讓下拉菜單顯示在swf前面,在調用swf的代碼中,加上“<param name="wmode" value="Opaque"> ”代碼即可。

舉例:

<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0' width="772" height="150"><param name='movie' value='http://www.powereasy.net/Express_AD/images/cms_red2.swf'><param name='quality' value='autohigh'><param name="wmode" value="Opaque"><embed src='http://www.powereasy.net/Express_AD/images/cms_red2.swf' quality='autohigh' width="772" height="150" pluginspage='http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash' type='application/x-shockwave-flash'></embed></object>

效果:

說明:

  Flash在輸出時的Html選項視窗中,有個“視窗模式”的選項,如下圖所示:

  以下是Flash的幫助文檔對“視窗模式”的相關說明:

選擇"視窗模式"選項,該選項控制 object 和 embed 标記中的 HTML wmode 屬性。視窗模式修改 Flash 内容邊框或虛拟視窗與 HTML 頁中内容的關系,如下表所示: 

"視窗"不會在 object 和 embed 标記中嵌入任何視窗相關屬性。Flash 内容的背景不透明并使用 HTML 背景顔色。HTML 無法呈現在 Flash 内容的上方或下方。這是預設設定。

"不透明無視窗"将 Flash 内容的背景設定為不透明,并遮蔽 Flash 内容下面的任何内容。"不透明無視窗"将 HTML 内容顯示在 Flash 内容的上方或上面。

"透明無視窗"将 Flash 内容的背景設定為透明。此選項使 HTML 内容顯示在 Flash 内容的上方和下方。

注意在某些情況下,當 HTML 圖像複雜時,透明無視窗模式的複雜呈現方式可能會導緻動畫速度變慢。

  若選擇了“視窗”,則輸出的Html代碼中沒有“<param name="wmode" value="***">”代碼。

  若選擇了“不透明無視窗”,則輸出的Html代碼中有“<param name="wmode" value="opaque"> ”

  若選擇了“透明無視窗”,則輸出的Html代碼中有“<param name="wmode" value="transparent"> ”

即:

  "opaque" 表示在無視窗狀态動畫背景不透明。

  "transparent"表示在無視窗狀态動畫背景透明。

DataGrid控件查詢問題(當數據綁定到datagrid控件後,翻頁到後一頁,當前就不是第一頁了,就會發生此種情況)

如果控件定義分頁後,(查詢出錯,提示currpageindex大於PageCount,或小於0),注意查詢在datagrid控件綁定前,使控件CurrentPageIndex=0,還原到第一頁

如:

strSql = "SELECT ask_productid as 請購單號,ask_department as 請購部門,ask_askdate as 請購日期,ask_staff as 請購人,ask_submitstate as 送出狀態,ask_finishstate as 完成狀態,ask_finishdate as 完成日期,ask_overstate as 結束狀態,ask_assignstate as 分發狀態";

            strSql = strSql + " from AskProduct_Master ";

            strSql = strSql + " where Ask_department like '" + (string)Session["Department"] + "%'";

            strSql = strSql + " And Ask_productid='" + TxtAskBill.Text.Trim() + "'";

            SqlDataAdapter DaSearch = new SqlDataAdapter(strSql, Conn);

            DaSearch.Fill(myDs);

            GridM.DataSource = myDs;

     //控件綁定前,還原

            GridM.CurrentPageIndex = 0;

            GridM.DataBind();

正則表達式

[1-9]/d* 不是0開頭的正整數

-?[^/D]+/.?[^/D]+ 正負小數

怎樣用正規表達式截取截取小數點前面的值。

String str1 = "33.3";

String regex = "([^.]*).*";

String str2 = str1.replaceAll(regex, "$1");

在分頁中行數未滿的行加入空行填充

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.Data.SqlClient;

//在相應表中加入空行

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        NewMethod();

    }

    private void NewMethod()

    {

        string connstr = "server=.;database=Northwind;uid=sa;pwd=wz";

        string strsql = "select top 25 * from Orders";

        SqlConnection cn = new SqlConnection(connstr);

        cn.Open();

        SqlDataAdapter da = new SqlDataAdapter(strsql, cn);

        DataSet ds = new DataSet();

        da.Fill(ds);

        cn.Close();

        DataTable dt = ds.Tables[0];

        int mypage = dt.Rows.Count % Grid.PageSize;

        for (int i = mypage; i < Grid.PageSize; i++)

        {

            DataRow dr = dt.NewRow();

            dr[0] = DBNull.Value;

            dt.Rows.Add(dr);

        }

        Grid.DataSource = dt;

        Grid.DataBind();

    }

    protected void Grid_PageIndexChanged(object source, DataGridPageChangedEventArgs e)

    {

        Grid.CurrentPageIndex = e.NewPageIndex;

        NewMethod();

    }

}

如何控制水晶報表每頁隻有25行

在水晶報表裡面操作,操作如下:   

1、右鍵單擊“詳細資料”節的灰色橫頭,選擇“節專家”,進入“節專家”對話框; 

2、在“公用”頁籤,選中“在後面頁建立頁”複選框; 

3、單擊後面的“x+2”按鈕,進入“公式工作室   -   格式公式編輯器”對話框; 

4、輸入“RecordNumber   mod   25   =   0”,并單擊左上角的“儲存并關閉”按鈕。 

注意:是   Crystal   Report   文法。 

///   25   是你想一頁想有有多少條紀錄數 

asp及asp.net的urlencode問題

我想在asp中加一個連結,指向asp.net網頁,但asp.net的網址是經過 HttpUtility.UrlEncode變形和HttpUtility.UrlDecode變回的,而asp的server.urlencode卻産 生不了和HttpUtility.UrlEncode一樣的編碼,請問有沒有解決辦法

補充:原來asp.net的是"web.aspx?str="+HttpUtility.UrlEncode(str)

和HttpUtility.UrlDecode(Request.QueryString["str"].ToString().Trim())

而asp的是"web.aspx?str="+server.urlencode(str)

結果:已經找出解決方法,在asp送出端"web.aspx?str="+server.urlEncode( server.URLpathencode(str))

asp.net送出端為:"web.aspx?str="+ HttpUtility.UrlEncode( str,System.Text.Encoding.GetEncoding("gb2312"))

asp.net接收端為:str= HttpUtility.UrlDecode(Request.QueryString["str"].ToString().Trim(),System.Text.Encoding.GetEncoding("gb2312"))

其中str為需要傳遞的變量

IIS6中破除ASP上傳200KB的限制

一、修改IIS設定,允許直接編輯配置資料庫,如下圖所示:

screen.width-400)this.width=screen.width-400" 按此在新視窗浏覽圖檔">

二、先在服務裡關閉iis admin service服務 

找到windows/system32/inesrv/下的metabase.xml, 

打開,找到ASPMaxRequestEntityAllowed 把他修改為需要的值,預設為204800,即200K  把它修改為你所需的大小即可。如:51200000(50M)

然後重新開機iis admin service服務

Visual C#常用函數和方法集彙總

  1、DateTime 數字型 

  System.DateTime currentTime=new System.DateTime(); 

  1.1 取目前年月日時分秒 

  currentTime=System.DateTime.Now; 

  1.2 取目前年 

  int 年=currentTime.Year; 

  1.3 取目前月 

  int 月=currentTime.Month; 

  1.4 取目前日 

  int 日=currentTime.Day; 

  1.5 取目前時 

  int 時=currentTime.Hour; 

  1.6 取目前分 

  int 分=currentTime.Minute; 

  1.7 取目前秒 

  int 秒=currentTime.Second; 

  1.8 取目前毫秒 

  int 毫秒=currentTime.Millisecond; 

  (變量可用中文) 

  1.9 取中文日期顯示——年月日時分 

  string strY=currentTime.ToString("f"); //不顯示秒 

  1.10 取中文日期顯示_年月 

  string strYM=currentTime.ToString("y"); 

  1.11 取中文日期顯示_月日 

  string strMD=currentTime.ToString("m"); 

  1.12 取目前年月日,格式為:2003-9-23 

  string strYMD=currentTime.ToString("d"); 

  1.13 取目前時分,格式為:14:24 

  string strT=currentTime.ToString("t"); 

  2、字元型轉換 轉為32位數字型 

  Int32.Parse(變量) Int32.Parse("常量") 

  3、 變量.ToString() 

  字元型轉換 轉為字元串 

  12345.ToString("n"); //生成 12,345.00 

  12345.ToString("C"); //生成 ¥12,345.00 

  12345.ToString("e"); //生成 1.234500e+004 

  12345.ToString("f4"); //生成 12345.0000 

  12345.ToString("x"); //生成 3039 (16進制) 

  12345.ToString("p"); //生成 1,234,500.00% 

  4、變量.Length 數字型 

  取字串長度: 

  如: string str="中國"; 

  int Len = str.Length ; //Len是自定義變量, str是求測的字串的變量名 

  5、字碼轉換 轉為比特碼 

  System.Text.Encoding.Default.GetBytes(變量) 

  如:byte[] bytStr = System.Text.Encoding.Default.GetBytes(str); 

  然後可得到比特長度: 

  len = bytStr.Length; 

  6、System.Text.StringBuilder("") 

  字元串相加,(+号是不是也一樣?) 

  如: 

  System.Text.StringBuilder sb = new System.Text.StringBuilder(""); 

  sb.Append("中華"); 

  sb.Append("人民"); 

  sb.Append("共和國"); 

  7、變量.Substring(參數1,參數2); 

  截取字串的一部分,參數1為左起始位數,參數2為截取幾位。 

  如:string s1 = str.Substring(0,2); 

  8、取遠端使用者IP位址 

  String user_IP=Request.ServerVariables["REMOTE_ADDR"].ToString(); 

  9、穿過代理伺服器取遠端使用者真實IP位址: 

  if(Request.ServerVariables["HTTP_VIA"]!=null){ 

  string user_IP=Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString(); 

  }else{ 

  string user_IP=Request.ServerVariables["REMOTE_ADDR"].ToString(); 

  } 

  10、存取Session值 

  Session["變量"]; 

  如,指派: 

  Session["username"]="小布什"; 

  取值: 

  Object objName=Session["username"]; 

  String strName=objName.ToString(); 

  清空: 

  Session.RemoveAll(); 

  11、用超連結傳送變量 

  String str=Request.QueryString["變量"]; 

  如在任一頁中建超連結:<a href=Edit.aspx?fbid=23>點選</a> 

  在Edit.aspx頁中取值:String str=Request.QueryString["fdid"]; 

  12、建立XML文檔新節點 

  DOC對象.CreateElement("建立節點名"); 

  13、将建立的子節點加到XML文檔父節點下 

  父節點.AppendChild(子節點); 

  14、 删除節點 

  父節點.RemoveChild(節點); 

    15、向頁面輸出:Response 

  Response.Write("字串"); 

  Response.Write(變量); 

  跳轉到URL指定的頁面: 

  Response.Redirect("URL位址"); 

  16、查指定位置是否空字元 

  char.IsWhiteSpce(字串變量,位數)——邏輯型; 

   

  如: 

  string str="中國 人民"; 

  Response.Write(char.IsWhiteSpace(str,2)); //結果為:True, 第一個字元是0位,2是第三個字元。 

  17、查字元是否是标點符号 

  char.IsPunctuation('字元') --邏輯型 

  如: 

  Response.Write(char.IsPunctuation('A')); //傳回:False 

  18、把字元轉為數字,查代碼點,注意是單引号。 

  (int)'字元' 

  如: 

  Response.Write((int)'中'); //結果為中字的代碼:20013 

  19、把數字轉為字元,查代碼代表的字元:(char)代碼 

  如: 

  Response.Write((char)22269); //傳回“國”字。 

  20、 清除字串前後空格: Trim() 

  21、字串替換 

  字串變量.Replace("子字串","替換為") 

  如: 

  string str="中國"; 

  str=str.Replace("國","央"); //将國字換為央字 

  Response.Write(str); //輸出結果為“中央” 

  再如:(這個非常實用) 

  string str="這是<script>腳本"; 

  str=str.Replace("<","<font><</font>"); //将左尖括号替換為<font> 與 < 與 </font> (或換為<,但估計經XML存諸後,再提出仍會還原) 

  Response.Write(str); //顯示為:“這是<script>腳本” 

  如果不替換,<script>将不顯示,如果是一段腳本,将運作;而替換後,腳本将不運作。 

  這段代碼的價值在于:你可以讓一個文本中的所有HTML标簽失效,全部顯示出來,保護你的具有互動性的站點。 

  具體實作:将你的表單送出按鈕腳本加上下面代碼: 

  string strSubmit=label1.Text; //label1是你讓使用者送出資料的控件ID。 

  strSubmit=strSubmit.Replace("<","<font><</font>"); 

  然後儲存或輸出strSubmit。 

  用此方法還可以簡單實作UBB代碼。 

  22、取i與j中的最大值:Math.Max(i,j) 

  如 int x=Math.Max(5,10); // x将取值 10 

  加一點吧 23、字串對比...... 

  23、字串對比一般都用: if(str1==str2){ } , 但還有别的方法: 

  (1)、 

  string str1; str2 

  //文法: str1.EndsWith(str2); __檢測字串str1是否以字串str2結尾,傳回布爾值.如: 

  if(str1.EndsWith(str2)){ Response.Write("字串str1是以"+str2+"結束的"); } 

  (2)、 

  //文法:str1.Equals(str2); __檢測字串str1是否與字串str2相等,傳回布爾值,用法同上. 

  (3)、 

  //文法 Equals(str1,str2); __檢測字串str1是否與字串str2相等,傳回布爾值,用法同上. 

  24、查找字串中指定字元或字串首次(最後一次)出現的位置,傳回索引值:IndexOf() 、LastIndexOf(), 如: 

  str1.IndexOf("字"); //查找“字”在str1中的索引值(位置) 

  str1.IndexOf("字串");//查找“字串”的第一個字元在str1中的索引值(位置) 

  str1.IndexOf("字串",3,2);//從str1第4個字元起,查找2個字元,查找“字串”的第一個字元在str1中的索引值(位置) 

  25、在字串中指定索引位插入指定字元:Insert() ,如: 

  str1.Insert(1,"字");在str1的第二個字元處插入“字”,如果str1="中國",插入後為“中字國”; 

  26、在字串左(或右)加空格或指定char字元,使字串達到指定長度:PadLeft()、PadRight() ,如: 

  <% 

  string str1="中國人"; 

  str1=str1.PadLeft(10,'1'); //無第二參數為加空格 

  Response.Write(str1); //結果為“1111111中國人” , 字串長為10 

  %> 

  27、從指定位置開始删除指定數的字元:Remove() 

  28.反轉整個一維Array中元素的順序。 

  har[] charArray = "abcde".ToCharArray(); 

  Array.Reverse(charArray); 

  Console.WriteLine(new string(charArray)); 

  29.判斷一個字元串中的第n個字元是否是大寫 

  string str="abcEEDddd"; 

  Response.Write(Char.IsUpper(str,3)); 

C# 開發和使用中的33個技巧

1.怎樣定制VC#DataGrid列标題?

  DataGridTableStyle dgts = new DataGridTableStyle();

  dgts.MappingName = "myTable"; //myTable為要載入資料的DataTable

  

  DataGridTextBoxColumn dgcs = new DataGridTextBoxColumn();

  dgcs.MappingName = "title_id";

  dgcs.HeaderText = "标題ID";

  dgts.GridColumnStyles.Add(dgcs);

  。。。

  dataGrid1.TableStyles.Add(dgts);

  2.檢索某個字段為空的所有記錄的條件語句怎麼寫?

  ...where col_name is null

  3.如何在c# Winform應用中接收Enter鍵輸入?

  設一下form的AcceptButton.

  4.比如Oracle中的NUMBER(15),在Sql Server中應是什麼?

  NUMBER(15):用numeric,精度15試試。

  5.sql server的應用like語句的存儲過程怎樣寫?

  select * from mytable where haoma like ‘%’ + @hao + ‘%’

  6.vc# winform中如何讓textBox接受Enter鍵消息(假沒沒有按鈕的情況下)?

  private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)

  {

  if(e.KeyChar != (char)13)

  return;

  else

  //do something;

  }

  7.為什麼(Int32)cmd.ExecuteScalar()指派給Int32變量時提示轉換無效?

  Int32.Parse(cmd.ExecuteScalar().ToString());

  8.DataSource為子表的DataGrid裡怎樣增加一個列以顯示母表中的某個字段?

  在子表裡手動添加一個列。

  DataColumn dc = new DataColumn("newCol", Type.GetType("System.String"));

  dc.Expression = "Parent.parentColumnName";

  dt.Columns.Add(dc); //dt為子表

  9.怎樣使DataGrid顯示DataTable中某列的資料時隻顯示某一部分?

  select ..., SUBSTR(string, start_index, end_index) as ***, *** from ***

  10.如何讓winform的combobox隻能選不能輸入?

  DropDownStyle 屬性确定使用者能否在文本部分中輸入新值以及清單部分是否總顯示。

  值:

  DropDown --- 文本部分可編輯。使用者必須單擊箭頭按鈕來顯示清單部分。

  DropDownList --- 使用者不能直接編輯文本部分。使用者必須單擊箭頭按鈕來顯示清單部分。

  Simple --- 文本部分可編輯。清單部分總可見。

  11.怎樣使winform的DataGrid裡顯示的日期隻顯示年月日部分,去掉時間?

  sql語句裡加上to_date(日期字段,'yyyy-mm-dd')

  12.怎樣把資料庫表的二個列合并成一個列Fill進DataSet裡?

  dcChehao = new DataColumn("newColumnName", typeof(string));

  dcChehao.Expression = "columnName1+columnName2";

  dt.Columns.Add(dcChehao);

  Oracle:

  select col1||col2 from table

  sql server:

  select col1+col2 from table

  13.如何從合并後的字段裡提取出括号内的文字作為DataGrid或其它綁定控件的顯示内容?即把合并後的字段内容裡的左括号(和右括号)之間的文字提取出來。

  Select COL1,COL2, case

  when COL3 like ‘%(%’ THEN substr(COL3, INSTR(COL3, ‘(’ )+1, INSTR(COL3,‘)’)-INSTR(COL3,‘(’)-1)

  end as COL3

  from MY_TABLE

  14.當用滑鼠滾輪浏覽DataGrid資料超過一定範圍DataGrid會失去焦點。怎樣解決?

  this.dataGrid1.MouseWheel+=new MouseEventHandler(dataGrid1_MouseWheel);

  private void dataGrid1_MouseWheel(object sender, MouseEventArgs e)

  {

  this.dataGrid1.Select();

  }

  15.怎樣把鍵盤輸入的‘+’符号變成‘A’?

  textBox的KeyPress事件中

  if(e.KeyChar == '+')

  {

  SendKeys.Send("A");

  e.Handled = true;

  }

  16.怎樣使Winform啟動時直接最大化?

  this.WindowState = FormWindowState.Maximized;

  17.c#怎樣擷取目前日期及時間,在sql語句裡又是什麼?

  c#: DateTime.Now

  sql server: GetDate()

  18.怎樣通路winform DataGrid的某一行某一列,或每一行每一列?

  dataGrid[row,col]

  19.怎樣為DataTable進行彙總,比如DataTable的某列值‘延吉'的列為多少?

  dt.Select("城市='延吉'").Length;

  20.DataGrid資料導出到Excel後0212等會變成212。怎樣使它導出後繼續顯示為0212?

  range.NumberFormat = "0000";

  21.

  ① 怎樣把DataGrid的資料導出到Excel以供列印?

  ② 之前已經為DataGrid設定了TableStyle,即自定義了列标題和要顯示的列,如果想以自定義的視圖導出資料該怎麼辦?

  ③ 把資料導出到Excel後,怎樣為它設定邊框啊?

  ④ 怎樣使從DataGrid導出到Excel的某個列居中對齊?

  ⑤ 資料從DataGrid導出到Excel後,怎樣使标題行在列印時出現在每一頁?

  ⑥ DataGrid資料導出到Excel後列印時每一頁顯示’目前頁/共幾頁’,怎樣實作?

  ①

  private void button1_Click(object sender, System.EventArgs e)

  {

  int row_index, col_index;

  

  row_index = 1;

  col_index = 1;

  

  Excel.ApplicationClass excel = new Excel.ApplicationClass();

  excel.Workbooks.Add(true);

  

  DataTable dt = ds.Tables["table"];

  

  foreach(DataColumn dcHeader in dt.Columns)

  excel.Cells[row_index, col_index++] = dcHeader.ColumnName;

  

  foreach(DataRow dr in dt.Rows)

  {

  col_index = 0;

  foreach(DataColumn dc in dt.Columns)

  {

  excel.Cells[row_index+1, col_index+1] = dr[dc];

  col_index++;

  }

  row_index++;

  }

  excel.Visible = true;

  

  }

  

  private void Form1_Load(object sender, System.EventArgs e)

  {

  SqlConnection conn = new SqlConnection("server=tao; uid=sa; pwd=; database=pubs");

  conn.Open();

  

  SqlDataAdapter da = new SqlDataAdapter("select * from authors", conn);

  ds = new DataSet();

  da.Fill(ds, "table");

  

  dataGrid1.DataSource = ds;

  dataGrid1.DataMember = "table";

  }

  ②dataGrid1.TableStyles[0].GridColumnStyles[index].HeaderText; //index可以從0~dataGrid1.TableStyles[0].GridColumnStyles.Count周遊。

  ③ Excel.Range range;

  range=worksheet.get_Range(worksheet.Cells[1,1],xSt.Cells[ds.Tables[0].Rows.Count+1,ds.Tables[0].Columns.Count]);

  

  range.BorderAround(Excel.XlLineStyle.xlContinuous,Excel.XlBorderWeight.xlThin,Excel.XlColorIndex.xlColorIndexAutomatic,null);

  

  range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic;

  range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle =Excel.XlLineStyle.xlContinuous;

  range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].Weight =Excel.XlBorderWeight.xlThin;

  

  range.Borders[Excel.XlBordersIndex.xlInsideVertical].ColorIndex =Excel.XlColorIndex.xlColorIndexAutomatic;

  range.Borders[Excel.XlBordersIndex.xlInsideVertical].LineStyle = Excel.XlLineStyle.xlContinuous;

  range.Borders[Excel.XlBordersIndex.xlInsideVertical].Weight = Excel.XlBorderWeight.xlThin;

  ④ range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter

  ⑤ worksheet.PageSetup.PrintTitleRows = "$1:$1";

  ⑥ worksheet.PageSetup.CenterFooter = "第&P頁 / 共&N頁";

  22.當把DataGrid的Cell内容指派到Excel的過程中想在DataGrid的CaptionText上顯示進度,但不顯示。WHY?

  ...

  dataGrid1.CaptionText = "正在導出:" + (row + 1) + "/" + row_cnt;

  System.Windows.Forms.Application.DoEvents();

  ...

  

  處理目前在消息隊列中的所有Windows消息。

  

  當運作Windows窗體時,它将建立新窗體,然後該窗體等待處理事件。該窗體在每次處理事件時,均将處理與該事件關聯的所有代碼。所有其他事件在隊列中等待。在代碼處理事件時,應用程式并不響應。如果在代碼中調用DoEvents,則應用程式可以處理其他事件。

  如果從代碼中移除DoEvents,那麼在按鈕的單機事件處理程式執行結束以前,窗體不會重新繪制。通常在循環中使用該方法來處理消息。

  23.怎樣從Flash調用外部程式,如一個C#編譯後生成的.exe?

  fscommand("exec", "應用程式.exe");

  ① 必須把flash釋出為.exe

  ② 必須在flash生成的.exe檔案所在目錄建一個名為fscommand的子目錄,并把要調用的可執行程式拷貝到那裡。

  24.有沒有辦法用代碼控制DataGrid的上下、左右的滾動?

  dataGrid1.Select();

  SendKeys.Send("{PGUP}");

  SendKeys.Send("{PGDN}");

  SendKeys.Send("{^{LEFT}"); // Ctrl+左方向鍵

  SendKeys.Send("{^{RIGHT}"); // Ctrl+右方向鍵

  25.怎樣使兩個DataGrid綁定兩個主從關系的表?

  DataGrid1.DataSource = ds;

  DataGrid1.DataMember = "母表";

  ...

  DataGrid2.DataSouce = ds;

  DataGrid2.DataMember = "母表.關系名";

  26.assembly的版本号怎樣才能自動生成?特别是在Console下沒有通過VStudio環境編寫程式時。

  關鍵是AssemblyInfo.cs裡的[assembly: AssemblyVersion("1.0.*")],指令行編譯時包含AssemblyInfo.cs

  27.怎樣建立一個Shared Assembly?

  用sn.exe生成一個Strong Name:keyfile.sn,放在源程式目錄下

  在項目的AssemblyInfo.cs裡[assembly: AssemblyKeyFile("..//..//keyfile.sn")]

  生成dll後,用gacutil /i myDll.dll放進Global Assembly Cach.

  28.在Oracle裡如何取得某字段第一個字母為大寫英文A~Z之間的記錄?

  select * from table where ascii(substr(字段,1,1)) between ascii('A') and ascii('Z')

  29.怎樣取得目前Assembly的版本号?

  Process current = Process.GetCurrentProcess();

  FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(current.MainModule.FileName);

  Console.WriteLine(myFileVersionInfo.FileVersion);

  30.怎樣制作一個簡單的winform安裝程式?

  ① 建一個WinForm應用程式,最最簡單的那種。運作。

  ② 添加新項目->安裝和部署項目,‘模闆’選擇‘安裝向導’。

  ③ 連續二個‘下一步’,在‘選擇包括的項目輸出’步驟打勾‘主輸出來自’,連續兩個‘下一步’,‘完成’。

  ④ 生成。

  ⑤ 到項目目錄下找到Setup.exe(還有一個.msi和.ini檔案),執行。

  31.怎樣通過winform安裝程式在Sql Server資料庫上建表?

  ① [項目]—[添加新項]

  類别:代碼;模闆:安裝程式類。

  名稱:MyInstaller.cs

  ② 在SQL Server建立一個表,再[所有任務]—[生成SQL腳本]。

  生成類似如下腳本(注意:把所有GO語句去掉):

  if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[MyTable]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)

  drop table [dbo].[MyTable]

  

  CREATE TABLE [dbo].[MyTable] (

  [ID] [int] NOT NULL ,

  [NAME] [nchar] (4) COLLATE Chinese_PRC_CI_AS NOT NULL

  ) ON [PRIMARY]

  

  

  ALTER TABLE [dbo].[MyTable] WITH NOCHECK ADD

  CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED

  (

  [ID]

  ) ON [PRIMARY]

  ③ [項目]—[添加現有項]。mytable.sql—[生成操作]-[嵌入的資源]。

  ④ 将MyInstaller.cs切換到代碼視圖,添加下列代碼:

  先增加:

  using System.Reflection;

  using System.IO;

  然後:

  private string GetSql(string Name)

  {

  try

  {

    Assembly Asm = Assembly.GetExecutingAssembly();

    Stream strm = Asm.GetManifestResourceStream(Asm.GetName().Name + "." + Name);

    StreamReader reader = new StreamReader(strm);

    return reader.ReadToEnd();

  }

  catch (Exception ex)

  {

    Console.Write("In GetSql:"+ex.Message);

    throw ex;

  }

  }

  

  private void ExecuteSql(string DataBaseName,string Sql)

  {

  System.Data.SqlClient.SqlConnection sqlConn = new System.Data.SqlClient.SqlConnection();

  sqlConn.ConnectionString = "server=myserver; uid=sa; password=; database=master";

  System.Data.SqlClient.SqlCommand Command = new System.Data.SqlClient.SqlCommand(Sql,sqlConn);

  

  Command.Connection.Open();

  Command.Connection.ChangeDatabase(DataBaseName);

  try

  {

  Command.ExecuteNonQuery();

  }

  finally

  {

  Command.Connection.Close();

  }

  }

  protected void AddDBTable(string strDBName)

  {

  try

  {

  ExecuteSql("master","create DATABASE "+ strDBName);

  ExecuteSql(strDBName,GetSql("mytable.sql"));

  }

  catch(Exception ex)

  {

  Console.Write("In exception handler :"+ex.Message);

  }

  }

  

  public override void Install(System.Collections.IDictionary stateSaver)

  {

  base.Install(stateSaver);

  AddDBTable("MyDB"); //建一個名為MyDB的DataBase

  }

  ⑤ [添加新項目]—[項目類型:安裝和部署項目]—[模闆:安裝項目]—[名稱:MySetup]。

  ⑥ [應用程式檔案夾]—[添加]—[項目輸出]—[主輸出]。

  ⑦ 解決方案資料總管—右鍵—[安裝項目(MySetup)]—[視圖]—[自定義操作]。[安裝]—[添加自定義操作]—[輕按兩下:應用程式檔案夾]的[主輸出來自***(活動)]。

  32.怎樣用TreeView顯示父子關系的資料庫表(winform)?

  三個表a1,a2,a3, a1為a2看母表,a2為a3的母表。

  a1: id, name

  a2: id, parent_id, name

  a3: id, parent_id, name

  用三個DataAdapter把三個表各自Fill進DataSet的三個表。

  用DataRelation設定好三個表之間的關系。

  

  foreach(DataRow drA1 in ds.Tables["a1"].Rows)

  {

   tn1 = new TreeNode(drA1["name"].ToString());

   treeView1.Nodes.Add(tn1);

   foreach(DataRow drA2 in drA1.GetChildRows("a1a2"))

   {

  tn2 = new TreeNode(drA2["name"].ToString());

  tn1.Nodes.Add(tn2);

  foreach(DataRow drA3 in drA2.GetChildRows("a2a3"))

  {

   tn3 = new TreeNode(drA3["name"].ToString());

   tn2.Nodes.Add(tn3);

  }

   }

  }

  33.怎樣從一個form傳遞資料到另一個form?

  假設Form2的資料要傳到Form1的TextBox。

  在Form2:

  // Define delegate

  public delegate void SendData(object sender);

  // Create instance

  public SendData sendData;

  在Form2的按鈕單擊事件或其它事件代碼中:

  if(sendData != null)

  {

   sendData(txtBoxAtForm2);

  }

  this.Close(); //關閉Form2

  在Form1的彈出Form2的代碼中:

  Form2 form2 = new Form2();

  form2.sendData = new Form2.SendData(MyFunction);

  form2.ShowDialog();

  ====================

  private void MyFunction(object sender)

  {

  textBox1.Text = ((TextBox)sender).Text;

  }

一段javascript實作縮略圖的好代碼,可以實作縮略圖,代碼如下

  <script language="javascript">

  //顯示縮略圖

  function DrawImage(ImgD,width_s,height_s){

  var image=new Image();

  image.src=ImgD.src;

  if(image.width>0 && image.height>0){

  flag=true;

  if(image.width/image.height>=width_s/height_s){

  if(image.width>width_s){

  ImgD.width=width_s;

  ImgD.height=(image.height*width_s)/image.width;

  }else{

  ImgD.width=image.width;

  ImgD.height=image.height;

  }

  }

  else{

  if(image.height>height_s){

  ImgD.height=height_s;

  ImgD.width=(image.width*height_s)/image.height;

  }else{

  ImgD.width=image.width;

  ImgD.height=image.height;

  }

  }

  }

  }

  </script>

  調用時,很簡單,比如一段ASP代碼的

  <img src="../memberphoto/<%=rs("picpath")%>" align="middle" οnlοad="DrawImage(this,200,200)"></div>

繼續閱讀