c#、sql、asp.net、js、ajax、jquery大学知识点笔记

时间:2023-11-24 20:45:44

<table cellSpacing="0" cellPadding="0" width="609" height="470" align="center" border="0">

<link href="../Css/default.css" rel="stylesheet" type="text/css">

<td width="200" align="left" valign="top" bgcolor="#e2eefe">--

-----------数据绑定

BillBusiness bill = new BillBusiness();

DataSet ds = new DataSet();

ds=bill.GetBillEmployees();

drdlReceiveBillPerson.DataSource = ds.Tables[0];

drdlReceiveBillPerson.DataTextField = "Employee";

drdlReceiveBillPerson.DataBind();

-------------gridview超链接绑定{生成模板}

<asp:TemplateField HeaderText="PackageNo" SortExpression="PackageNo">

<EditItemTemplate>

<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("PackageNo") %>'></asp:TextBox>

</EditItemTemplate>

<ItemTemplate>

<asp:HyperLink ID='HyperLink1' runat="server" NavigateUrl='<%# "OrderStatus.aspx?PackageNo=" + Eval("PackageNo") %>' >

<%#Eval("PackageNo")%>

</asp:HyperLink>

</ItemTemplate>

<ControlStyle Width="75px" />

<HeaderStyle HorizontalAlign="Left" />

<ItemStyle Width="75px" />

</asp:TemplateField>

---------------或者是

<asp:TemplateField HeaderText="票据开始号" SortExpression="BillStartCode">

<EditItemTemplate>

<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("BillStartCode") %>'></asp:TextBox>

</EditItemTemplate>

<Itemtemplate>

<a href="BillDispenseUpdate.aspx?pkid=<%# Eval("BillStartCode") %>"/>

<%# Eval("BillStartCode")%>

</Itemtemplate>

</asp:TemplateField>

--------------删除

this.imgbDelete.Attributes.Add("onclick", "javascript:return confirm('您确实要删除这些记录吗?'); ");

------------------------grieview绑定

<asp:GridView ID="GridView1" runat="server" Width="560px"

AutoGenerateColumns="False"  Height="42px">

<Columns>

<asp:BoundField DataField="BillType" HeaderText="票据类型"

SortExpression="BillType" />

<asp:BoundField DataField="BillCode" HeaderText="票据编号"

SortExpression="BillCode" />

<asp:BoundField DataField="BillState" HeaderText="票据类型"

SortExpression="BillState" />

<asp:BoundField DataField="WriteDate" HeaderText="填票时间"

SortExpression="WriteDate" />

<asp:BoundField DataField="AcceptStation" HeaderText="领票地点"

SortExpression="AcceptStation" />

</Columns>

</asp:GridView>

------------------------------存储过程

ALTER PROCEDURE [dbo].[feng]

AS

declare @num varchar(10), @sqls nvarchar(4000)

set @sqls='select @a=name from xuesheng where id=01'

exec sp_executesql @sqls,N'@a varchar(10) output',@num output

return @num

------------------------------游标

ALTER PROCEDURE [dbo].[ze]

(

@num1 int

)

AS

begin

declare @b int

declare @f int

declare @c int

declare @g int

declare a cursor for select num1,num2 from 游标

open a

while @@fetch_status=0

begin

fetch next from a into @b,@c

if  @num1>=@b and @num1<=@c

return 10

end

close a

return 0

end

----------------------------------函数日期取整形

ALTER FUNCTION [dbo].[funGenerateBillCode](@billType NVARCHAR(50) ,@billCode NVARCHAR(50),@receiveBillTime datetime)

RETURNS CHAR(11)

AS

BEGIN

DECLARE @e NVARCHAR(50)

DECLARE @a int

DECLARE @b int

DECLARE @c NVARCHAR(50)

IF @billType='货运单'

SET @e='C'

ELSE

SET @e='R'

SELECT @a=DATEPART(YEAR,@receiveBillTime)

SELECT @b=DATEPART(MONTH,@receiveBillTime)

SET @c=CONVERT(NVARCHAR(50),@a*100+@b)

SET @e=@e+@c+@billCode

RETURN @e

END

----------------------------------------文件流

public static void Log(string message)

{

string fileName = System.Web.HttpContext.Current.Server.MapPath(EXPConfiguration.Log);

if(File.Exists(fileName))

{

StreamWriter sr = File.AppendText(fileName);

sr.WriteLine ("\n");

sr.WriteLine (DateTime.Now.ToString()+message);

sr.Close();

}

else

{

StreamWriter sr = File.CreateText(fileName);

sr.Close();

Log(message);

}

}

}

---------------------------------------------------------

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

<MenuItem Text="快递运输管理系统" NavigateUrl="~/Index.aspx" ImageUrl="Images/tu005.gif">

<MenuItem Text="票据管理" NavigateUrl="~/Index.aspx" ImageUrl="Images/tu008.gif">

<MenuItem Text="票据分发" NavigateUrl="~/Bill/BillDispenseCreate.aspx" ImageUrl="Images/tu008.gif"></MenuItem>

<MenuItem Text="票据查询" NavigateUrl="~/Bill/BillDispenseList.aspx" ImageUrl="Images/tu008.gif"></MenuItem>

<MenuItem Text="票据销核" NavigateUrl="~/Bill/BillDetailList.aspx" ImageUrl="Images/tu008.gif"></MenuItem>

</MenuItem>

</MenuItem>

</MenuItem>

---------------------------------------------------------------样式连接+消除乱码

<link href="App_Themes/Default/default.css" type="text/css" rel="Stylesheet" />

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">

--------------------------------------------------------------------文本写入预读取

----------------------------------------------------------------------------------三层架构实体模型

缓存:-------------------------------

// ===================================================================

// 工厂(COM.OA.DBFactory)项目

//====================================================================

// wabgyp @Copy Right 2006-2008

// 文件:DataCache.cs

// 项目名称:工程项目管理

// 创建时间:2008-9-23

// 负责人:wangyp

// 引用System.Web程序集

// ===================================================================

using System;

using System.Web;

namespace COM.OA.DBFactory

{

/// <summary>

/// 数据缓存对象

/// </summary>

public class DataCache

{

public DataCache()

{

}

/// <summary>

/// 获得缓存对象

/// </summary>

/// <param name="CacheKey">键</param>

/// <returns>缓存对象</returns>

public static object GetCache(string CacheKey)

{

System.Web.Caching.Cache objCache = HttpRuntime.Cache;

return objCache[CacheKey];

}

/// <summary>

/// 设置缓存对象

/// </summary>

/// <param name="CacheKey">键</param>

/// <param name="objObject">要被缓存的对象</param>

public static void SetCache(string CacheKey, object objObject)

{

System.Web.Caching.Cache objCache = HttpRuntime.Cache;

objCache.Insert(CacheKey, objObject);

}

}

}

反射:-------------------

// ===================================================================

// 工厂(COM.OA.DBFactory)项目

//====================================================================

// wangyp @Copy Right 2006-2008

// 文件:DALFactory.cs

// 项目名称:工程项目管理

// 创建时间:2008-9-23

// 负责人:wangyp

// 先创建DataCache.cs文件,引用实体(COM.OA.Entity)和产品规则(COM.OA.IDAL)项目,System.Configuration程序集

// 在 web.config 文件

/*

<appSettings>

<add key="DAL" value="COM.OA.SqlServerDAL"/>

</appSettings>

*/

// ===================================================================

using System;

using System.Reflection;

using COM.OA.IDAL;

namespace COM.OA.DBFactory

{

/// <summary>

/// 数据层工厂

/// </summary>

public class DALFactory

{

/// <summary>

/// 通过反射机制,实例化接口对象

/// </summary>

private static readonly string _path = System.Configuration.ConfigurationManager.AppSettings["DAL"];

/// <summary>

/// 通过反射机制,实例化接口对象

/// </summary>

/// <param name="CacheKey">接口对象名称(键)</param>

///<returns>接口对象/returns>

private static object GetInstance(string CacheKey)

{

object objType = DataCache.GetCache(CacheKey);

if (objType == null)

{

try

{

objType = Assembly.Load(DALFactory._path).CreateInstance(CacheKey);

DataCache.SetCache(CacheKey, objType);

}

catch (Exception ex)

{

throw ex;

}

}

return objType;

}

SqlDataReader   sdr     =   command.ExecuteReader();//**就是这里改了一下**

sdr.Read();//

int   result   =   Convert.ToInt32(sdr[0]);//返回return返回的值

int   mycount   =   Convert.ToInt32(command.Parameters[ "@mycount "].Value);//返回output值

获取存储过程返回值,当然也可已接收变量

SqlParameter p2 = new SqlParameter("values", SqlDbType.Int);

p2.Direction = ParameterDirection.ReturnValue;

cmd.Parameters.Add(p2);

MessageBox.Show(cmd.Parameters["values"].Value.ToString());

----------------------------postajax

<script type="text/javascript">

window.onload = function () {

$("#add").click(function () {

var x = new XMLHttpRequest();

x.onreadystatechange = function () {

if (x.readyState == 4 && x.status == 200) {

var result = x.responseText;

$("#info").html(result);

}

}

x.open("post", "Handler4.ashx", true);

x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); //一个字都不能差;//放在open和send之间;

var body = "a=" + $("#Text1").val() + "&b=" + $("#Text2").val();

x.send(body);

})

}

</script>

------------------------------------------ajax综合:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="_1_Default4" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

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

<head runat="server">

<title></title>

<script src="../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

<script src="../Scripts/cookie.js" type="text/javascript"></script>

<script type="text/javascript">

window.onload = function () {

$("#add").click(function () {

var x = new XMLHttpRequest();

x.onreadystatechange = function () {

if (x.readyState == 4 && x.status == 200) {//注意readyState中的s是大写的。

var result = x.responseText;

$("#info").html(result);

}

}

x.open("post", "Handler4.ashx", true);

x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); //一个字都不能差;//放在open和send之间;

var body = "a=" + $("#Text1").val() + "&b=" + $("#Text2").val();

x.send(body);

});

$("#xmladd").click(function () {

var x = new XMLHttpRequest();

x.onreadystatechange = function () {

if (x.readyState == 4 && x.status == 200) {

var result = x.responseXML;

var xml = $(result);

$("#info").html(xml.find("result").text());

}

}

x.open("post", "Handler3.ashx", true);

x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); //一个字都不能差;//放在open和send之间;

var body = "a=" + $("#Text1").val() + "&b=" + $("#Text2").val();

x.send(body);

});

$("#buttonheader").click(function () {

var x = new XMLHttpRequest();

x.onreadystatechange = function () {

if (x.readyState == 4 && x.status == 200) {

var result = x.getResponseHeader("result");

$("#info").html(result + "<hr/>" + x.getAllResponseHeaders());

}

}

x.open("post", "Handler5.ashx", true);

x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); //一个字都不能差;//放在open和send之间;

//var body = "a=" + $("#Text1").val() + "&b=" + $("#Text2").val();

var a = $("#Text1").val();

var b = $("#Text2").val();

//////////

x.setRequestHeader("a", a);

x.setRequestHeader("b", b);

///////////////

x.send(null);

});

$("#cookie").click(function () {

var x = new XMLHttpRequest();

x.onreadystatechange = function () {

if (x.readyState == 4 && x.status == 200) {

var result =getCookie("result");

$("#info").html(result);

}

}

x.open("post", "Handler6.ashx", true);

// x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); //一个字都不能差;//放在open和send之间;

//var body = "a=" + $("#Text1").val() + "&b=" + $("#Text2").val();

var a = $("#Text1").val();

var b = $("#Text2").val();

//////////存数据到cookies中

setCookie("a", a);

setCookie("b", b);

///////////////

x.send(null);

});

$("#jquery").click(function () {

//var x = new XMLHttpRequest();

// x.onreadystatechange = function () {

//if (x.readyState == 4 && x.status == 200) {

//var result = x.responseXML;

//var xml = $(result);

// $("#info").html(xml.find("result").text());

// }

// }

//  x.open("post", "Handler3.ashx", true);

//  x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); //一个字都不能差;//放在open和send之间;

//  var body = "a=" + $("#Text1").val() + "&b=" + $("#Text2").val();

//  x.send(body);

$.post("Handler3.ashx","a=1&b=2",function(x){

if (x.readyState == 4 && x.status == 200) {

var result = x.responseXML;

var xml = $(result);

$("#info").html(xml.find("result").text());

},"xml")

});

}

function jquery_onclick() {

}

</script>

</head>

<body>

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

<div>

<input id="button" type="button" value="showtime" onclick="showtime()" />

<input id="add" type="button" value="add"  />

<input id="xmladd" type="button" value="xmladd"  />

<input id="Text1" type="text" />

<input id="Text2" type="text" />

<br />

<input id="buttonheader" type="button" value="addheader"  />

<input id="cookie" type="button" value="cookie"  />

<input id="jquery" type="button" value="jquery"  onclick="return jquery_onclick()" />

</div>

<div id="info" ></div>

</form>

</body>

</html>

-------------------------------------aspajax

<%@ WebHandler Language="C#" class="Handler" %>

using System;

using System.Web;

public class Handler : IHttpHandler {

public void ProcessRequest (HttpContext context) {

context.Response.ContentType = "text/plain";

string firstname = context.Request.Params["firstname"];

string lastname = context.Request.Params["lastname"];

string title = context.Request.Params["title"];

Employee employee = new Employee(firstname,lastname,title);

System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

string js = serializer.Serialize(employee);

//序列化

context.Response.Write(js);

}

public bool IsReusable {

get {

return false;

}

}

}

----

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default4" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

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

<head runat="server">

<title></title>

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

<script type="text/javascript" >

$(function () {

$("#buttonok").click(function () {

var fname = $("#first").val();

var lname = $("#last").val();

var title = $("#title").val();

var request = new Sys.Net.WebRequest(); //xmlhttprequest的new

request.set_httpVerb("POST");

request.set_url("Handler.ashx");

request.add_completed(//回调函数

function (response) {

if (response.get_responseAvailable()) {//x.status=200

var employee = response.get_object(); //服务器的相应对象;

$("#result").html(String.format("hellow i'am{0},my{1},{2}", employee.FirstName, employee.LastName, employee.Title));

}

});

var requestbody = String.format("firstname={0}&lastname={1}&title={2}", encodeURIComponent(fname), encodeURIComponent(lname), encodeURIComponent(title));

request.set_body(requestbody); //x.send(body参数)

request.invoke(); //x.send方法调用

});

});

</script>

</head>

<body>

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

<asp:ScriptManager ID="ScriptManager1" runat="server">

</asp:ScriptManager>

<div>

firstname:<input type="text" id="first" />

<br/>

lastname:<input type="text" id="last" />

<br/>

title:<input type="text" id="title" />

<br/>

<input id="buttonok" value="serialization" type="button" />

<div id="result">

</div>

</div>

</form>

</body>

</html>

-------------------------------------实用ajax

$.ajax({

type:"POST",

contentType:"application/json;charset=utf-8",

url:"../getuser.asmx/HelloWorld",

dataType: "json",

data: "{}",

success: function (result) { alert(result.d); },

error: function (error) { alert('sdfsdf'); }

});

}

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default5.aspx.cs" Inherits="Default5" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

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

<head runat="server">

<title></title>

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

<script type="text/javascript">

$(function () {

$("#buttonok").click(function () {

var fname = $("#first").val();

var lname = $("#last").val();

var title = $("#title").val();

WebService.getemployee(fname, lname, title, function (employee) {

$("#result").html(String.format("hellow i'am{0},my{1},{2}", employee.FirstName, employee.LastName, employee.Title));

}, null, null);

});

$("#jquery").click(function () {

var fname = $("#first").val();

var lname = $("#last").val();

var title = $("#title").val();

$.ajax({

type: "POST",

contentType: "application/json",

url: "WebService.asmx/getemployee",

data: "{" + String.format("firstname:'{0}',lastname:'{1}',title:'{2}'", fname, lname, title) + "}",

success: function (result) {

var employee = result.d;//系统自定义的d;死记住就ok了;

$("#result").html(String.format("hellow i'am{0},my{1},{2}", employee.FirstName, employee.LastName, employee.Title));

}

});

});

});

</script>

</head>

<body>

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

<asp:ScriptManager ID="ScriptManager1" runat="server">

<Services>

<asp:ServiceReference Path="~/WebService.asmx"/>

</Services>

</asp:ScriptManager>

<div>

firstname:<input type="text" id="first" />

<br/>

lastname:<input type="text" id="last" />

<br/>

title:<input type="text" id="title" />

<br/>

<input id="buttonok" value="serialization" type="button" />

<input id="jquery" value="jferwquery" type="button" />

<div id="result">

sdsd

</div>

</div>

</form>

</body>

</html--------------------------------------反应沉睡时间;

-----iis-----inetmgr:在运行中;IIS

System.Threading.Thread.Sleep(3000);//是让updateprocess沉睡三秒钟在反应;--------

-----------------------规范的ajax

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default5.aspx.cs" Inherits="Default5" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

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

<head runat="server">

<title></title>

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

<script type="text/javascript">

$(function () {

$("#buttonok").click(function () {

var fname = $("#first").val();

var lname = $("#last").val();

var title = $("#title").val();

WebService.getemployee(fname, lname, title, function (employee) {

$("#result").html(String.format("hellow i'am{0},my{1},{2}", employee.FirstName, employee.LastName, employee.Title));

}, null, null);

});

$("#jquery").click(function () {

var fname = $("#first").val();

var lname = $("#last").val();

var title = $("#title").val();

$.ajax({

type: "POST",

contentType: "application/json",

url: "WebService.asmx/getemployee",

data: "{" + String.format("firstname:'{0}',lastname:'{1}',titles:'{2}'", fname, lname, title) + "}",//这种形式字符串则是json;//format内的内容中firstname,lastname是web服务中的参数;这很重要呀?千万别再栽在这里呀;

success: function (result) {

var employee = result.d;//系统自定义的d;死记住就ok了;

$("#result").html(String.format("hellow i'am{0},my{1},{2}", employee.FirstName, employee.LastName, employee.Title));

}

});

});

});

</script>

</head>

<body>

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

<asp:ScriptManager ID="ScriptManager1" runat="server">

<Services>

<asp:ServiceReference Path="~/WebService.asmx"/>

</Services>

</asp:ScriptManager>

<div>

firstname:<input type="text" id="first" />

<br/>

lastname:<input type="text" id="last" />

<br/>

title:<input type="text" id="title" />

<br/>

<input id="buttonok" value="serialization" type="button" />

<input id="jquery" value="jferwquery" type="button" />

<div id="result">

sdsd

</div>

</div>

</form>

</body>

</html>

-------------------------------------------------ajax脚本注册:

protected void Page_Load(object sender, EventArgs e)

{

//声明一个脚本快;

var cs = this.ClientScript;

//声明一个数组;

cs.RegisterArrayDeclaration("arr", "1,2,3");

//添加脚本引用;

cs.RegisterClientScriptInclude("jquery", "Scripts/jquery-1.4.1.min.js");

//添加一个脚本函数;

cs.RegisterClientScriptBlock(this.GetType(), "hellow", "window.onload=function(){ alert(arr.length);};",true);

//为一个控件添加属性;

cs.RegisterExpandoAttribute(this.Button1.ClientID, "myid", "abc");

cs.RegisterClientScriptBlock(this.GetType(), "hellow1", "window.onload=function(){ alert($('#"+this.Button1.ClientID+"').attr('myid'));};", true);

//在页面提交时弹出提示框

cs.RegisterOnSubmitStatement(this.GetType(), "sure", "return confirm('fsdfds');");

//在页面加载时添加提示框;

cs.RegisterStartupScript(this.GetType(),"hellow3","alert('hellow')",true);

}

-------------------------- 错误跳转<customErrors mode="On" redirectMode="ResponseRedirect" defaultRedirect="~/Error.aspx" ></customErrors>

-------------------updatepannel错误提示

scriptmanage中有一个事件

protected void ScriptManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e)

{

this.ScriptManager1.AsyncPostBackErrorMessage= e.Exception.Message;

}

--在页面内添加以下即可;

<script type="text/javascript" language="javascript">

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function (sender, e) {

e.set_errorHandled(true);

alert(e.get_error().message);

//        setTimeout(function () { $get("error").innerHTML=""},3000);

}

);

</script>

-----------------------其它网站调用web服务的引用方法:

namespace ConsoleApplication4

{

class Program

{

static void Main(string[] args)

{

int a = 3, b = 3;

var ws = new ServiceReference1.WebServiceSoapClient();

//当配置选项打对勾时,必须用以下形式(对象)

//var c = ws.add(a, b);

//Console.WriteLine(c.ToString());

Console.WriteLine(ws.add(new ServiceReference1.addRequest(a,b)).addResult.ToString());

}

}

}

----------------winform异步调用web服务

private void button1_Click(object sender, EventArgs e)

{

int a = Convert.ToInt32(textBox1.Text);

int b = Convert.ToInt32(textBox2.Text);

var ws = new ServiceReference1.WebServiceSoapClient("WebServiceSoap");

//ws.add(new ServiceReference1.addRequest(a,b)).addResult.ToString()

//两次tab键即可

ws.addCompleted += new EventHandler<ServiceReference1.addCompletedEventArgs>(ws_addCompleted);

ws.addAsync(new ServiceReference1.addRequest(a,b));

//MessageBox.Show(ws.add(new ServiceReference1.addRequest(a,b)).addResult.ToString());

}

void ws_addCompleted(object sender, ServiceReference1.addCompletedEventArgs e)

{

MessageBox.Show(e.Result.addResult.ToString());

}

}

-------------------javascript:数组:var a=new array(3);若不写3,则表示无限大;a.length表示他的长度;var a=new array(1,2,4);

------------------------membership配置命令:aspnet_regsql

--------------------------发送邮件:

protected void PasswordRecovery1_SendingMail(object sender, MailMessageEventArgs e)

{

e.Message.Body = string.Format

(e.Message.Body, this.PasswordRecovery1.UserName,

Membership.GetUser(this.PasswordRecovery1.UserName).GetPassword(this.PasswordRecovery1.Answer),

DateTime.Now

);

//e.Cancel = true;

this.Literal1.Text = e.Message.Body;

e.Cancel = true;

}

-----------------------------webconfig:

<?xml version="1.0"?>

<!--

有关如何配置 ASP.NET 应用程序的详细信息,请访问

http://go.microsoft.com/fwlink/?LinkId=169433

-->

<configuration>

<connectionStrings>

<clear/>

<add name="connection" connectionString="data source=.;initial catalog=Membership;uid=sa;pwd=sa"

providerName="System.Data.SqlClient"></add>

</connectionStrings>

<system.web>

<!--<machineKey decryptionKey=""/>-->

<authentication mode="Forms">

<forms defaultUrl="~/Default.aspx" loginUrl="~/Accounts/Login.aspx" name="being"><!--设置cookie-->

<!--<credentials passwordFormat="Clear">

<user name="a" password="a"/>

<user name="b" password="b"/>

</credentials>-->

</forms>

</authentication>

<authorization>

<!--<deny users="?"/>-->

</authorization>

<membership defaultProvider="net">

<providers>

<clear/>

<add name="net" type="System.Web.Security.SqlMembershipProvider" connectionStringName="connection" enablePasswordRetrieval="true"

enablePasswordReset="true" requiresQuestionAndAnswer="false" passwordFormat="Clear"

requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="1" minRequiredNonalphanumericCharacters="0"

passwordAttemptWindow="10" applicationName="/"/>

</providers>

</membership>

<compilation debug="false" targetFramework="4.0" />

<roleManager enabled="true" defaultProvider="sd">

<providers>

<clear/>

<add name="sd" type="System.Web.Security.SqlRoleprovider"

connectionStringName="connection"  applicationName="/"  />

</providers>

</roleManager>

</system.web>

<system.net>

<mailSettings >

<smtp from="guozfeng@qq.com">

<network host="smtp.gmail.com" port="8090" userName ="zhang@qq.com" password="hellow"/>

</smtp>

</mailSettings>

</system.net>

</configuration>

----------------创建角色:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

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

{

protected void Page_Load(object sender, EventArgs e)

{

}

protected void Button1_Click(object sender, EventArgs e)

{

if(  !System.Web.Security.Roles.RoleExists("经理"))

System.Web.Security.Roles.CreateRole("经理");

if (!System.Web.Security.Roles.IsUserInRole("a", "经理"))

{

System.Web.Security.Roles.AddUserToRole("a", "经理");

}

}

protected void Button2_Click(object sender, EventArgs e)

{

var roles = System.Web.Security.Roles.GetRolesForUser("a");

foreach (var item in roles)

{

this.Label1.Text += item;

}

}

}

---------------------添加删除用户

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.Security;

using System.Web.UI.WebControls;

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

{

protected void Page_Load(object sender, EventArgs e)

{

}

protected void Button1_Click(object sender, EventArgs e)

{

MembershipUser user = Membership.CreateUser(this.TextBox1.Text, this.TextBox2.Text);

this.Literal1.Text = user.UserName + user.ProviderUserKey.ToString();

}

protected void Button2_Click(object sender, EventArgs e)

{

GridView1.DataSource = Membership.GetAllUsers();

GridView1.DataBind();

}

protected void Button3_Click(object sender, EventArgs e)

{

this.Literal1.Text = Membership.ValidateUser(this.TextBox1.Text, this.TextBox2.Text).ToString();

if(this.Literal1.Text=="True")

FormsAuthentication.SetAuthCookie(this.TextBox1.Text,true);//设置cookie;(名字为being)

}

protected void Button4_Click(object sender, EventArgs e)

{

if (this.User.Identity.IsAuthenticated)

{

this.Label1.Text = this.User.Identity.Name;

}

//if (Membership.GetUser() != null)

//{

//    this.Label1.Text = Membership.GetUser().ToString();

//}

}

protected void Button5_Click(object sender, EventArgs e)

{

//删除验证的kooies;

FormsAuthentication.SignOut();

}

}

----------------------------------------webconfig权限:

文件夹内部:

<?xml version="1.0"?>

<configuration>

<system.web>

<authorization>

<deny users="?"/>

<allow roles="管理员"/>

<deny users="*"/>

</authorization>

</system.web>

<location path="员工.aspx">

<system.web>

<authorization>

<allow users="*"/>

</authorization>

</system.web>

</location>

</configuration>

----------------------站点地图:

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

<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >

<siteMapNode title="本人的网站" roles="*">

<siteMapNode  title="主页"  description="返回主页" roles="经理" >

<siteMapNode url="~/About.aspx" title="帮助"  description="帮助" />

</siteMapNode>

<siteMapNode  title="密码服务@"  description="帮助" roles="*" >

<siteMapNode url="~/Account/Register.aspx" title="密码服务1"  description="帮助" roles="管理员" />

<siteMapNode url="~/Account/Login.aspx" title="密码服务2"  description="帮助" roles="经理" />

<siteMapNode url="~/Account/ChangePassword.aspx" title="密码服务3"  description="帮助" roles="员工" />

<siteMapNode url="~/hj/管理员.aspx" title="密码服务4"  description="帮助"/>

<siteMapNode url="~/hj/员工.aspx" title="密码服务5"  description="帮助"/>

</siteMapNode>

</siteMapNode>

</siteMap>

------------------------------------较为完整的web.config

<?xml version="1.0"?>

<!--

有关如何配置 ASP.NET 应用程序的详细信息,请访问

http://go.microsoft.com/fwlink/?LinkId=169433

-->

<configuration>

<connectionStrings>

<clear/>

<add name="connection" connectionString="data source=.;initial catalog=Membership;uid=sa;pwd=sa"

providerName="System.Data.SqlClient"></add>

</connectionStrings>

<system.web>

<compilation debug="false" targetFramework="4.0" />

<authentication mode="Forms">

<forms loginUrl="~/Account/Login.aspx" timeout="2880" />

</authentication>

<membership>

<providers>

<clear/>

<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="connection"

enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"

maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"

applicationName="/" />

</providers>

</membership>

<profile enabled="true" defaultProvider="AspNetSqlProfileProvider" automaticSaveEnabled="true">

<providers>

<clear/>

<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="connection" applicationName="/"/>

</providers>

<properties>

<clear/>

<add name="shopcart" type="gouwu" serializeAs="Xml" allowAnonymous="true" />

<add name="Age" type="System.Int32" defaultValue="18"/>

<add name ="Nick"/>

<group name="Tel">

<add name="Mobile"/>

<add name="hometel"/>

</group>

</properties>

</profile>

<roleManager enabled="true">

<providers>

<clear />

<add connectionStringName="connection" applicationName="/" name="AspNetSqlRoleProvider"

type="System.Web.Security.SqlRoleProvider" />

</providers>

</roleManager>

<siteMap>

<providers>

<clear/>

<!--name="AspNetXmlSiteMapProvider",必须有这个名字-->

<add siteMapFile="Web2.sitemap" name="AspNetXmlSiteMapProvider" type="System.Web.XmlSiteMapProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>

<add siteMapFile="Web.sitemap" name="a2" type="System.Web.XmlSiteMapProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" securityTrimmingEnabled="true"/>

</providers>

</siteMap>

<anonymousIdentification enabled="true"/>

</system.web>

<system.net>

<mailSettings >

<smtp from="guozfeng@qq.com">

<network host="smtp.gmail.com" port="8090" userName ="zhang@qq.com" password="hellow"/>

</smtp>

</mailSettings>

</system.net>

<system.webServer>

<modules runAllManagedModulesForAllRequests="true"/>

</system.webServer>

</configuration>

----------------------------------------profile购物车:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

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

{

protected void Page_Load(object sender, EventArgs e)

{

}

protected void Button1_Click(object sender, EventArgs e)

{

gouwu cart = this.Profile.shopcart;

if (cart == null)

{

cart = new gouwu();

}

var id =int.Parse( this.TextBox1.Text);

var existcar = cart.shopcar.FindByproid(id);

if (existcar == null)

{

cart.shopcar.AddshopcarRow(id

, this.TextBox2.Text, double.Parse(this.TextBox3.Text

), int.Parse(this.TextBox4.Text));

}

else

{

existcar.amount += int.Parse(this.TextBox4.Text);

}

this.Profile.shopcart = cart;//更新

this.Profile.Save();

this.Literal1.Text = "ok";

}

protected void Button2_Click(object sender, EventArgs e)

{

Response.Redirect("jiesuan.aspx");

}

}

结算界面:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

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

{

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

gouwu cart = this.Profile.shopcart;

if (cart != null && cart.shopcar.Count > 0)

{

this.GridView1.DataSource = cart.shopcar;

this.GridView1.DataBind();

}

}

}

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)

{

}

protected void Button1_Click(object sender, EventArgs e)

{

//System.Web.Security.AnonymousIdentificationModule.ClearAnonymousIdentifier();

//删除匿名标示;但是必须先登录在清理匿名用户;

this.Literal1.Text= System.Web.Profile.ProfileManager.DeleteInactiveProfiles(System.Web.Profile.ProfileAuthenticationOption.Anonymous, DateTime.Now).ToString();

}

protected void Button2_Click(object sender, EventArgs e)

{

//此是删除当前匿名用户信息

System.Web.Profile.ProfileManager.DeleteProfile(Request.AnonymousID);

////此是删除所有匿名用户信息;

//System.Web.Security.Membership.DeleteUser(Request.AnonymousID);

}

}

--------------------------------------------编程成员资格:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.Security;

using System.Web.UI.WebControls;

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

{

protected void Page_Load(object sender, EventArgs e)

{

}

protected void Button1_Click(object sender, EventArgs e)

{

MembershipUser user = Membership.CreateUser(this.TextBox1.Text, this.TextBox2.Text);

this.Literal1.Text = user.UserName + user.ProviderUserKey.ToString();

}

protected void Button2_Click(object sender, EventArgs e)

{

GridView1.DataSource = Membership.GetAllUsers();

GridView1.DataBind();

}

protected void Button3_Click(object sender, EventArgs e)

{

this.Literal1.Text = Membership.ValidateUser(this.TextBox1.Text, this.TextBox2.Text).ToString();

if(this.Literal1.Text=="True")

FormsAuthentication.SetAuthCookie(this.TextBox1.Text,true);//设置cookie;(名字为being)

}

protected void Button4_Click(object sender, EventArgs e)

{

if (this.User.Identity.IsAuthenticated)

{

this.Label1.Text = this.User.Identity.Name;

}

//if (Membership.GetUser() != null)

//{

//    this.Label1.Text = Membership.GetUser().ToString();

//}这个if不好使

}

protected void Button5_Click(object sender, EventArgs e)

{

//删除验证的kooies;

FormsAuthentication.SignOut();

}

}

--------------------文件上传的大小控制:

<httpRuntime maxRequestLength="1024"/>

---------------------------取config信息:

var a = WebConfigurationManager.ConnectionStrings[""].ToString();

var b=WebConfigurationManager.AppSettings[""].ToString();

-------------------------------ajax调用web服务

$.ajax({

type: "POST",

contentType: "application/json",

url: "WebService.asmx/register",

data: "{usersname:'" + name + "',pwd:'" + pwd + "'}",

dataType: 'json',

success: function (result) {

var r = eval("("+result.d+")");

if (r.code == 0) {

show2(name,pwd);

}

else {

$.messager.alert('I LOVE YOU', '注册失败'+r.message, 'warning');

}

}

});

return true;

}

}

--------------------------------print newid()

------------------------------reperater的用法

<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">

<ItemTemplate>

<li class="cat-item cat-item-4"><a href='<%# "日志分类.aspx?id="+ Eval("catagoryid") %>' runat="server"><%# Eval("name") %> </a></li>

</ItemTemplate>

</asp:Repeater>

-------------------------------------后台代码来控制前台代码的语法:

<%if (this.xianshi)//xianshi 是在后台中的属性

{ %>

<span class="permalink"><a href='<%# "~/Edite.aspx?blogid="+Eval("blogid") %>' runat="server">编辑</a>

<a href="#">删除</a></span>

<%} %>

}

------------------  $.ajax(

{

type: "post",

contentType: "application/json",

url: "WebService.asmx/newcomment", //若为两级目录../WebService.ascx/newblog

data: "{title:'" + title + "',comment:'" + content + "',blogid:'" + blogid + "',username:'" + usename + "',pwd:'" + pwd + "',type:" + type + "}",

dataType: 'json',

success: function (result) {

if (result.d != "a") {

alert(result.d);

}

else {

$.messager.alert('I LOVE YOU', '发表成功', 'warning');

window.location.reload();

}

}

}

);

});

------------------------------------------javascript为服务器端控件赋值--经典

$("#<%=DropDownList1.ClientID %>").val(blog.categoryid);

window.top.location.href = "fabiao.aspx";

---------------------------获取存储过程的返回值return:

command.Parameters.Add(

new SqlParameter("ReturnValue", SqlDbType.Int, 4,

ParameterDirection.ReturnValue, false, 0, 0,

string.Empty, DataRowVersion.Default, null));

command.ExecuteNonQuery();

conn.Close();

return (int)command.Parameters["ReturnValue"].Value;

-----------------------------------接收输出值

SQLHelper helper = new SQLHelper();

SqlParameter[] prams = {

new SqlParameter("@receiveBillperson",SqlDbType.VarChar,50),

new SqlParameter("@billType", SqlDbType.VarChar,50),

new SqlParameter("@pageIndex", SqlDbType.Int, 4),

new SqlParameter("@pageSize", SqlDbType.Int, 4),

new SqlParameter("@recordCount", SqlDbType.Int, 4)

};

prams[0].Value = receiveBillperson;

prams[1].Value = billType;

prams[2].Value = pageIndex;

prams[3].Value = pageSize;

prams[4].Direction = ParameterDirection.Output;

DataSet ds = helper.ExecuteDataSet("uspGetBillDispenses", prams);

recordCount = int.Parse(prams[4].Value.ToString());

return ds;

------------------------------读取sqldatareader内的值:

if (dr.Read())

{

db.BillType = dr["BillType"].ToString();

db.BillStartCode = dr["BillStartCode"].ToString();

db.BillEndCode = dr["BillEndCode"].ToString();

db.ReceiveBillPerson = dr["ReceiveBillPerson"].ToString();

db.AcceptStation = dr["AcceptStation"].ToString();

db.ReceiveBillTime =Convert.ToDateTime(dr["ReceiveBillTime"].ToString());

db.ReleasePerson = dr["ReleasePerson"].ToString();

}

-----------------------

prams[3].Value = Convert.ToDateTime(beginWriteDate).ToShortDateString();

prams[4].Value =Convert.ToDateTime(endWriteDate).ToShortDateString();

------------------------------现存的存储过程中的语法一begin-end

BEGIN

BEGIN TRY

INSERT Account_Users

(

LoginID,

Username,

[Password],

Sex,

Birthday

)

VALUES

(

@loginID,

@userName,

'1234',

@sex,

@birthday

)

RETURN 0

END TRY

BEGIN CATCH

RETURN ERROR_NUMBER()

END CATCH

END

--------------------------------------------存储过程函数规则表达:

ALTER FUNCTION [dbo].[funGenerateBillCode](@billType NVARCHAR(50) ,@billCode NVARCHAR(50),@receiveBillTime datetime)

RETURNS CHAR(11)

AS

BEGIN

DECLARE @e NVARCHAR(50)

DECLARE @a int

DECLARE @b int

DECLARE @c NVARCHAR(50)

IF @billType='货运单'

SET @e='C'

ELSE

SET @e='R'

SELECT @a=DATEPART(YEAR,@receiveBillTime)

SELECT @b=DATEPART(MONTH,@receiveBillTime)

SET @c=CONVERT(NVARCHAR(50),@a*100+@b)

SET @e=@e+@c+@billCode

RETURN @e

END

-----------------------------------------游标示例

ALTER PROCEDURE [dbo].[uspExistBillDispense]

(

@billCode   VARCHAR(50),       ---票据开始号或票据结束号

@billType   VARCHAR(50),       ---票据类型

@receiveBillTime DATETIME      ---领票时间

)

AS

BEGIN

DECLARE @vBillCode VARCHAR(50)

DECLARE @billStartCode VARCHAR(50)

DECLARE @billEndCode VARCHAR(50)

DECLARE cursorBillDispense CURSOR FOR SELECT BillStartCode,BillEndCode FROM BillMgt_BillDispense  WHERE BillType=@billType

SET @vBillCode=[dbo].[funGenerateBillCode](@billType,@billCode,@receiveBillTime)

OPEN cursorBillDispense

WHILE @@FETCH_STATUS=0

BEGIN

FETCH NEXT FROM cursorBillDispense INTO  @billStartCode,@billEndCode

IF @vBillCode>=@billStartCode AND @vBillCode<=@billEndCode

RETURN 1

END

RETURN 0

END

---------------------------------------数据库分页示例

/*********************************************************************************

*过程名称 : uspGetBillDetails

*功能描述 : 获取多条票据明细信息

*输入参数 :

@billCode         VARCHAR(50),      --领票编号

@billType         VARCHAR(50),      --票据类型

@billStatus       VARCHAR(50),      --票据状体

@beginWriteDate   DATETIME,         --开始填写日期

@endWriteDate     DATETIME,         --结束填写日期

@pageSize         INT,              --每页显示的索引号

@pageIndex        INT               --每页显示的记录数

*输出参数 :

@recoreCount      INT OUTPUT        --总记录数

*返 回 值 :

*结果集:

BillType             --票据类型

BillCode             --票据编号

Billstate            --票据状态

WriteDate            --填写日期

AcceptStation        --接货点

*作    者 : 郭泽峰

*创建日期 : 2011-12-28

***********************************************************************************/

ALTER PROCEDURE [dbo].[uspGetBillDetails]

(

@billCode         VARCHAR(50),      --领票编号

@billType         VARCHAR(50),      --票据类型

@billStatus       VARCHAR(50),      --票据状体

@beginWriteDate   DATETIME,         --开始填写日期

@endWriteDate     DATETIME,         --结束填写日期

@pageSize         INT,              --每页显示的索引号

@pageIndex        INT,               --每页显示的记录数

@recordCount      INT OUTPUT        --总记录数

)

AS

BEGIN

declare @a char(20)

declare @b char(20)

set @a=@beginWriteDate

set @b=@endWriteDate

DECLARE @sqlRC    NVARCHAR(4000)    --RecordCount SQL

DECLARE @sqlRS    NVARCHAR(4000)    --ResultSet       SQL

SET @sqlRC =

'SELECT @recordCount = Count(*)

FROM BillMgt_BillDetail

WHERE BillCode LIKE ''%'' + REPLACE(''' + @billCode + ''', ''%'', ''/%'') + ''%'' ESCAPE ''/'''

IF @billType <> '全部'

BEGIN

SET @sqlRC =

@sqlRC + ' AND BillType ='''+@billType+''''

END

IF @billStatus <> '全部'

BEGIN

SET @sqlRC =

@sqlRC + ' AND BillState ='''+@billStatus+''''

END

IF @a <>''

BEGIN

SET @sqlRC =

@sqlRC + ' AND WriteDate >='''+@a+''''

END

IF @b <>''

BEGIN

SET @sqlRC =

@sqlRC + ' AND WriteDate <='''+@b+''''

END

EXEC sp_executesql @sqlRC, N'@recordCount INT OUTPUT', @recordCount OUTPUT

SET @sqlRS =

'SELECT PKID,

BillType,

BillCode,

BillState,

WriteDate,

AcceptStation

FROM

(

SELECT PKID,

BillType,

BillCode,

BillState,

WriteDate,

AcceptStation,

ROW_NUMBER() OVER (ORDER BY PKID ) AS SerialNumber

FROM BillMgt_BillDetail

WHERE BillCode LIKE ''%'' + REPLACE(''' + @billCode + ''', ''%'', ''/%'') + ''%'' ESCAPE ''/'''

IF @billType <> '全部'

BEGIN

SET @sqlRS =

@sqlRS + ' AND BillType ='''+@billType+''''

END

IF @billStatus <> '全部'

BEGIN

SET @sqlRS =

@sqlRS + ' AND BillState ='''+@billStatus+''''

END

IF @a <>''

BEGIN

SET @sqlRS =

@sqlRS + ' AND WriteDate >='''+@a+''''

END

IF @b<>''

BEGIN

SET @sqlRS =

@sqlRS + ' AND WriteDate <='''+@b+''''

END

SET @sqlRS =

@sqlRS +

') AS T

WHERE T.SerialNumber > ' + CONVERT(NVARCHAR(100), (@pageIndex - 1) * @pageSize) +

' AND T.SerialNumber <= ' + CONVERT(NVARCHAR(100), @pageIndex * @PageSize)

EXEC (@sqlRS)

END

------------------------快捷反射

string path = EXPConfiguration.DataAccess;

string className = path + ".Bill.BillSQLHandle";

return (Billnterface)Assembly.Load(path).CreateInstance(className);

------------查找类的路径:

var path=System.Web.HttpContext.Current.Setver.MapPath("~/wenjian");

-----------------------设置动态时间:

function showtime(){

var now=new Date();

var year=now.getFullYear();

var month=now.getMonth()+1;

var day=now.getDate();

var hours=now.getHours();

var minutes=now.getMinutes();

var seconds=now.getSeconds();

time=year+'/'+month+'/'+day +'/'+hours+':'+minutes+':'+seconds;

var div1=document.getElementById('div1');

div1.innerHTML=time;

}

function letstart(){

taskId=setInterval(showtime,500);

-------------

}

-----------------------------获取configuration规范方法;

using System.Configuration;

public static string str

{

get

{

string str = ConfigurationSettings.AppSettings["Connetion"];

return str;

}

}

------------------------------更改gridview列数值();

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

{

if (e.Row.RowType == DataControlRowType.DataRow)

{

switch (e.Row.Cells[2].Text.Trim())

{

case "0":

e.Row.Cells[2].Text = "考勤正常";

break;

case "1":

e.Row.Cells[2].Text = "上班迟到";

break;

}

switch (e.Row.Cells[4].Text.Trim())

{

case "0":

e.Row.Cells[4].Text = "考勤正常";

break;

case "1":

e.Row.Cells[4].Text = "下班迟到";

break;

}

DateTime a = Convert.ToDateTime(e.Row.Cells[0].Text);

e.Row.Cells[0].Text = a.Date.ToShortDateString();

DateTime b = Convert.ToDateTime(e.Row.Cells[1].Text);

e.Row.Cells[1].Text = b.Date.ToShortTimeString();

DateTime c = Convert.ToDateTime(e.Row.Cells[3].Text);

e.Row.Cells[3].Text = c.Date.ToShortTimeString();

}

}

--------------------scriptmanager中出错;加scriptMode=release;

<asp:ScriptManager ID="ScriptManager1" runat="server" ScriptMode="Release">

</asp:ScriptManager>

---------------------------button按钮提示:

var cs = this.ClientScript;

cs.RegisterOnSubmitStatement(this.GetType(), "tishi", "return confirm('请填写起始日期和结束日期')");

-----------------------------linkbutton传值:

<asp:LinkButton ID="Label1" runat="server" Text='<%# Bind("Name") %>' PostBackUrl='<%# Eval("UserStaffId", "~/attendence/AttendanceSearch.aspx?ids={0}") %>'></asp:LinkButton></span>

---------------------

//计算本周起始时间

switch(DateTime.Now.DayOfWeek)

{

case DayOfWeek.Monday: spanDays = 0;

break;

case DayOfWeek.Tuesday: spanDays = 1;

break;

case DayOfWeek.Wednesday: spanDays = 2;

break;

case DayOfWeek.Thursday: spanDays = 3;

break;

case DayOfWeek.Friday: spanDays = 4;

break;

case DayOfWeek.Saturday: spanDays = 5;

break;

case DayOfWeek.Sunday: spanDays = 6;

break;

}

DateTime start = DateTime.Today.AddDays(-spanDays);

DateTime startTime3 = DateTime.Today.AddDays(-DateTime.Today.Day + 1);//本月起始时间

--------------------sql循环插入一个月日期:

declare @date datetime

set @date='2009-9-1'

while @date<'2009-10-1'

begin

insert into tb(col) values(@date)

set @date=dateadd(day,1,@date)

end

-----------------------------将库中的日期显示在calendar上

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Data;

using System.Configuration;

using System.Data.SqlClient;

using System.Web.UI.WebControls;

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

{

protected DataSet dsHolidays;

protected void Page_Load(object sender, EventArgs e)

{

if (IsPostBack)

{

Calendar1.VisibleDate = DateTime.Today;

FillHolidayDataset();

}

}

protected void FillHolidayDataset()

{

DateTime firstDate = new DateTime(Calendar1.VisibleDate.Year,

Calendar1.VisibleDate.Month, 1);

DateTime lastDate = GetFirstDayOfNextMonth();

dsHolidays = GetCurrentMonthData(firstDate, lastDate);

}

protected DateTime GetFirstDayOfNextMonth()

{

int monthNumber, yearNumber;

if (Calendar1.VisibleDate.Month == 12)

{

monthNumber = 1;

yearNumber = Calendar1.VisibleDate.Year + 1;

}

else

{

monthNumber = Calendar1.VisibleDate.Month + 1;

yearNumber = Calendar1.VisibleDate.Year;

}

DateTime lastDate = new DateTime(yearNumber, monthNumber, 1);

return lastDate;

}

protected DataSet GetCurrentMonthData(DateTime firstDate, DateTime lastDate)

{

DataSet dsMonth = new DataSet();

ConnectionStringSettings cs;

cs = ConfigurationManager.ConnectionStrings["myconnection"];

String connString = cs.ConnectionString;

SqlConnection dbConnection = new SqlConnection(connString);

String query;

query = "SELECT CalendarDate FROM AttendenceWorkingDate " + " WHERE CalendarDate >= @firstDate AND CalendarDate < @lastDate and IsWorkingDay=1";

SqlCommand dbCommand = new SqlCommand(query, dbConnection);

dbCommand.Parameters.Add(new SqlParameter("@firstDate", firstDate));

dbCommand.Parameters.Add(new SqlParameter("@lastDate", lastDate));

SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(dbCommand);

try

{

sqlDataAdapter.Fill(dsMonth);

}

catch { }

return dsMonth;

}

protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)

{

DateTime nextDate;

if (dsHolidays != null)

{

foreach (DataRow dr in dsHolidays.Tables[0].Rows)

{

nextDate = (DateTime)dr["CalendarDate"];

if (nextDate == e.Day.Date)

{

e.Cell.BackColor = System.Drawing.Color.Pink;

e.Cell.Controls.Add(new Literal() { Text="已设考勤日"});

}

}

}

}

protected void Calendar1_VisibleMonthChanged(object sender, MonthChangedEventArgs e)

{

FillHolidayDataset();

}

protected void Calendar1_SelectionChanged(object sender, EventArgs e)

{

Label1.Text=this.Calendar1.SelectedDate.ToString();

}

}

-----------------------日历扩展程序

<cc2:CalendarExtender ID="TextBox1_CalendarExtender" runat="server"

Enabled="True" FirstDayOfWeek="Monday" Format="yyyy-MM-dd"

TargetControlID="TextBox1">

---------------------html时间函数

<script type="text/javascript">

setInterval(function () {

var a = new Date();

var b = a.getHours();

var c = a.getMinutes();

var d = a.getSeconds();

document.getElementById("time").innerHTML = b + ":" + c + ":" +d;

}, 500)

//        })

</script>

-------------------------------界面转向“

window.location.href("Default.aspx?uid="+result.d+"");

----------------------- Response.Redirect("~/attendence/myattendence.aspx");

-----------------时间的比较convert.todatetime(datetiime.now.toshorttimestring())

DateTime.Compare(now,oon)>0

--------------------------------

$(function () {

$("#Text3").mouseover(function () {

$("#Text3").focus();

$("#Text3").select();

});

$("#Text4").mouseover(function () {

$("#Text4").focus();

$("#Text4").select();

});

})

----------------------------获取服务器端控件:

、 $("[id$=yingpian]").mouseover(

<div id="menu-demo" class="session">

<div id="menu" >

<a href="javascript:void(0);"><img src="MovieImg/070625155324000.jpg" title="胡单身公" /></a>

<a href="javascript:void(0);"><img src="MovieImg/1054928.jpg" title="Animals"/></a>

<a href="javascript:void(0);"><img src="MovieImg/13069068623501961.jpg" title="动物大家庭" /></a>

<a href="javascript:void(0);"><img src="MovieImg/130690686268821043.jpg" title="幸福天地"/></a>

<a href="javascript:void(0);"><img src="MovieImg/070625155324000.jpg" title="因为爱" /></a>

<a href="javascript:void(0);"><img src="MovieImg/070625155324000.jpg" title="一走了之" /></a>

</div>

</div>

--------------------------:数字验证:

$("#zhuuser").keydown(function () {

$("#zhuuser").val(this.value.replace(/[^\d]/g, ''));

});

----------------------更改用户信息

<%@ Page Language="C#" %>

<%@ Import Namespace="System.Web.Security" %>

<script runat="server">

MembershipUser u;

public void Page_Load(object sender, EventArgs args)

{

u = Membership.GetUser(User.Identity.Name);

if (!IsPostBack)

{

EmailTextBox.Text = u.Email;

}

}

public void UpdateEmailButton_OnClick(object sender, EventArgs args)

{

try

{

u.Email = EmailTextBox.Text;

Membership.UpdateUser(u);

Msg.Text = "User e-mail updated.";

}

catch (System.Configuration.Provider.ProviderException e)

{

Msg.Text = e.Message;

}

}

</script>

<html>

<head>

<title>Sample: Update User E-Mail</title>

</head>

<body>

<form runat="server">

<h3>Update E-Mail Address for <%=User.Identity.Name%></h3>

<asp:Label id="Msg" ForeColor="maroon" runat="server" /><BR>

<table CellPadding="3" border="0">

<tr>

<td>E-mail Address:</td>

<td><asp:TextBox id="EmailTextBox" MaxLength="128" Columns="30" runat="server" /></td>

<td><asp:RequiredFieldValidator id="EmailRequiredValidator" runat="server" ControlToValidate="EmailTextBox" ForeColor="red" Display="Static" ErrorMessage="Required" /></td>

</tr>

<tr>

<td></td>

<td><asp:Button id="UpdateEmailButton" Text="Update E-mail" OnClick="UpdateEmailButton_OnClick" runat="server" /></td>

</tr>

</table>

</form>

</body>

</html>

相关资料:

使用 membership 来进行角色与权限管理

作者:99love(w3see.cn) 时间:2007-04-27 来源:蓝色理想

全文阅读:http://www.blueidea.com/tech/program/2007/4676.asp

1、membership简介

2、membership在sql server中的设置

3、配置web.config

4、创建用户CreateUserWizard控件

5、用户登录login控件

6、显示当前用户的名称LoginName控件

7、检测用户的身份验证状态的LoginStatus控件

8、为不同类别用户呈现不同内容的LoginView控件

9、更改密码的ChangePassword控件

10、自助找回密码的PasswordRecovery控件

11、总结

-------------------------后台提示框

this.Page.RegisterStartupScript( "alert ", " <script> alert('添加成功') </script> ");

-----------------------

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)

{

//bool result = bus.userinfodelebyid( new Guid(e.Keys.Values.ToString()));

Label8.Text = GridView1.DataKeys[e.RowIndex].Value.ToString();

}

------------------

在 GridView1_RowCommand中获取主键的值:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)

{

int OrderId = Convert.ToInt32(GridView1.DataKeys[Convert.ToInt32(e.CommandArgument)].Value); }

在 GridView1_PageIndexChanging中获取主键的值

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)

{

int index=GridView1.DataKeys[e.NewPageIndex].Value;

}

在 GridView1_RowDeleting中获取主键的值

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)

{

int index=GridView1.DataKeys[e.RowIndex].Value;

}

在 GridView1_RowEditing中获取主键的值

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)

{

int index = GridView1.DataKeys[e.NewEditIndex].Value;

}

在 GridView1_RowUpdating中获取主键的值

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

{

int index = GridView1.DataKeys[e.RowIndex].Value;

}

在 GridView1_RowDataBound中获取主键的值

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

{

int index = GridView1.DataKeys[e.Row.RowIndex].Value;

}

通常情况下,ASP.Net 页面 PostBack(回发)后,页面一般定位在整个网页的顶部!但我们在实际项目中经常需要,回发后能定位到自己刚刚点击提交按钮位置,那这种情况如何实现呢,下面介绍三种实现些功能的方法

一、应用程序级设置:在web.config中增加一个pages节点

<pages maintainScrollPositionOnPostBack="true">

二、页面级设置:在aspx页面上进行设置,在页面的page指令中增加属性

<@page MaintainScrollPositionOnPostback="true"

三、在后台cs代码中设置

-----------------获取当前用户名:

HttpContext.Current.User.Identity.Name.ToString();

-----------------------------前台截取字符串

<img src='<%# Eval("Address").ToString().Substring(2) %>' title='<%# Eval("name") %>' /></a>

<%#Convert.ToString(Eval( "title ")).SubString(0,20)   %>

////////////////日志写入

public static void Log(string message)

{

string fileName = System.Web.HttpContext.Current.Server.MapPath(EXPConfiguration.Log);

if(File.Exists(fileName))

{

StreamWriter sr = File.AppendText(fileName);

sr.WriteLine ("\n");

sr.WriteLine (DateTime.Now.ToString()+message);

sr.Close();

}

else

{

StreamWriter sr = File.CreateText(fileName);

sr.Close();

Log(message);

}

////////////////数据库取日期部分

获取SQL字符串中日期部分的语句 数据库Sql,VFP,Access

作者:数据库Sql,VFP,Access 浏览:386次 评论:0条

  在SQL中,日期类型DateTime的默认格式就是yyyy-mm-dd hh:mi:ss: mmm,仍然大多数情况下我们只想得到它的日期部分,而不要后面的时间部分。

  那么如何取得不包含时间的日期呢?比如要获取日期时间:2010-9-2 11:34:52中的2010-9-2,可使用如下方法。

  只需要使用Convert()函数就足够了,下面是方法,希望对您有所帮助。

  select convert(char(10),GetDate(),120) as Date

  参数中的第3个参数就是用来设置日期类型数据的显示样式的,下面介绍几种样式的参数:

  100:mm dd yyyy

  101:mm/dd/yyyy

  102:yyyy.mm.dd

  103:dd/mm/yyyy

  106:dd mm yyyy

  108:hh:mi:ss(时间)

  111:yyyy/mm/dd

  112:yyyymmdd

  120:yyyy-mm-dd

  现在,我们应该明白了,用这种方法获得日期部分将会更加方便,与这种方法比较Datename()函数的好处就是在于得到日期的具体部分。

  知识扩展:

  比如,您想获取SQL数据库字段中的日期,可以这样来获取:

  假如,SQL某数据表中有一个字段的名称是:MyDateTime

  那么,我们就这样来获取:

  select convert(char(10),MyDateTime,120) as MyDate from MyTable

  当然,如何要想获取当天日期之前的数据,而不需要当前日期之后的数据,可以这样来获取:

  select id,Aritle,convert(char(10),MyDateTime,120) as MyDate,FORMAT(Now(),'YYYY-MM-DD') as MyNowDate from MyTable where MyDate<=MyNowDate

  这样,上述的语句功能,返回的是日期小于等于今天的记录;如果日期大于今天的记录,将不返回。

爱盲互联 www.amhl.net

/////////////div随下拉滚动条而滚动

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default7.aspx.cs" Inherits="Default7" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

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

<head runat="server">

<title></title>

</head>

<style>

<!--

.div{

position: absolute;

border: 2px solid red;

background-color: #EFEFEF;

line-height:90px;

font-size:12px;

z-index:1000;

}

-->

</style>

<BODY>

<div id="Javascript.Div1" class="div" style="width: 240px; height:90px" align="center">正中...</div>

<SCRIPT LANGUAGE="JavaScript">

function sc1() {

document.getElementById("Javascript.Div1").style.top = (document.documentElement.scrollTop + (document.documentElement.clientHeight - document.getElementById("Javascript.Div1").offsetHeight) / 2) + "px";

document.getElementById("Javascript.Div1").style.left = (document.documentElement.scrollLeft + (document.documentElement.clientWidth - document.getElementById("Javascript.Div1").offsetWidth) / 2) + "px";

}

</SCRIPT>

<div id="Javascript.Div2" class="div" style="width: 240px; height:90px" align="center">左上...</div>

<SCRIPT LANGUAGE="JavaScript">

function sc2() {

document.getElementById("Javascript.Div2").style.top = (document.documentElement.scrollTop) + "px";

document.getElementById("Javascript.Div2").style.left = (document.documentElement.scrollLeft) + "px";

}

</SCRIPT>

<div id="Javascript.Div3" class="div" style="width: 240px; height:90px" align="center">左下...</div>

<SCRIPT LANGUAGE="JavaScript">

function sc3() {

document.getElementById("Javascript.Div3").style.top = (document.documentElement.scrollTop + document.documentElement.clientHeight - document.getElementById("Javascript.Div3").offsetHeight) + "px";

document.getElementById("Javascript.Div3").style.left = (document.documentElement.scrollLeft) + "px";

}

</SCRIPT>

<div id="Javascript.Div4" class="div" style="width: 240px; height:90px" align="center">右上...</div>

<SCRIPT LANGUAGE="JavaScript">

function sc4() {

document.getElementById("Javascript.Div4").style.top = (document.documentElement.scrollTop) + "px";

document.getElementById("Javascript.Div4").style.left = (document.documentElement.scrollLeft + document.documentElement.clientWidth - document.getElementById("Javascript.Div4").offsetWidth) + "px";

}

</SCRIPT>

<div id="Javascript.Div5" class="div" style="width: 240px; height:90px" align="center">右下...</div>

<SCRIPT LANGUAGE="JavaScript">

function sc5() {

document.getElementById("Javascript.Div5").style.top = (document.documentElement.scrollTop + document.documentElement.clientHeight - document.getElementById("Javascript.Div5").offsetHeight) + "px";

document.getElementById("Javascript.Div5").style.left = (document.documentElement.scrollLeft + document.documentElement.clientWidth - document.getElementById("Javascript.Div5").offsetWidth) + "px";

}

</SCRIPT>

<SCRIPT LANGUAGE="JavaScript">

<!--

function scall() {

sc1(); sc2(); sc3(); sc4(); sc5();

}

window.onscroll = scall;

window.onresize = scall;

window.onload = scall;

//-->

</SCRIPT>

<div style="position: absolute; top: 0px; left: 0px; width: 10000px; height: 4000px;"></div>

</BODY>

</html///////////

///////////////三角形面积公式:

普通的:1/2底乘高or1/2absinC;1/2bcsinA;1/2acsinB 海伦公式(与之类似的是秦九韶公式):S=根号下P(P-a)(P-b)(P-c)其中P=1/2(a+b+c)内切圆的算法:1/2r(a+b+c)             够显然了吧 参考资料:高中数学必修5

//获取datalist重复出现控件的属性:

<ItemTemplate>

<asp:Button ID="Seat_numberLabel" runat="server" CommandName="select"

Text='<%# Eval("Seat_number") %>' />

</ItemTemplate>

protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)

{

if (e.CommandName == "select")

{

Label1.Text = (e.Item.FindControl("Seat_numberLabel") as Button).Text;

}

}

//datalist中根据字段不同显示北京不同,tooltip是与字段绑定的;

protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)

{

{

Button btn=(Button)e.Item.FindControl("Seat_numberLabel");

if (btn.ToolTip=="True")

{

btn.BackColor = System.Drawing.Color.Yellow;

}

else

{

}

}

}

//循环插入数据数据库

USE MovieTicket

declare @i int

set @i=1

declare @j int

WHILE(@i<=20)

BEGIN

set @j=1

WHILE(@j<=20)

BEGIN

insert INTO SeatDetail(Seat_number,fangyi_id)VALUES(convert(nvarCHAR

,@i)+','+convert(nvarCHAR

,@j),22)

set @j=@j+1

END

set @i=@i+1

END

DELETE from SeatDetail

在Gridview或者Formview里面放置了其它的控件,比如label,那么如何获取这个label的值呢?看以下代码

前台GridView 的设置:

<asp:GridView ID="GridView1" runat="server" AllowPaging="True"

AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ID"

DataSourceID="LinqDataSource1">

<Columns>

<asp:BoundField DataField="ID" HeaderText="编号" InsertVisible="False"

ReadOnly="True" SortExpression="ID" />

<asp:BoundField DataField="fname" HeaderText="文件名" SortExpression="fname" />

<asp:TemplateField HeaderText="下载地址" SortExpression="furl">

<EditItemTemplate>

<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("furl") %>'></asp:TextBox>

</EditItemTemplate>

<ItemTemplate>

<asp:Label ID="Label1" runat="server" Text='<%# Bind("furl") %>'></asp:Label>

<asp:Button ID="downBtn" runat="server" Text="点击下载" onclick="downBtn_Click" />

<asp:Label ID="errLabel" runat="server" Text=""></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:BoundField DataField="addtime" HeaderText="添加时间"

SortExpression="addtime" />

</Columns>

</asp:GridView>

后台cs文件:

protected void downBtn_Click(object sender, EventArgs e)

{

//根据控件所在的行和列,再用 FindControl函数获取到该控件

Label furlLabel = (Label)GridView1.Rows[1].Cells[3].FindControl("Label1");

string fileName = furlLabel.Text;

this.DownLoadFile(fileName);

}

Formview里面获取就更加简单,直接使用  Label furlLabel = (Label)FormView1.FindControl("furlLabel");

//服务器添加提示框:return confirm('确定删除吗?')卸载onclientclick;

//// string bbb=aaa.Substring(aaa.LastIndexOf("?")+1);//获取字符串某个字母后的字符串

///sql如何将以逗号间隔的字符串循环插入数据库中

DECLARE @Str nvarchar(1000);

DECLARE @Index int;

DECLARE @Left nvarchar;

SELECT @Str = 'A|B|C|';

WHILE CHARINDEX('|',@Str) > 0

BEGIN

SELECT @Index = CHARINDEX('|',@Str);

SELECT @Left = LEFT(@Str,@Index-1);

INSERT INTO asd (iid,str) VALUES (1,@LEFT);

SELECT @Str = REPLACE(@Str,@Left+'|','');

END

IF @Str <> ''

BEGIN

INSERT INTO asd (iid,str) VALUES (1,@LEFT);

END

SELECT * FROM asd

delete FROM asd

///////////////////完整sql如何将以逗号间隔的字符串循环插入数据库中

ALTER PROCEDURE dbo.dingpiaoinsert

(

@userId uniqueidentifier,

@Str nvarchar(200),

@movie_yingtingid int,

@date datetime

)

AS

begin

begin try

DECLARE @Index int;

DECLARE @Left int;

WHILE CHARINDEX('|',@Str) > 0

BEGIN

SELECT @Index = CHARINDEX('|',@Str);

SELECT @Left = LEFT(@Str,@Index-1);

INSERT INTO SeatUser(UserId,SeatId,Movie_yingtingid,[date]) VALUES (@userId,@Left,@movie_yingtingid,@date);

SELECT @Str = REPLACE(@Str,@Left+'|','');

END

IF @Str <> ''

BEGIN

INSERT INTO SeatUser(UserId,SeatId,Movie_yingtingid,[date]) VALUES (@userId,@Left,@movie_yingtingid,@date);

END

return 0

end try

begin catch

return error_number()

end catch

end

//求某个字符串中某个字母出现的次数:

result= str.Split('|').Length - 1;

//分割字符串

string s="abcdeabcdeabcde";

string[] sArray=s.Split('c');

foreach(string i in sArray)

Console.WriteLine(i.ToString());

输出下面的结果:

ab

deab

deab

de

///////////////发送邮件的全部代码:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Net.Mail;

using System.Web.UI;

using System.Web.UI.WebControls;

public partial class 传送邮件 : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

}

public void Email()

{

MailAddress Messagefrom = new MailAddress(TextBox1.Text);  //发件人邮箱地址

string MessageTo = TextBox2.Text;  //收件人邮箱地址

string MessageSubject = TextBox3.Text;        //邮件主题

string MessageBody = TextBox4.Text;    //邮件内容

if (Send(Messagefrom, MessageTo, MessageSubject, MessageBody))

{

Response.Write("<script type='text/javascript'>alert('发送成功!');history.go(-1)</script>");//发送成功则提示返回当前页面;

}

else

{

Response.Write("<script type='text/javascript'>alert('发送失败!');history.go(-1)</script>");

}

}

public static bool Send(MailAddress Messagefrom, string MessageTo, string MessageSubject, string MessageBody)

{

MailMessage message = new MailMessage();//创建一个邮件信息的对象

message.From = Messagefrom;

message.To.Add(MessageTo);              //收件人邮箱地址可以是多个以实现群发

message.Subject = MessageSubject;

message.Body = MessageBody;

message.IsBodyHtml = false;              //是否为html格式

message.Priority = MailPriority.High;  //发送邮件的优先等级

SmtpClient sc = new SmtpClient();       //简单邮件传输协议(Simple Message Transfer Protocol)

sc.Host = "smtp.qq.com";              //指定发送邮件的服务器地址或IP 使用其它邮箱的发送 需做更改ru:smtp。126.com

sc.Port = 25;                          //指定发送邮件端口

sc.UseDefaultCredentials = true;

sc.EnableSsl = false;

sc.Credentials = new System.Net.NetworkCredential("1624484726", "gzf1309841991"); //指定登录服务器的用户名和密码

try

{

sc.Send(message);      //发送邮件

}

catch (Exception e)

{

return false;

}

return true;

}

protected void Button1_Click(object sender, EventArgs e)

{

Email();

}

}

-------------------------访问access数据库

OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Student.mdb");

cn.Open();

OleDbCommand cmd = new OleDbCommand("select * from stu",cn);

// OleDbDataReader rea = cmd.ExecuteReader();

//while (rea.Read())

//{

//    MessageBox.Show(rea[1].ToString());

//}

OleDbDataAdapter da = new OleDbDataAdapter(cmd);

DataSet ds=new DataSet();

da.Fill(ds);

dataGridView1.DataSource = ds.Tables[0];

cn.Close();

OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Student.mdb;Jet OLEDB:Database password=jiba");

-========================================

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Data.OleDb;

using System.Windows.Forms;

using System.Data.SqlClient;

namespace Access连接

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Student.mdb;Jet OLEDB:Database password=jiba");

private void button1_Click(object sender, EventArgs e)

{

cn.Open();

OleDbCommand cmd = new OleDbCommand("select * from stu",cn);

// OleDbDataReader rea = cmd.ExecuteReader();

//while (rea.Read())

//{

//    MessageBox.Show(rea[1].ToString());

//}

OleDbDataAdapter da = new OleDbDataAdapter(cmd);

DataSet ds=new DataSet();

da.Fill(ds);

dataGridView1.DataSource = ds.Tables[0];

cn.Close();

}

}

}

--------------------验证码

string s = "";

Bitmap m = new Bitmap(50,20);

Graphics c = Graphics.FromImage(m);

c.FillRectangle(Brushes.Blue, 0, 0, 100, 100);

Random a = new Random();

s =a.Next(0, 10000).ToString();

Font f=new Font(new FontFamily("黑体"),15,FontStyle.Bold);

//TextureBrush t = new TextureBrush(System.Drawing.Image.FromFile(@"C:\Users\dell\Documents\Visual Studio 2010\NetFramework\测试\img\13031I320610-26250.jpg"));

// HatchBrush b = new HatchBrush(HatchStyle.DarkHorizontal, Color.Red, Color.Yellow);

LinearGradientBrush b = new LinearGradientBrush(new Point(12,34),new Point(23,45), Color.Yellow, Color.Green);

c.DrawString(s, f, b, 0, 0);

c.DrawLine(Pens.Gray, 0, 4, 55, 10);

MemoryStream ms = new MemoryStream();

m.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);

Response.ContentType = "image/bmp ";

Response.BinaryWrite(ms.ToArray());

-------------------------存储图片

string s=Server.MapPath("~/img/13031I320610-26250.jpg");

string ss=Server.MapPath("~/img/as.txt");

FileStream f = new FileStream(s,FileMode.Open);

byte[] b=new byte[f.Length];

f.Read(b, 0, b.Length);

f.Close();

Response.ContentType = "image/bmp";

Response.BinaryWrite(b);

直接插入b即可,image插入的是byte[]类型的;

读的时候用sqldatareader接收;并转化为byte[](强制转型)即可;

----------------------------xml:定义方框:

display:block;

border:10px;

border-color:yellow;

border-style:solid;

--------------------------

UnicodeEncoding ue=new UnicodeEncoding();//字节的转换

byte[] dataToEncrypt = ue.GetBytes(s);//要加密的数据

---------------------哈希计算是单向的;

rigjided是例外的;

计算哈希:ComputeHash

--------------字符串转为字节数组;

byte [] key = System.Text.Encoding.Default.GetBytes( textBox );

fswrite.WriteByte((byte)length);

byte[]   RgbKey   =   System.Text.Encoding.UTF8.GetBytes(decryptKey);

---------------

DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);

----------------------对datatable的查询

1。统计所有性别为女的销售员的数量:

table.Compute("Count(*)","Sex=0");

2。统计所有销售员中年龄大于20岁的

table.Compute("Count(*)","Birthday<'"+today);//today为今天的日期字符串

3。统计销售产品的平均价格

table.Compute("Aver(Price)","true");

4。统计产品代码为1的产品销售数量:

table.Compute("Sum(Quantity)","ProID=1");

5。统计所有产品的销售总金额:

要统计总销售金额,由于table中不存在某项产品某个促销员销售的金额数据,但我们可以通过Quantity*Price来获得。比如:

table.Compute("Sum(Quantity*Price)","true");

这里一个问题是:DataTable的统计功能没有SqlServer强,这个统计是错误的,因为Compute的统计不具备Sum(Quantity*Price)这样数据的功能。那怎么办呢?

对于这样复杂数据的统计,我们可以在DataTable中创建一个新的字段来完成,比如Amount,同时设置该字段的Expression为Quantity*Price,这样我们就可以使用统计功能了:

table.Compute("Sum(Amount)","true");

以上都是计算每一列的合计,要添加一行求合计可以使用下面的方法:

System.Data.DataRow dataRow=dataSet.Tables[0].NewRow()

'假设你的DataSet为dataSet,表在索引0位置,同时假设你的所有字段都是可以求合计的。

System.DataRow dataRow = new System.DataRow();

dataRow=DT.NewRow();

然后就是统计了:

int i ;

int fldCnt ;

fldCnt=DT.Cols.Count;

for( i=0 ;i< fldCnt-1;i++)

dataRow(i)=DT.Compute("Sum("+i.ToString()+")","true");

DT.Rows.Add(dataRow);

好了,大功告成。希望对大家有用。

-----------------------------------------------------------Dictionary的应用

int count = 0;

d = new Dictionary<string, int>();

if (ta.Rows.Count !=0)

{

for (int i = 0; i < ta.Rows.Count; i++)

{

if (!d.ContainsKey(ta.Rows[i][2].ToString()))

{

count = Convert.ToInt32(ta.Compute("count(winner)","winner='" + ta.Rows[i][2].ToString().Trim() + "'"));

d.Add(ta.Rows[i][2].ToString(), count);

}

}

//linq排序

var so = from dd in d orderby dd.Value  select dd;

//定义流

if (saveFileDialog1.ShowDialog() == DialogResult.OK)

{

try

{

fs = new FileStream(saveFileDialog1.FileName, FileMode.OpenOrCreate);

sw = new StreamWriter(fs);

foreach (KeyValuePair<string, int> va in so)

{

sw.BaseStream.Seek(0, SeekOrigin.End);

sw.WriteLine(va.Value + ":" + va.Key);

}

}

catch (Exception ex)

{

MessageBox.Show(ex.Message);

}

finally

{

sw.Close();

fs.Close();

}

}

}

}

----------------------------------

var这只能用于局部变量,用于字段是不可以的。

---------------------

var persons = new List<Person> {

new Person {username = "a", age=1},

new Person {username = "b", age=2}};

foreach(var p in persons)

Console.WriteLine(p.ToString());

-----------------------

//跨线程调用wincontrol

CheckForIllegalCrossThreadCalls = false;

------------------------滚动

<marquee direcion="left" behavior="scroll" bgcolor="red" height="150px" scrolldelay="1000" scrollmount="800" onMouseOver="this.stop()" onMouseOut="this.start()" >

dfsdfsfsf

</marquee>

-------------------------ctor:tab+tab键:构造函数;

--------------自定义异常类

namespace 控制台程序

{

public  class Class2 :ApplicationException

{

public Class2(string conStr,DateTime time):base(conStr)

{

Console.WriteLine(string.Format("错误信息:{0},出错时间:{1}",conStr,time));

}

public override string Message

{

get

{

return string.Format("错误信息:{0}",base.Message);

}

}

}

}

--throw new class2(两个参数);

----------判断继承关系

Bird b = new Bird();

if (b is BirdClass)

{

Console.WriteLine("我是继承的是飞机");

(b as BirdClass).Fly();

}

-----------------------------------

public void sum(params int[] num)

{

}

调用时:sum(1,2,4)即可

----------------------------------------------

int s = 001;不违法

----------------------------格式化string.Format();

Console.WriteLine(string.Format("值是:{0:C2}", 1000000));//2表示保留几位小数

Console.WriteLine(string.Format("值是:{0:D}", 'a'));//输出10进制数字

Console.WriteLine(string.Format("值是:{0:F3}", 100000.345678));//保留小数后几位

Console.WriteLine(string.Format("值是:{0:N6}", 100000));//用逗号隔开

Console.WriteLine(string.Format("值是:{0:P2}", 0.23));//百分数

------------------------数据库有中文为unicode;char(5)若只有a,前面补空格00005;

-----------lambda--->goes to

---抽象类总属性也可是抽象的。

-------------------------------------------------------------软查询

//软绑定

public bool InsertFriend1(Entity.Friend friend)

{

string str = "insert into Friends(Name,Age) values(@Name,@Age)";

SqlParameter[] param ={

new SqlParameter("@Name",SqlDbType.NVarChar,50),

new SqlParameter("@Age",SqlDbType.Int)

};

param[0].Value = friend.Name;

param[1].Value = Convert.ToInt32(friend.Age);

int i = helper.ExecuteNoneQuery(str,param);

if (i == 1)

return true;

else

return false;

}

----------------------datagridview获取字段值

extBox1.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();

设置属性selectionmode=fullrowselect

-------------------------

ALTER PROCEDURE dbo.GDeleteAllScore

(

@beginstuid char(10),

@endstuid char(10),

@GTime smalldatetime,

@GCour char(10),

@Tid char(10),

@bubianid char(10)

)

AS

begin try

delete from Grade where SId>=rtrim(@bubianid)+@beginstuid and SId<= rtrim(@bubianid)+@endstuid and GCour=@GCour and GTime=@GTime and Tid=@Tid

return 0;

end try

begin catch

return error_number()

end catch

-----------------------------数据库存储查询大小写密码;

SELECT * FROM Admin WHERE APwd='aa' COLLATE Chinese_PRC_CS_AI

-----------------------------MD5加密

string s = FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox2.Text.Trim(), "MD5");

------------------------------------

<script type="text/javascript">

var i=2;

window.onload=function(){

setInterval(Show,1000);

}

function Show()

{

var path="../image/class1-"+i+".jpg";

document.getElementById("pic").src=path;

if(i==3)

{

i=0;

}

i=i+1;

}

</script>

-------------------------js元素的坐标

ad.style.left = 100;

ad.style.top = 100;

----------------------

this.FormView1.UpdateItem(true);

-----------------------------------

$(function () {

//        $("p").click(function () { $.each($(this).nextAll("p"), function () { $(this).css("background-color", "red"); } )});

//    })

-----------------------------

$(this).siblings().html("<img src='mobilynotes/img/nature/img1.jpg' />");

其它的

--------------

$("#Text1").val("请输入姓名").css("background-Color", "red").focus(function () { $(this).val("").css("background-Color", "white") });

--------------

$(function () {

if ($.cookie("username"))

$("#Text1").val($.cookie("username"));

})

function guo() {

$.cookie("username", $("#Text1").val());

}

------------------

var v =Math.random();

---------------------------------

$(function () {

//            var date = { "name": "guozefeng", "nam": "guozefeng", "nme": "guoze" };

//            $.each(date, function (key, value) {

//                var a = $("<tr><td>" + key + "</td><td>" + value + "</td></tr>");

//               $("#oo").append(a);

//            });

//        })

----------------------

function ze() {

//        if (arguments.length== 1)//判断传过来的参数是多少个

var df = arguments[0];//获取参数;

var d = arguments[1];

alert(df+d);

}

---------------

判断输入内容是否为空

function IsNull(){

var str = document.getElementById('str').value.trim();

if(str.length==0){

alert('对不起,文本框不能为空或者为空格!');//请将“文本框”改成你需要验证的属性名称!

}

}

----------------------------存储过程的好处。

存储过程安全,优化,减少网络传输等,还是可以的。不过开发时存储过程好麻烦

-------------------------js元素的坐标

ad.style.left = 100;

ad.style.top = 100;

----------------------

this.FormView1.UpdateItem(true);

-----------------------------------

$(function () {

//        $("p").click(function () { $.each($(this).nextAll("p"), function () { $(this).css("background-color", "red"); } )});

//    })

-----------------------------

$(this).siblings().html("<img src='mobilynotes/img/nature/img1.jpg' />");

其它的

--------------

$("#Text1").val("请输入姓名").css("background-Color", "red").focus(function () { $(this).val("").css("background-Color", "white") });

--------------

$(function () {

if ($.cookie("username"))

$("#Text1").val($.cookie("username"));

})

function guo() {

$.cookie("username", $("#Text1").val());

}

------------------

var v =Math.random();

---------------------------------

$(function () {

//            var date = { "name": "guozefeng", "nam": "guozefeng", "nme": "guoze" };

//            $.each(date, function (key, value) {

//                var a = $("<tr><td>" + key + "</td><td>" + value + "</td></tr>");

//               $("#oo").append(a);

//            });

//        })

----------------------

function ze() {

//        if (arguments == 1)//判断传过来的参数是多少个

var df = arguments[0];//获取参数;

var d = arguments[1];

alert(df+d);

}

-------asp.net传值(3种传值方式)

1.跨页面传值

if (this.PreviousPage != null)

{

if (this.PreviousPage.IsCrossPagePostBack)

{

this.TextBox1.Text = (this.PreviousPage.FindControl("TextBox1") as TextBox).Text.ToString().Trim();

this.TextBox2.Text = (this.PreviousPage.FindControl("TextBox2") as TextBox).Text.ToString().Trim();

}

}

//postbackurl设置属性即可;

//if (this.PreviousPage != null)

//{

//    if (this.PreviousPage.IsCrossPagePostBack)

//    {

//        this.TextBox1.Text = (this.PreviousPage.FindControl("TextBox1") as TextBox).Text.ToString().Trim();

//        this.TextBox2.Text = (this.PreviousPage.FindControl("TextBox2") as TextBox).Text.ToString().Trim();

//    }

//}

//post方法://不会报错;需要名明空间using System.Collections.Specialized;:特殊集合

//前面 Server.Transfer("a2aspx.aspx");

NameValueCollection nv = new NameValueCollection();//这种集合的好处是key值可以重复

nv = Request.Form;

this.TextBox1.Text = nv["TextBox1"];

this.TextBox2.Text = nv["TextBox2"];

//get显示Response.Redirect("a2aspx.aspx?name="+TextBox1.Text+"&pwd="+TextBox2.Text);

TextBox1.Text = Request.QueryString["name"].ToString();

TextBox2.Text = Request.QueryString["pwd"].ToString();

------------------只要用户一打开就会执行globle.asax文件的session.start;

安全退出或是注销

Session.Abandon();即可;

--------------------------------蓝色样式背景颜色;

<style type="text/css">

.Menu

{

width:198px;

height:600px;

}

.Menu1

{

width:100%;

height:26px;

background:#ecf6fc;

text-align:center;

border:1px solid #95bce2;

border-spacing:2px;

padding-top:10px;

}

.Menu2

{

margin-top:auto;

width:100%;

height:100%;

text-align:center;

border:1px solid #95bce2

}

</style>

------------------------------数据库节点

protected void Page_Load(object sender, EventArgs e)

{

SqlConnection cn = new SqlConnection("data source=GUOZEFENG\\GZF;initial catalog=MyBookShop;uid=sa;pwd=sa");

cn.Open();

SqlCommand cmd = new SqlCommand("select * from Categories",cn);

SqlDataAdapter daa = new SqlDataAdapter(cmd);

DataSet dss = new DataSet();

daa.Fill(dss);

TreeNode node = new TreeNode();

this.TreeView1.Nodes.Add(node);

for (int j = 0; j < dss.Tables[0].Rows.Count; j++)

{

TreeNode node1 = new TreeNode();

node1.Text =dss.Tables[0].Rows[j][1].ToString();

node1.Value =dss.Tables[0].Rows[j][0].ToString();

node1.NavigateUrl = "#";

//bangdingtushu

SqlDataAdapter da = new SqlDataAdapter("select top(3) id,title from books where categoryid=" + Convert.ToInt32(dss.Tables[0].Rows[j][0].ToString()) + "", cn);

DataSet ds = new DataSet();

da.Fill(ds);

for (int i = 0; i < ds.Tables[0].Rows.Count; i++)

{

TreeNode node2 = new TreeNode();

node2.Text = ds.Tables[0].Rows[i][1].ToString();

node2.Value = ds.Tables[0].Rows[i][0].ToString();

node2.NavigateUrl = "Showbook.aspx?id="+ds.Tables[0].Rows[i][0].ToString();

node1.ChildNodes.Add(node2);

}

//end

node.ChildNodes.Add(node1);

}

----------------------------------------------------

数据库中的money对应的是decimal(最大对应38)

-------------------------文件上传

bool fileok = false;

//string pt = HttpContext.Current.Request.MapPath("../MovieImg/");

string pt = Server.MapPath("../MovieImg/");

if (FileUpload1.HasFile)//judge has file

{

string fe = Path.GetExtension(FileUpload1.FileName).ToLower();

//filename属性是来获取上传控件的文件名

//getexetension()方法是用来获取文件名中的扩展名

//tolower()方法转换所有自负串为小写字母;

string[] ae = { ".gif", ".bmp", ".jpg", ".jpeg",".PNG",".tif" };

for (int i = 0; i < ae.Length; i++)

{

if (fe == ae[i])

{

fileok = true;

}

}

}

if (fileok)

{

FileUpload1.PostedFile.SaveAs(pt +FileUpload1.FileName);

this.Button2.Text = "上传成功";

a2.Text = "~/MovieImg/" + FileUpload1.FileName;

}

else

{

this.Button2.Text = "文件不能上传";

}

-------------------------------------gradeview\gridview数据绑定操作dropdownlist

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

{

protected void Page_Load(object sender, EventArgs e)

{

}

public string GetUrl(object obj)    //页面绑定

{

return "BookCovers"+"/"+obj.ToString()+".jpg";

}

protected void DetailsView1_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)

{

FileUpload file1 = this.DetailsView1.FindControl("fileEdit") as FileUpload;

if (file1.FileName != "")

{

TextBox txtedit=this.DetailsView1.FindControl("txtISBNedit") as TextBox;//因为要获取isbn的值,所以要把isbn也换成模板列

file1.SaveAs(Server.MapPath("BookCovers") + "/" + txtedit.Text + ".jpg");

}

//参数中存在差异(对象)需手动添加参数而cAteGoryId与界面update中的参数只要差一个字母大写就行了,这样不仅能别识别为同一个参数而且不会因重复而报错

DropDownList ddlcategory=this.DetailsView1.FindControl("ddlCategoryEdit") as DropDownList;

this.ObjectDataSource1.UpdateParameters.Add("cAteGoryId", ddlcategory.SelectedValue);

DropDownList ddlPublisher = this.DetailsView1.FindControl("ddlPublisherEdit") as DropDownList;

this.ObjectDataSource1.UpdateParameters.Add("publisHerid", ddlPublisher.SelectedValue);

}

protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)

{

FileUpload file2 = this.DetailsView1.FindControl("fileInsert") as FileUpload;

TextBox txtinsert = this.DetailsView1.FindControl("txtISBNinsert") as TextBox;

file2.SaveAs(Server.MapPath("BookCovers") + "/" + txtinsert.Text + ".jpg");

DropDownList ddlcategory = this.DetailsView1.FindControl("ddlCategoryInsert") as DropDownList;

this.ObjectDataSource1.InsertParameters.Add("cAteGoryId", ddlcategory.SelectedValue);

DropDownList ddlPublisher = this.DetailsView1.FindControl("ddlPublisherInsert") as DropDownList;

this.ObjectDataSource1.InsertParameters.Add("publisHerid", ddlPublisher.SelectedValue);

}

protected void DetailsView1_DataBound(object sender, EventArgs e)

{

if (this.DetailsView1.CurrentMode == DetailsViewMode.Edit)

{

//保证更再更改时还会显示之前的选项;

HiddenField hf = this.DetailsView1.FindControl("HiddenField1") as HiddenField;

DropDownList ddlcategory = this.DetailsView1.FindControl("ddlCategoryEdit") as DropDownList;

ddlcategory.SelectedValue = hf.Value;

HiddenField hf2 = this.DetailsView1.FindControl("HiddenField2") as HiddenField;

DropDownList ddlPublisher = this.DetailsView1.FindControl("ddlPublisherEdit") as DropDownList;

ddlPublisher.SelectedValue = hf2.Value;

}

}

//protected void DetailsView1_ModeChanging(object sender, DetailsViewModeEventArgs e)

//{

//    if (this.DetailsView1.CurrentMode == DetailsViewMode.Edit)

//    {

//        HiddenField hf = this.DetailsView1.FindControl("HiddenField1") as HiddenField;

//        DropDownList ddlcategory = this.DetailsView1.FindControl("ddlCategoryEdit") as DropDownList;

//        ddlcategory.SelectedValue = hf.Value;

//        HiddenField hf2 = this.DetailsView1.FindControl("HiddenField2") as HiddenField;

//        DropDownList ddlPublisher = this.DetailsView1.FindControl("ddlPublisherEdit") as DropDownList;

//        ddlPublisher.SelectedValue = hf2.Value;

//    }

//}

}

-------------------------------发布网站:

1.发布网站:发布到到一个文件夹

2.安装iis和asp.net4.0:

C:\Windows\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis.exe -i

开始安装 ASP.NET (4.0.30319)。

3.添加网站,端口号设为:8000以上

4.默认文档:添加登录页面;

5.点击全网站:选择:isapi和cgi都设为允许;

6.应用程序池:全部勾经典,在asp.net v4.0classc高级设置,表示改为localSystem;

7.在asp图标,父级目录改为true;

需要注意:发布时,要在空文件夹内放上东西,否则会丢失的!;

放到服务器上时,先上传文件,之后进入服务器操作便可;

-----------------treeviewexpanddepth=0;默认合拢

折叠节点:his.tvMenue.SelectedNode.Collapse();

-----------对于gridview绑定id隐藏域

<EditItemTemplate>

<asp:TextBox ID="TextBox1" runat="server" Height="54px"

Text='<%# Bind("RoleName") %>'></asp:TextBox>

<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Bind("RoleId") %>' />

</EditItemTemplate>

写一个便可

-----------------------设置行高:

Height="20px" 在gridview内写;

-----------------gridview删除绑定实体:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)

{

if (e.CommandName == "Delete")

{

bool result = MyOffice.BLL.BllProvider.RoleInfoManageP.DeleteRoleInfoById(Convert.ToInt32(e.CommandArgument));

if (result)

{

this.GridView1.DataSourceID = "ObjectDataSource1";//相当于刷新

}

}

}

objectdatasource绑定delete一个空方法,但参数是实体,业务层这个方法可以不写;

--------------------绑定:

if (this.DetailsView1.CurrentMode == DetailsViewMode.Edit)

{

HiddenField hf = this.DetailsView1.FindControl("HiddenField1") as HiddenField;

DropDownList ddlcategory = this.DetailsView1.FindControl("ddlCategoryEdit") as DropDownList;

ddlcategory.SelectedValue = hf.Value;

HiddenField hf2 = this.DetailsView1.FindControl("HiddenField2") as HiddenField;

DropDownList ddlPublisher = this.DetailsView1.FindControl("ddlPublisherEdit") as DropDownList;

ddlPublisher.SelectedValue = hf2.Value;

}

--------------gridview绑定:

1.查询总天数(去除周六日)

DECLARE @count int

SET @count=0

DECLARE @str nvarchar(10)

SET @str=''

DECLARE @date1 datetime

SET @date1='2012-8-16'

DECLARE @date2 datetime

SET @date2='2012-8-19'

WHILE @date1<@date2

begin

set @str=datename(dw,@date1)

IF @str<>'星期六' and @str<>'星期日'

set @count=@count+1

set @date1=dateadd(dd,1,@date1)

end

PRINT @count

-----------------------------------

插入一行数据,并返回插入行的id

INSERT INTO RoleInfo(RoleName,RoleDesc)VALUES('12','123');SELECT @@identity;

execuscalar();

---------------------------设置cookie

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using BookShop.Model;

using BookShop.Bll;

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

{

UserManage umg = new UserManage();

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

if (Request.Cookies["userName"] != null)

{

TextBox1.Text = Request.Cookies["userName"].Value;

TextBox2.Text = Request.Cookies["userPwd"].Value;

CheckBox1.Checked = true;

}

}

}

protected void Button1_Click(object sender, EventArgs e)

{

User user=new User();

user.LoginId=TextBox1.Text.Trim();

user.LoginPwd=TextBox2.Text.Trim();

if (umg.ValidateUser(user) == 1)

{

if (CheckBox1.Checked)

{

if (Request.Cookies["userName"] == null || Request.Cookies["userName"].Value != TextBox1.Text.Trim())

{

HttpCookie cku = new HttpCookie("userName", user.LoginId);

HttpCookie ckp = new HttpCookie("userPwd", user.LoginPwd);

cku.Expires = DateTime.Now.AddDays(30);

ckp.Expires = DateTime.Now.AddDays(30);

Response.Cookies.Add(cku);

Response.Cookies.Add(ckp);

}

}

else

{

Response.Cookies.Remove("userName");

Response.Cookies.Remove("userPwd");

Response.Cookies.Clear();

}

Server.Transfer("Show.aspx");

}

else

{

this.Page.RegisterStartupScript("","<script type='text/javascript'>alert('登陆失败!请检查用户名和密码!')</script>");

}

}

protected void Button2_Click(object sender, EventArgs e)

{

Server.Transfer("注册.aspx");

}

}

//获取客户端ip地址

private string GetUserIp()

{

string loginip=string.Empty;

if (Request.ServerVariables["REMOTE_ADDR"] != null) //判断发出请求的远程主机的ip地址是否为空

{

//获取发出请求的远程主机的Ip地址

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

}

//判断登记用户是否使用设置代理

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

{

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

{

//获取代理的服务器Ip地址

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

}

else

{

//获取客户端IP

loginip = Request.UserHostAddress;

}

}

return loginip;

}

}

全球化:

<globalization culture="zh-CN" uiCulture="zh-CN"/>(web.config)

<asp:ScriptManager EnableScriptGlobalization="true"

EnableScriptLocalization="true" ID="ScriptManager1" runat="server">

</asp:ScriptManager>

--------------------

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using MyOffice.BLL;

using MyOffice.Model;

using MyOffice.Framework;

//gridview各种绑定(增删改查)

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

{

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

DataBound();

}

}

protected void Button1_Click(object sender, EventArgs e)

{

if (TextBox1.Text != "" && TextBox2.Text != "")

{

BranchInfo bi = new BranchInfo();

bi.BranchName = TextBox1.Text;

bi.BranchShortName = TextBox2.Text;

BllProvider.BranchInfoManageP.InsertBranch(bi);

}

}

private void DataBound()

{

List<BranchInfo> list;

list = BllProvider.BranchInfoManageP.GetAllBrachInfos();

if (list.Count != 0)

{

this.GridView1.DataSource = list;

this.GridView1.DataBind();

}

}

protected void Button1_Click1(object sender, EventArgs e)

{

//ui上已经做了验证

BranchInfo bi = new BranchInfo();

bi.BranchName = TextBox1.Text.Trim();

bi.BranchShortName = TextBox2.Text.Trim();

bool result = BllProvider.BranchInfoManageP.InsertBranch(bi);

if (result)

{

DataBound();

}

else

{

//失败!

}

}

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)

{

int no =Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0].ToString());

bool b = BllProvider.BranchInfoManageP.DeleteBranchInfoById(no);

if (b)

{

DataBound();

}

}

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)

{

}

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)

{

this.GridView1.PageIndex = e.NewPageIndex;

DataBound();

}

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)

{

GridView1.EditIndex = e.NewEditIndex;

DataBound();

}

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

{

//不好用:可以findcotrol方法;

int stuno = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0].ToString());

string newBranchName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox3")).Text;

string newBranchShortName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox4")).Text;

BranchInfo bi = new BranchInfo();

bi.BranchName = newBranchName;

bi.BranchShortName =newBranchShortName;

bi.BranchId =stuno;

GridView1.EditIndex = -1;

if (BllProvider.BranchInfoManageP.UpdateBranchInfoById(bi))

{

//成功!

DataBound();

//DataBind();

}

else

{

//失败!

}

}

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

{

GridView1.EditIndex = -1;

DataBound();

}

protected void Button2_Click(object sender, EventArgs e)

{

}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

{

if (e.Row.RowType == DataControlRowType.DataRow)

{

e.Row.Attributes.Add("onmouseover", "cc=this.style.backgroundColor;this.style.backgroundColor='#ecf6fc'");

e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=cc");

}

}

protected void Changing(object sender, GridViewPageEventArgs e)

{

}

protected void aBound(object sender, GridViewRowEventArgs e)

{

}

}

----------------------------第三方分页控件的使用

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using MyOffice.Framework;

using MyOffice.BLL;

using MyOffice.Model;

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

{

LoginLogManage lm = BllProvider.LoginLogManageP;

static PagedDataSource pds = new PagedDataSource();

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

Label7.Text = string.Empty;

pds.DataSource = lm.SelectAllLog(Convert.ToDateTime("2000-01-01"),Convert.ToDateTime("3000-01-01"));

pds.AllowPaging = true;

BindData();

}

}

protected void rdoday_CheckedChanged(object sender, EventArgs e)

{

TxtGetValue(DateTime.Now.ToShortDateString(), DateTime.Now.AddDays(1).ToShortDateString());

}

protected void rdoweek_CheckedChanged(object sender, EventArgs e)

{

TxtGetValue(MyOffice.Framework.DateProvider.CurrentWeekStartDay().ToShortDateString(), DateTime.Now.AddDays(1).ToShortDateString());

}

protected void rdomodth_CheckedChanged(object sender, EventArgs e)

{

TxtGetValue(MyOffice.Framework.DateProvider.CurrentMonthStartDay().ToShortDateString(), DateTime.Now.AddDays(1).ToShortDateString());

}

//给textbox赋值

private void TxtGetValue(string str1, string str2)

{

txtbegintime.Text = str1;

txtendtime.Text = str2;

}

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)

{

}

protected void Button1_Click(object sender, EventArgs e)

{

Label7.Text = string.Empty;

if (YanZheng(txtbegintime, txtendtime))

{

pds.DataSource = lm.SelectAllLog(Convert.ToDateTime(txtbegintime.Text.Trim()), Convert.ToDateTime(txtendtime.Text.Trim()));

BindData();

}

else

{

Label7.Text = "日期不能为空!";

}

}

//绑定gridview

private void BindData()

{

int a = 1;

AspNetPager1.RecordCount = pds.DataSourceCount;

if (pds.DataSourceCount % pds.PageSize != 0)

a = pds.DataSourceCount / pds.PageSize + 1;

else

a = pds.DataSourceCount / pds.PageSize;

this.AspNetPager1.SubmitButtonText = "GO(共计)" + a + "页";

if (a != 0)

{

this.AspNetPager1.NumericButtonCount = a;

}

else

{

this.AspNetPager1.NumericButtonCount = 1;

}

pds.PageSize = this.AspNetPager1.PageSize;

pds.CurrentPageIndex = this.AspNetPager1.CurrentPageIndex - 1;

this.GridView1.DataSource = pds;

this.GridView1.DataBind();

}

protected void AspNetPager1_PageChanged(object sender, EventArgs e)

{

BindData();

}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

{

if (e.Row.RowType == DataControlRowType.DataRow)

{

e.Row.Attributes.Add("onmouseover", "cc=this.style.backgroundColor;this.style.backgroundColor='#ecf6fc'");

e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=cc");

}

}

//判断gridview是否登录成功

public string CheckCell(object obj)

{

if (Convert.ToString(obj).ToString() == "0")

{

return "登录失败";

}

else

{

return "登录成功";

}

}

protected void btndelete_Click(object sender, EventArgs e)

{

string str = string.Empty;

for (int i = 0; i < this.GridView1.Rows.Count; i++)

{

CheckBox ch = this.GridView1.Rows[i].FindControl("CheckBox1") as CheckBox;//模板列,放置的是多选控件

if (ch.Checked == true)

{

Label lb = this.GridView1.Rows[i].FindControl("Label1") as Label;//被隐藏的模板列,帮定的是图书id

str += lb.Text.Trim() + ",";

}

}

//存储过程已经搞定了

//str = str.Substring(0, str.Length - 1);

bool num = lm.DeleteLoginLogById(str);

if (!num)

{

//删除失败

}

else

{

if (YanZheng(txtbegintime, txtendtime))

{

pds.DataSource = lm.SelectAllLog(Convert.ToDateTime(txtbegintime.Text.Trim()), Convert.ToDateTime(txtendtime.Text.Trim()));

}

else

{

pds.DataSource = lm.SelectAllLog(Convert.ToDateTime("2000-01-01"), Convert.ToDateTime("3000-01-01"));

}

try

{

BllProvider.OperateLogManageP.InsertOperateLog(Session["UserId"].ToString(), "删除登陆日志", str, "批量删除", DateTime.Now);

}

catch

{

}

BindData();

}

}

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)

{

}

private bool YanZheng(TextBox txt1, TextBox txt2)

{

if (txt1.Text.Trim().Length != 0 && txt2.Text.Trim().Length != 0)

{

return true;

}

else

{

return false;

}

}

}

-----------------------------

scriptmanage 注册javascript脚本

ScriptManager.RegisterStartupScript(this, this.GetType(), "str", " <script>$.messager.alert('MyOffice温馨提示:', '请选择用户!');</script> ", false);

ScriptManager.RegisterStartupScript(this, this.GetType(), "str", " <script>$.messager.alert('MyOffice温馨提示:', '<center><h5>已经存在,不能插入重复!</h5></span></center>');</script> ", false);

----------sql获取星期天

WHILE @startTime<@endTime

begin

set @str=datename(dw,@startTime)

IF @str<>'星期六' and @str<>'星期日'

set @count=@count+1

set @startTime=dateadd(dd,1,@startTime)

end

-------------------------添加水印效果

string str = "文字";

Font font = Font("宋体",30f); //字体,大小

Brush brush = Brushes.Red; //笔刷,颜色

PointF point = new PointF(10f,10f); //左上角位置

//文字格式

System.Drawing.StringFormat sf = new System.Drawing.StringFormat();

sf.FormatFlags = StringFormatFlags.DirectionVertical

Image image = Image.FromFile("C:\\1.gif");

Graphics g = Graphics.FromImage(image);

g.DrawString(str,font,brush,point,sf);

images.Save("c:\\1.gif");

-----------------------------查看表的触发器

select * from sys.triggers

------------------------------

string path = HttpContext.Current.Server.MapPath("~/Config/Sys/AirBtc.config");

return GetConfigValue(Target, path);

---------------------------------------sql区分大小写

ALTER TABLE tb ALTER COLUMN colname nvarchar(100) COLLATE Chinese_PRC_CI_AS

从数据库Collate到存储过程到函数,各种方法都有,选择适合你的。

第一种:

ALTER TABLE tb ALTER COLUMN colname nvarchar(100)

COLLATE Chinese_PRC_CI_AS --不区分大小写 ALTER TABLE tb

ALTER COLUMN colname nvarchar(100) COLLATE Chinese_PRC_CS_AS --区分大小写

alter database 数据库 COLLATE Chinese_PRC_CS_AS

---------------------

随笔- 9  文章- 195  评论- 9

转发与跳转的区别

Server.Transfer and Response.Redirect

Server.Transfer(ASP 3.0 以上) 和 Response.Redirect 在以前的 ASP 中就存在了,Page.Navigate 是 ASP.NET Beta 1 提供的新功能,它们之间的区别在于:

1、  Server.Transfer - 用于把处理的控制权从一个页面转移到另一个页面,在转移的过程中,没有离开服务器,内部控件(如:request, session 等)的保存的信息不变,因此,你能从页面 A 跳到页面 B 而不会丢失页面 A 中收集的用户提交信息。此外,在转移的过程中,浏览器的 URL 栏不变。

2、Response.Redirect - 发送一个 HTTP 响应到客户端,告诉客户端跳转到一个新的页面,客户端再发送跳转请求到服务器。使用此方法时,将无法保存所有的内部控件数据,页面 A 跳转到页面 B,页面 B 将无法访问页面 A 中 Form 提交的数据。

3、Page.Navigate - Page.Navigate 实现的功能和 Response.Redirect 差不多,它实际上包括三个步骤:首先调用 Response.Redirect,其次依次卸载所有的控件,最后调用 Response.End。

--------------页面传递中文参数

Server.UrlEncode();

<a href=<%=nowpage%>?page=Server.UrlEncode("上一页")>上一页</a>

------------------

asp.net有三种验证

forms,windows,passport;

--------------------------------

param[4].Value!=DBNull.Value

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.Security.Cryptography;

using System.IO;

using System.Text;

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

{

protected void Page_Load(object sender, EventArgs e)

{

}

}

///MD5加密

public string MD5Encrypt(string  pToEncrypt,  string  sKey)

{

DESCryptoServiceProvider  des  =  new  DESCryptoServiceProvider();

byte[]  inputByteArray  =  Encoding.Default.GetBytes(pToEncrypt);

des.Key  =  ASCIIEncoding.ASCII.GetBytes(sKey);

des.IV  =  ASCIIEncoding.ASCII.GetBytes(sKey);

MemoryStream  ms  =  new  MemoryStream();

CryptoStream  cs  =  new  CryptoStream(ms,  des.CreateEncryptor(),CryptoStreamMode.Write);

cs.Write(inputByteArray,  0,  inputByteArray.Length);

cs.FlushFinalBlock();

StringBuilder  ret  =  new  StringBuilder();

foreach(byte  b  in  ms.ToArray())

{

ret.AppendFormat("{0:X2}",  b);

}

ret.ToString();

return  ret.ToString();

}

///MD5解密

public string MD5Decrypt(string  pToDecrypt,  string  sKey)

{

DESCryptoServiceProvider  des  =  new  DESCryptoServiceProvider();

byte[]  inputByteArray  =  new  byte[pToDecrypt.Length  /  2];

for(int  x  =  0;  x  <  pToDecrypt.Length  /  2;  x++)

{

int  i  =  (Convert.ToInt32(pToDecrypt.Substring(x  *  2,  2),  16));

inputByteArray[x]  =  (byte)i;

}

des.Key  =  ASCIIEncoding.ASCII.GetBytes(sKey);

des.IV  =  ASCIIEncoding.ASCII.GetBytes(sKey);

MemoryStream  ms  =  new  MemoryStream();

CryptoStream  cs  =  new  CryptoStream(ms,  des.CreateDecryptor(),CryptoStreamMode.Write);

cs.Write(inputByteArray,  0,  inputByteArray.Length);

cs.FlushFinalBlock();

StringBuilder  ret  =  new  StringBuilder();

return  System.Text.Encoding.Default.GetString(ms.ToArray());

}

protected void Button1_Click(object sender, EventArgs e)

{

this.Label1.Text= MD5Encrypt(this.TextBox1.Text, "8lvbe4kE");

}

protected void Button2_Click(object sender, EventArgs e)

{

this.Label1.Text=MD5Decrypt(this.Label1.Text, "8lvbe4kE");

}

}

--------------------------------------------------------截图原理

简单截图软件实现原理

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Drawing.Drawing2D;

namespace jietu

{

public partial class benginok : Form

{

public benginok()

{

InitializeComponent();

}

private void button2_Click(object sender, EventArgs e)

{

Application.Exit();

}

private void buttok_Click(object sender, EventArgs e)

{   //隐藏窗体;

this.Hide();

//启动定时器,1.5秒后开始截图,以便于隐藏窗体。

timer1.Start();

}

private void timer1_Tick(object sender, EventArgs e)

{

//停止定时器;

timer1.Stop();

Bitmap bit = new Bitmap(System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width, System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height);

Graphics g = Graphics.FromImage(bit);

g.CopyFromScreen(new Point(0, 0), new Point(0, 0), bit.Size);

SaveFileDialog saveFileDialog = new SaveFileDialog();

saveFileDialog.Filter = "bmp|*.bmp|jpg|*.jpg|gif|*.gif";

if (saveFileDialog.ShowDialog() != DialogResult.Cancel)

{

bit.Save(saveFileDialog.FileName);

}

g.Dispose();

this.Visible = true;

}

}

}

//cellspacing :边框的宽度;

//蓝色背景;

-------数据集中的表简历关联关系;

可以找到关联关系:1.关联关系名,父表Id,子表Id;

dataSet11.Relations.Add("OrderDetails",

dataSet11.Tables["Orders"].Columns["OrderID"],

dataSet11.Tables["Order Details"].Columns["OrderID"]);

foreach (DataRow e in ds.Tables["dtext"].Rows)

{

DataRow f = e.GetParentRow("admin");//返回父表的行

// DataRow f = e.GetChildRows("admin");返回子表的行

Console.Write(f["列名"]);

}

----------------------:

D:\Company\CS\WebTabs\WinMediaPla

---------------------------------------------gridview导出到excel表格:(必须写VerifyRenderingInServerForm这个方法,添加 EnableEventValidation = "false")

protected void Button1_Click(object sender, EventArgs e)

{

GridView1.AllowPaging =false;

this.GridView1.AllowPaging = false;

this.GridView1.DataSource = ds;

this.GridView1.DataBind();

Response.Clear();

Response.BufferOutput = true;

//设定输出的字符集

Response.Charset = "GB2312";

//假定导出的文件名为.xls

Response.AppendHeader("Content-Disposition", "attachment;filename=caiwu.xls");

Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");

//设置导出文件的格式

Response.ContentType = "application/ms-excel";

//关闭ViewState

EnableViewState = false;

System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("ZH-CN", true);

System.IO.StringWriter stringWriter = new System.IO.StringWriter(cultureInfo);

System.Web.UI.HtmlTextWriter textWriter = new System.Web.UI.HtmlTextWriter(stringWriter);

this.GridView1.RenderControl(textWriter);

//把HTML写回浏览器

Response.Write(stringWriter.ToString());

Response.End();

this.GridView1.AllowPaging = true;

GridView1.AllowPaging = true;

this.GridView1.DataSource = ds;

this.GridView1.DataBind();

}

public override void VerifyRenderingInServerForm(Control control)

{

}

----------------------------------------------------excel表格导入:到dataset中;

this.GridView1.DataSource = null;

//string xlsPath = Server.MapPath("~/app_data/somefile.xls"); // 绝对物理路径

string xlsPath =@"C:\Users\dell\Desktop\今驰软件员工联系表.xls";

string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" +

"Extended Properties=Excel 8.0;" +

"data source=" + xlsPath;

// 查询语句

string sql = "SELECT * FROM [Sheet1$]";

DataSet ds = new DataSet();

OleDbDataAdapter da = new OleDbDataAdapter(sql, connStr);

da.Fill(ds);    // 填充DataSet

// 在这里对DataSet中的数据进行操作

// 输出,绑定数据

GridView1.DataSource = ds.Tables[0];

GridView1.DataBind();

-------------------------------------------------------灰色提示框,弹出框

function Button2_onclick() {

document.getElementById("guo").style["display"]='none';

}

function Button1_onclick() {

document.getElementById("guo").style.display='block';

}

function show(str)

{

document.getElementById("TextBox1").value=str;

}

// ]]>

</script>

</head>

<body id="modal">

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

<div>

<input id="Button1" type="button" value="button" onclick="return Button1_onclick()" />&nbsp;

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

</div>

<div id="guo" style=" width:100%;height:100%; position:absolute; display:none; filter:alpha(opacity=70); top: 0px;  background-color: #777;">

<center>

<div style="padding-top:100px; width:619px; height:315px;">

<div style="border:2px solid white; background-color:#95bce2; width:617px; height:27px;" >

<p style="padding-top:5px;">欢迎您</p>

</div>

<iframe name="ifr" src="../Col.aspx" style="width:618px; height:315px;" >

</iframe>

</div>

</center>

</div>

</form>

</body>

</html>

----------------------------------------------对称加密解密:密码是8位密码;

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.Security.Cryptography;

using System.IO;

using System.Text;

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

{

protected void Page_Load(object sender, EventArgs e)

{

}

///MD5加密

public string MD5Encrypt(string  pToEncrypt,  string  sKey)

{

DESCryptoServiceProvider  des  =  new  DESCryptoServiceProvider();

byte[]  inputByteArray  =  Encoding.Default.GetBytes(pToEncrypt);

des.Key  =  ASCIIEncoding.ASCII.GetBytes(sKey);

des.IV  =  ASCIIEncoding.ASCII.GetBytes(sKey);

MemoryStream  ms  =  new  MemoryStream();

CryptoStream  cs  =  new  CryptoStream(ms,  des.CreateEncryptor(),CryptoStreamMode.Write);

cs.Write(inputByteArray,  0,  inputByteArray.Length);

cs.FlushFinalBlock();

StringBuilder  ret  =  new  StringBuilder();

foreach(byte  b  in  ms.ToArray())

{

ret.AppendFormat("{0:X2}",  b);

}

ret.ToString();

return  ret.ToString();

}

///MD5解密

public string MD5Decrypt(string  pToDecrypt,  string  sKey)

{

DESCryptoServiceProvider  des  =  new  DESCryptoServiceProvider();

byte[]  inputByteArray  =  new  byte[pToDecrypt.Length  /  2];

for(int  x  =  0;  x  <  pToDecrypt.Length  /  2;  x++)

{

int  i  =  (Convert.ToInt32(pToDecrypt.Substring(x  *  2,  2),  16));

inputByteArray[x]  =  (byte)i;

}

des.Key  =  ASCIIEncoding.ASCII.GetBytes(sKey);

des.IV  =  ASCIIEncoding.ASCII.GetBytes(sKey);

MemoryStream  ms  =  new  MemoryStream();

CryptoStream  cs  =  new  CryptoStream(ms,  des.CreateDecryptor(),CryptoStreamMode.Write);

cs.Write(inputByteArray,  0,  inputByteArray.Length);

cs.FlushFinalBlock();

StringBuilder  ret  =  new  StringBuilder();

return  System.Text.Encoding.Default.GetString(ms.ToArray());

}

protected void Button1_Click(object sender, EventArgs e)

{

this.Label1.Text= MD5Encrypt(this.TextBox1.Text, "8lvbe4kE");

}

protected void Button2_Click(object sender, EventArgs e)

{

this.Label1.Text=MD5Decrypt(this.Label1.Text, "8lvbe4kE");

}

}

//--------------------------------------查询某数据库某个表:

SELECT * FROM CC ..AA

----------------------------------------sqlconnection状态连接;

---------------------------------------------调用webserviceweb服务;

添加引用;

<Services>

<asp:ServiceReference Path="~/getuser.asmx" />

</Services>

function Button1_onclick() {

WebService.Ceshi1(2,2,function (result) { document.getElementById("Text1").value = result; },null,null);

}

,只要页面不刷新就可以实现异步调用;

------------------------前台调用后台方法:(必须是静态方法)

1.using System.Web.Services;

2.  [WebMethod]

public static string get()

{

System.Threading.Thread.Sleep(5000);

return "guozfng";

}

3.<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">

4. function Button1_onclick() {

PageMethods.get(function (res) { document.getElementById("Text1").value = res; });

}

---------------------------ajax调用(不是异步的)

using System.Web.Script.Services;

using System.Web.Script.Services;(感觉添加不添加这条引用是无所谓的!)

后台方法必须是静态的;

[WebMethod]

public static string get1(string s,string s1)

{

return s +s1+ "我就是结果!";

}

前台调用:

无参的

function Button1_onclick() {

$.ajax({

//要用post方式

type: "Post",

//方法所在页面和方法名

url: "ajax2.aspx/get",

contentType: "application/json; charset=utf-8",

dataType: "json",

success: function(data) {

//返回的数据用data.d获取内容

alert(data.d);

},

error: function(err) {

alert(err);

}

});

}

有参数的

function Button2_onclick() {

$.ajax({

type: "Post",

url: "ajax2.aspx/get1",

//方法传参的写法一定要对,str为形参的名字,str2为第二个形参的名字

data: "{'s':'aa','s1':'bb'}",

contentType: "application/json; charset=utf-8",

dataType: "json",

success: function(data) {

//返回的数据用data.d获取内容

alert(data.d);

},

error: function(err) {

alert(err);

}

});

}

//--------------------------------验证文本框是够为空,js验证字符串是否是空格

function txtvalidation(txtName)

{

if(txtName.length<1)

{

alert("供应商类别设置名称不能为空!");

//document.getElementById("txtTypeName").focus();

return false;

}

else

{

for(i = 0; i < txtName.length; i ++)

{

if(txtName.substring(i, i + 1) != ' ')

return true;

}

alert("供应商类别设置名称不能为空!");

document.getElementById("txtTypeName").focus();

return false;

}

return true;

}

------------------------事务案例:

事务案例:

StringBuilder sb = new StringBuilder("begin transaction ");

sb.Append("use CC update [User] set UName='xiao' where UId=1");

sb.Append("use CD update [User] set UName='xiao' where UId=1");

…….

sb.Append("if @@ERROR = 0 begin commit transaction end else begin rollback transaction end");

--------------------------------:查询数据库中的表的数量

USE SJCL1

SELECT * from sysobjects where xtype = 'u'  order by name

-------------------------自增id,查询最大值

public static int getGysMaxBH()

{

int i = 1;

string sql = "select max(BH) as BH from GYS";

using (SqlDataReader dr = DBHelperXT.GetReader(sql))

{

if (dr.Read())

{

if (dr["BH"].ToString() != "")

{

i += Convert.ToInt32(dr["BH"]);

}

}

}

return i;

}

--------------------------------------sb.ToString().TrimEnd(',');去掉最后一个逗号

-------------

<a href="javascript:alert('guozefng')";>ggggggggggg</a>

<a href="#" onclick="alert('111111')";>ggggggggggg</a>

----------------------------表复制或表备份有两种形式

SELECT * INTO aa from bb;(自动创建表)

insert into aa select * from b

--------------------合并两个表的数据

insert   into   B   select   *   from     A   where   not   exists(select   1   from   B   where   A.id=B.id)

CrystalReportViewer1.Dispose();6222020200120983792水晶报表:添加报表引擎:using CrystalDecisions.CrystalReports.Engine;

string title = string.Empty;

title = "材料信息管理";

XtVar xt = Commond.GetXVar();

DataTable dtable = null;//单据数据

dtable = CaiLiaoXinxiManager.GetAllTable();

PageBean page = new PageBean();

page.CurrentPage = 1;

page.PageSize = 10;

report = new ReportDocument();

report.Load(Server.MapPath("../../Report/CaiLiaoXinXiReport.rpt"));

report.SetDataSource(dtable);

report.SetParameterValue("reportTitle", title);//设置单据标题

CrystalReportViewer1.DisplayGroupTree = false;

CrystalReportViewer1.HasCrystalLogo = false;

CrystalDecisions.Shared.ReportPageRequestContext rprc = new CrystalDecisions.Shared.ReportPageRequestContext();

int totalPCount = report.FormatEngine.GetLastPageNumber(rprc);

CrystalReportViewer1.ReportSource = report;

------------- 在产生错误的文件的顶部添加一条“Debug=true”指令。例如:

----------- protected void Page_UnLoad(object sender, EventArgs e)

{

//建立完页面时,释放报表文档资源

this.Dispose();

report.Close();

report.Dispose();

this.Dispose();

this.ClearChildState();

}

----------------------using CrystalDecisions.CrystalReports.Engine;

要想页面回发dataset数据得以保存,将dataset设置为静态;

----------------------------------------水晶报表案例:

using CrystalDecisions.CrystalReports.Engine;

ds = new DataSet();

cn = new SqlConnection("data source=DELL-PC\\AA;initial catalog=CC;uid=sa;pwd=sa");

da = new SqlDataAdapter("select * from AA", cn);

da.Fill(ds, "aaa");

rdoc = new ReportDocument();

rdoc.Load(Server.MapPath("report/CrystalReport.rpt"));

rdoc.SetDataSource(ds.Tables["aaa"]);

rdoc.SetParameterValue("Title", "sdfs");

//CrystalReportViewer1.DisplayGroupTree = false;

//CrystalReportViewer1.HasCrystalLogo = false;

//CrystalDecisions.Shared.ReportPageRequestContext rprc = new CrystalDecisions.Shared.ReportPageRequestContext();

//int totalPCount = rdoc.FormatEngine.GetLastPageNumber(rprc);

this.CrystalReportViewer1.ReportSource = rdoc;

---------------------------------------加密狗;

ViewType="OutlookGroupBy"//去除边框,和显示单选,将这两条记录删除;

RowSelectorsDefault="Yes"

分页效果

<pager allowpaging="True"  PageSize="2"  StyleMode="QuickPages" pattern="页码:[currentpageindex]/[pagecount]   每页:[pagesize]  [page:1:首页]  [prev]  [default]  [next] [page:[pagecount]:末页]   &lt;input id=PageNum size=2 type=text /&gt;&lt;input id=btgo type=button value=go onclick=javascript:goPage(event) /&gt;" AllowCustomPaging="True" ChangeLinksColor="True" NextText="下一页" PrevText="上一页">

</pager>

//添加这个函数,表示go按钮是可用的;

function goPage(event)

{

igtbl_pageGrid(event,'UltraWebGrid1',document.getElementById("PageNum").value);

}

---------------------------------------------

PageBean page=new PageBean();

page.CurrentPage=pageNumber;

PageIndex = pageNumber;

this.UltraWebGrid2.DataSource = GongSiManager.getGongSiAllByPageIndex(page);

this.UltraWebGrid2.DisplayLayout.Pager.PageCount = page.TotalPage;

this.UltraWebGrid2.DisplayLayout.Pager.PageSize = page.PageSize;

this.UltraWebGrid2.DisplayLayout.Pager.CurrentPageIndex = pageNumber;

this.UltraWebGrid2.DataBind();

--------------------------------------------------