asp.net开发收集

收集一些常用的代码便于工作中应用

<% @ Page Language="C#" ResponseEncoding="gb2312" %>
<% @ Import Namespace="System.Data" %>
<% @ Import Namespace="System.Xml" %>
<% @ Import Namespace="System.IO" %>
<Script Language="C#" Runat="Server">
DataSet ds;        //定义公用的DataSet
DataView dv;  //定义公用的DataView
string SortField;
string sPath;
public void Page_Load(Object src,EventArgs e)
{
    if(State["adxml"]==null)
    {
        sPath = Server.MapPath(".") + "//AdBanners//ad_gb.xml";
        ds = new DataSet();
        ds.ReadXml(sPath);
        State["adxml"] = ds;
    }
    else
    {
        ds = (DataSet)State["adxml"];
    }
    dv = ds.Tables[0].DefaultView;
    dv.Sort = "ImageUrl";

    if(!Page.IsPostBack)
    {
        CreateTable();
    }
}

//捆绑Binder
public void CreateTable()
{

    dgXML.DataSource = dv;
    dgXML.DataBind();
}

//翻页时
public void dgXML_Changed(Object sender,DataGridPageChangedEventArgs e)
{
    CreateTable();
}

//删除
public void DelItem(Object sender,DataGridCommandEventArgs e)
{
    if(((LinkButton)e.CommandSource).CommandName == "del")
    {
        //首先取得当前更新页的行数与CurrentPageIndex
        int CPI = (int)dgXML.CurrentPageIndex;
        int EII = (int)e.Item.ItemIndex;
        int row = CPI*5+EII;

        lb.Text = row.ToString();

        //删除
        dv.Delete(row);

        dgXML.EditItemIndex = -1;
        ds.WriteXml(sPath);

        CreateTable();
    }
}

//取消
public void dgXML_Cancel(Object sender,DataGridCommandEventArgs e)
{
    dgXML.EditItemIndex = -1;
    CreateTable();
}

//编辑
public void dgXML_Edit(Object sender,DataGridCommandEventArgs e)
{
    dgXML.EditItemIndex = (int)e.Item.ItemIndex;
    CreateTable();
}

//更新
public void dgXML_Update(Object sender, DataGridCommandEventArgs e)
{
    try
    {
        //首先取得当前更新页的行数与CurrentPageIndex
        int CPI = (int)dgXML.CurrentPageIndex;
        int EII = (int)e.Item.ItemIndex;
        int row = CPI*5+EII;
        //lb.Text = row.ToString();

        //取得各项值

        string ImageUrl         = ((TextBox)e.Item.Cells[2].Controls[0]).Text;
        string NavigateUrl        = ((TextBox)e.Item.Cells[3].Controls[0]).Text;
        string AlternateText  = ((TextBox)e.Item.Cells[4].Controls[0]).Text;
        string Keyword        = ((TextBox)e.Item.Cells[5].Controls[0]).Text;
        string Impressions        = ((TextBox)e.Item.Cells[6].Controls[0]).Text;

        dv.Delete(row);

        DataRow dr = ds.Tables[0].NewRow();
        dr[0] =    ImageUrl;
        dr[1] =    NavigateUrl;
        dr[2] =    AlternateText;
        dr[3] =    Keyword;
        dr[4] =    Impressions;
        ds.Tables[0].Rows.Add(dr);
        ds.WriteXml(sPath);
    }
    catch(Exception ee)
    {
        lb.Text = ee.ToString();
    }

    dgXML.EditItemIndex = -1;
    CreateTable();


}

public void PanelShow(Object sender,EventArgs e)
{
    AddItem.Visible = true;
}

public void AddItem_Click(Object sender,EventArgs e)
{
    DataRow dr = ds.Tables[0].NewRow();
    dr[0] =    mUrl.Text;
    dr[1] =    aUrl.Text;
    dr[2] =    mText.Text;
    dr[3] =    aKey.Text;
    dr[4] =    aTime.Text;
    ds.Tables[0].Rows.Add(dr);
    ds.WriteXml(sPath);
    CreateTable();
    AddItem.Visible=false;
}
</script>
<html>
<head>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:DataGrid id="dgXML" runat="server"
AllowPaging="True"
PageSize="10"
BorderColor="black"
BorderWidth="1"
CellPadding="3"
Font-Name="Verdana"
Font-Size="8pt"
HeaderStyle-BackColor="#aaaadd"
PagerStyle-Mode="NumericPages"
PagerStyle-HorizontalAlign="Right"
PagerStyle-PrevPageText="前页"
PagerStyle-NextPageText="后页"
OnPageIndexChanged="dgXML_Changed"
OnEditCommand="dgXML_Edit"
OnCancelCommand="dgXML_Cancel"
OnUpdateCommand="dgXML_Update"
OnItemCommand="DelItem"
AutoGenerateColumns="false"
>
<property name="Columns">
    <asp:ButtonColumn HeaderText="删除" Text="删除" CommandName="del" />
   。糰sp:EditCommandColumn EditText="修改" CancelText="取消" UpdateText="更新" ItemStyle-Wrap="false" HeaderText="操作区" HeaderStyle-Wrap="false" />
    <asp:BoundColumn HeaderText="图片地址(相对)" SortField="ImageUrl" DataField="ImageUrl" />
    <asp:BoundColumn HeaderText="链接URL" SortField="NavigateUrl" DataField="NavigateUrl" />
    <asp:BoundColumn HeaderText="图片说明" SortField="AlternateText" DataField="AlternateText" />
    <asp:BoundColumn HeaderText="类别" SortField="Keyword" DataField="Keyword" />
    <asp:BoundColumn HeaderText="显示时间" SortField="Impressions" DataField="Impressions" />
</property>
</asp:DataGrid>
<hr>
<asp:Button id="vi" Text="添加新项" OnClick="PanelShow" runat="server"/>
<br>
<asp:Panel id="AddItem" runat="server" Visible="false">
<table>
    <tr Bgcolor="#aaaadd"><td colspan=2>添加新的广告页面</td></tr>
    <tr>
        <td>广告图片URL:</td>
        <td><asp:TextBox id="mUrl" runat="server" Text="http://" /></td>
    </tr>
    <tr>
        <td>广告链接地址:</td>
        <td><asp:TextBox id="aUrl" runat="server" Text="http://" /></td>
    </tr>
    <tr>
        <td>图片说明:</td>
        <td><asp:TextBox id="mText" runat="server" /></td>
    </tr>
    <tr>
        <td>广告所属类别:</td>
        <td><asp:TextBox id="aKey" runat="server" /></td>
    </tr>
    <tr>
        <td>显示时间</td>
        <td><asp:TextBox id="aTime" runat="server" /></td>
    </tr>
    <tr><td>
   <asp:Button id="submit" Text="提交" OnClick="AddItem_Click" runat="server" /></td></tr>
</table>
</asp:Panel>
<asp:Label id="lb" runat="server" />
</form>
</body>
</html> 


public  void  CreateExcel(DataSet  ds,string  typeid,string  FileName)   
                       { 
                                   HttpResponse  resp; 
                                   resp  =  Page.Response; 
                                   resp.ContentEncoding  =  System.Text.Encoding.GetEncoding("GB2312"); 
                                   resp.AppendHeader("Content-Disposition",  "attachment;filename="  +  FileName);                                     
                                   string  colHeaders=  "",  ls_item=""; 
                                   int  i=0; 
 
                                   //定义表对象与行对像,同时用DataSet对其值进行初始化 
                                   DataTable  dt=ds.Tables[0]; 
                                   DataRow[]  myRow=dt.Select("");   
                                   //  typeid=="1"时导出为EXCEL格式文件;typeid=="2"时导出为XML格式文件 
                                   if(typeid=="1") 
                                   { 
                                               //取得数据表各列标题,各标题之间以/t分割,最后一个列标题后加回车符 
                                               for(i=0;i<dt.Columns.Count-1;i++) 
                                                           colHeaders+=dt.Columns[i].Caption.ToString()+"/t"; 
                                               colHeaders  +=dt.Columns[i].Caption.ToString()  +"/n";                                     
                                               //向HTTP输出流中写入取得的数据信息 
                                               resp.Write(colHeaders);             
                                               //逐行处理数据                         
                                               foreach(DataRow  row  in  myRow) 
                                               { 
                                                           //在当前行中,逐列获得数据,数据之间以/t分割,结束时加回车符/n 
                                                           for(i=0;i<row.Table.Columns.Count-1;i++) 
                                                                       ls_item  +=row[i].ToString()  +  "/t";                                                             
                                                           ls_item  +=  row[i].ToString()  +"/n"; 
                                                           //当前行数据写入HTTP输出流,并且置空ls_item以便下行数据                                                 
                                                           resp.Write(ls_item); 
                                                           ls_item=""; 
                                               } 
                                   } 
                                   else 
                                   { 
                                               if(typeid=="2") 
                                               {             
                                                           //从DataSet中直接导出XML数据并且写到HTTP输出流中 
                                                           resp.Write(ds.GetXml()); 
                                               }                                                 
                                   } 
                                   //写缓冲区中的数据到HTTP头文件中 
                                   resp.End(); 
 
 
                       }


Duwamish 7.0 web 项目中提供了一个 Web Service service/catalogservice.asmx ),以向 Internet 公开它的书目录搜索功能。 CatalogService Web Service 由一个 asmx 文件和一个代码隐藏文件组成,其中 ASMX 文件充当调用 Web Services 的客户端的基 URL ,代码隐藏文件包含实现 Web 服务的代码。不过,在整个 Duwamish 项目中并没有调用该 web service ,正如以前的 POST 中所提及的:
If you need to communicate between applications (even .NET apps) then use web services. Note this is not between tiers, but between applications – as in SOA (Service-Oriented Architecture). SOA is not useful INSIDE applications. It is only useful BETWEEN applications.
 
1. Web Services 概述
Web Services 既可以在内部由单个应用程序使用,也可通过 Internet 公开以供外部的应用程序使用。由于可以通过标准接口访问,因此 Web Services 使异类系统能够作为单个计算网络资源协同运行。
Web Services 并不追求一般的代码可移植性功能,而是为实现数据和系统的互操作性提供了一种可行的解决方案。 Web Services 使用基于 XML 的消息处理作为基本的数据通讯方式,以帮助消除使用不同组件模型、操作系统和编程语言的系统之间存在的差异。开发人员可以用像过去在创建分布式应用程序时使用组件一样的方式创建将来自各种平台的 Web Services 组合在一起的应用程序。
Web Services 的核心特征之一是服务的实现与使用之间的高度抽象化。通过将基于 XML 的消息处理机制, Web Services 客户端和 Web Services 提供程序之间除输入、输出和位置之外无需互相了解其他信息。
Web Services 向外界发布出一个能够通过 Web 进行调用的、平台无关的 API 。也就是说,你能够在任何你喜欢的平台上,用编程的方法通过 Web 来调用这个应用程序,进行基于 Web 的分布式计算和处理。 Web Services 平台是一套标准,它定义了应用程序如何在 Web 上实现互操作性。 Web Services 平台采用 XML 来表示数据的基本格式,采用 W3C 制定的 XML Schema(XSD) 来作为其数据类型系统。
组成 Web Services 平台的三个核心的技术规范分别为 SOAP WSDL UDDI SOAP 规范定义了 SOAP 消息的格式,以及怎样通过 HTTP 协议来使用 SOAP ,来执行 Web Services 的调用。 WSDL Web Services 描述语言)用来描述 Web Services 。因为其基于 XML ,所以 WSDL 文档既是机器可阅读的,又是人可阅读的。 UDDI (统一描述,发现和集成协议)标准定义了 Web Services 的发布与发现的方法。
从技术的角度来看, Web Services 可以被认为是一种部署在 Web 上的对象( Web Object ),因此,具有对象技术所承诺的所有优点;同时, Web Services 的基石是以 XML 为主的、开放的 Web 规范技术,因此,具有比任何现有对象技术更好的开放性。
 
2. Duwamish 中的 CatalogService Web Service
(1)CatalogServer.asmx文件中仅包含一行代码:
<%@ WebService Language="c#" Codebehind="CatalogService.cs" Class="Duwamish7.Web.Service.CatalogService" %>
 
2 CatalogService.cs 代码隐藏文件包含实现 web service 的代码:
CatalogService Web 服务实现 GetBooksByTopic GetBooksByTopicSecure Web 方法,返回值为 DataSet 类型(支持 XML 编码和序列化)。 Web Service 发布的上述 Web 方法均都有 WebMethodAttribute
 
WebMethodAttribute 向使用 ASP.NET 创建的 XML Web services 中的某个方法添加此特性后,就可以从远程 Web 客户端调用该方法。
 
另外还有一些辅助的 class 和方法(调用 BusinessFacade tier ),代码比较简单。
 
3 Web.config 配置文件 <webServices> 元素:可以配置使用 ASP.NET 创建的 XML Web services 的设置。
 
 
3. Summary
Web Services 不仅可用于异构平台的相互集成,也是分布式应用开发的一种技术。 Microsoft 在推 .Net Framework 时,尽心尽力吹捧这项技术,并冠以 XML Web Services 。不过由于 Web Services 的性能不好的问题,感觉目前在企业内部应用并不多,估计还不及 .Net Remoting 技术的应用。
Microsoft 还有一个 Web Services 的增强软件开发包: Web Services Enhancements (WSE) Version 2.0 ,主要提供如下特性:安全特性(数字签名和加密),消息路由,消息附件等等,从 Reference 1 可以下载。
现在, Web Services 方面的相关规范很多,如 WS-Security, WS-Policy, WS-Trust, WS-SecureConversation…… ,令人目不暇接,在不断地向前发展。从另外一个方面也表示, Web Services 技术目前在企业应用方面还不够成熟。

 #region 组件设计器生成的代码
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {
   components = new System.ComponentModel.Container();
  }
  #endregion
  private  string GetSql(string Name) 
  { 
//   //调用osql执行脚本
//
//   System.Diagnostics.Process sqlProcess = new System.Diagnostics.Process();
//
//   sqlProcess.StartInfo.FileName = "osql.exe";
//
//   sqlProcess.StartInfo.Arguments = String.Format(" -U {0} -P {1} -d {2} -i {3}db.sql", this.Context.Parameters["user"], this.Context.Parameters["pwd"],"master", this.Context.Parameters["targetdir"]);
//
//   sqlProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
//
//   sqlProcess.Start();
//
//   sqlProcess.WaitForExit() ;//等待执行
//
//   sqlProcess.Close();
   try 
   { 
//    Assembly Asm = Assembly.GetExecutingAssembly();
//    System.IO.FileInfo FileInfo = new System.IO.FileInfo(Asm.Location);
//    string path=FileInfo.DirectoryName+@"/"+Name;
    string path=this.Context.Parameters["targetdir"]+Name;
    FileStream fs=new FileStream(path,FileMode.Open,FileAccess.Read,FileShare.Read);
    StreamReader reader = new StreamReader(fs,System.Text.Encoding.Default); 
    //System.Text.Encoding.ASCII;
    return reader.ReadToEnd(); 
   } 
   catch (Exception ex) 
   { 
    Console.Write("In GetSql:"+ex.Message); 
    throw ex; 
   } 
  } 
  private void ExecuteSql(string DataBaseName,string Sql) 
  {
   SqlConnection sqlConnection1=new SqlConnection();
   sqlConnection1.ConnectionString =string.Format("server={0}; user id={1}; password={2}; Database=master",this.Context.Parameters["server"],this.Context.Parameters["user"],this.Context.Parameters["pwd"]);
   System.Data.SqlClient.SqlCommand Command = new System.Data.SqlClient.SqlCommand(Sql,sqlConnection1); 
   try 
   {
    Command.Connection.Open(); 
    Command.Connection.ChangeDatabase(DataBaseName); 
   
    Command.ExecuteNonQuery(); 
   } 
   catch(Exception ex) 
   { 
    Console.Write("In exception handler :"+ex.Message); 
   }
   finally 
   { 
    Command.Connection.Close(); 
   } 
  } 

  protected void AddDBTable(string strDBName) 
  { 
   try 
   {     
    ExecuteSql("master","CREATE DATABASE "+ strDBName);
    ExecuteSql(strDBName,GetSql("sql.txt")); 
    ExecuteSql("master","exec sp_addlogin 'myoamaster','myoamaster','"+strDBName+"',Null,Null");
    ExecuteSql(strDBName,"EXEC sp_grantdbaccess 'myoamaster', 'myoamaster'");
    ExecuteSql(strDBName,"exec sp_addrolemember 'db_owner','myoamaster'");
   } 
   catch(Exception ex) 
   { 
    Console.Write("In exception handler :"+ex.Message); 
   } 
  } 
  public override void Install(System.Collections.IDictionary stateSaver) 
  { 
   base.Install(stateSaver); 
   AddDBTable(this.Context.Parameters["dbname"]); 
  } 
 }
}
这里有个sql.txt是数据库的sql脚本,当然可以调用osql来执行sql脚本,其实是一样的。
打包的时候必须把sql.txt文件加进来,否则不会执行。
如果你想附加数据库的mdf文件和ldf文件,用下面这段程序:
private void CreateDataBase(string strSql,string DataName,string strMdf,string strLdf)
  {
   String str;
   SqlConnection myConn = new SqlConnection (strSql);
   //EXEC sp_detach_db @dbname = 'BX_FreightMileage_2'//需要先将数据库分离出来
   str = "EXEC sp_attach_db @dbname = '"+ DataName +"', @filename1 = '"+ strMdf +"',@filename2='"+strLdf+"'";
   SqlCommand myCommand = new SqlCommand(str, myConn);
  
    myConn.Open();
    myCommand.ExecuteNonQuery();
    myConn.Close();
  
  }
当然打包的时候也要把这两个数据库文件也加进来。


"^/d+$"  //非负整数(正整数 + 0)
"^[0-9]*[1-9][0-9]*$"  //正整数
"^((-/d+)|(0+))$"  //非正整数(负整数 + 0)
"^-[0-9]*[1-9][0-9]*$"  //负整数
"^-?/d+$"    //整数
"^/d+(/./d+)?$"  //非负浮点数(正浮点数 + 0)
"^(([0-9]+/.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*/.[0-9]+)|([0-9]*[1-9][0-9]*))$"  //正浮点数
"^((-/d+(/./d+)?)|(0+(/.0+)?))$"  //非正浮点数(负浮点数 + 0)
"^(-(([0-9]+/.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*/.[0-9]+)|([0-9]*[1-9][0-9]*)))$"  //负浮点数
"^(-?/d+)(/./d+)?$"  //浮点数
"^[A-Za-z]+$"  //由26个英文字母组成的字符串
"^[A-Z]+$"  //由26个英文字母的大写组成的字符串
"^[a-z]+$"  //由26个英文字母的小写组成的字符串
"^[A-Za-z0-9]+$"  //由数字和26个英文字母组成的字符串
"^/w+$"  //由数字、26个英文字母或者下划线组成的字符串
"^[/w-]+(/.[/w-]+)*@[/w-]+(/.[/w-]+)+$"    //email地址
"^[a-zA-z]+://(/w+(-/w+)*)(/.(/w+(-/w+)*))*(/?/S*)?$"  //url


c#学习体会:使用 ref 和 out 传递数组(downmoon),希望与大家分享
1、与所有的 out 参数一样,在使用数组类型的 out 参数前必须先为其赋值,即必须由接受方为其赋值。例如:

public static void MyMethod(out int[] arr)
{
   arr = new int[10];   // 数组arr的明确委派
}
2、与所有的 ref 参数一样,数组类型的 ref 参数必须由调用方明确赋值。因此不需要由接受方明确赋值。可以将数组类型的 ref 参数更改为调用的结果。例如,可以为数组赋以 null 值,或将其初始化为另一个数组。例如:

public static void MyMethod(ref int[] arr)
{
   arr = new int[10];   // arr初始化为一个新的数组
}
下面的两个示例说明 out 和 ref 在将数组传递给方法上的用法差异。

示例 1
在此例中,在调用方(Main 方法)中声明数组 myArray,并在 FillArray 方法中初始化此数组。然后将数组元素返回调用方并显示。


using System;
class TestOut
{
   static public void FillArray(out int[] myArray)
   {
      // 初始化数组(必须):
      myArray = new int[5] {1, 2, 3, 4, 5};
   }

   static public void Main()
   {
      int[] myArray; // 初始化数组(不是必须的!)

      // 传递数组给(使用out方式的)调用方:
      FillArray(out myArray);

      // 显示数组元素
      Console.WriteLine(数组元素是:);
      for (int i=0; i < myArray.Length; i++)
         Console.WriteLine(myArray[i]);
   }
}
输出
数组元素是:
1
2
3
4
5
示例 2
在此例中,在调用方(Main 方法)中初始化数组 myArray,并通过使用 ref 参数将其传递给 FillArray 方法。在 FillArray 方法中更新某些数组元素。然后将数组元素返回调用方并显示。


using System;
class TestRef
{
   public static void FillArray(ref int[] arr)
   {
      // 根据需要创建一新的数组(不是必须的)
      if (arr == null)
         arr = new int[10];
      // 否则填充数组,就可以了
      arr[0] = 123;
      arr[4] = 1024;
   }

   static public void Main ()
   {
      //初始化数组:
      int[] myArray = {1,2,3,4,5}; 

      // 使用ref传递数组:
      FillArray(ref myArray);

      //显示更新后的数组元素:
      Console.WriteLine(数组元素是:);
      for (int i = 0; i < myArray.Length; i++)
         Console.WriteLine(myArray[i]);
   }
}
输出
数组元素是:
123
2
3
4
1024


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));

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值