<table cellSpacing="0" cellPadding="0" width="609" height="470" align="center" border="0">javascript
<link href="../Css/default.css" rel="stylesheet" type="text/css">css
<td width="200" align="left" valign="top" bgcolor="#e2eefe">--html
-----------數據綁定java
BillBusiness bill = new BillBusiness();node
DataSet ds = new DataSet();jquery
ds=bill.GetBillEmployees();web
drdlReceiveBillPerson.DataSource = ds.Tables[0]; ajax
drdlReceiveBillPerson.DataTextField = "Employee";算法
drdlReceiveBillPerson.DataBind();sql
-------------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
一、membership簡介
二、membership在sql server中的設置
三、配置web.config
四、建立用戶CreateUserWizard控件
五、用戶登陸login控件
六、顯示當前用戶的名稱LoginName控件
七、檢測用戶的身份驗證狀態的LoginStatus控件
八、爲不一樣類別用戶呈現不一樣內容的LoginView控件
九、更改密碼的ChangePassword控件
十、自助找回密碼的PasswordRecovery控件
十一、總結
-------------------------後臺提示框
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(回發)後,頁面通常定位在整個網頁的頂部!但咱們在實際項目中常常須要,回發後能定位到本身剛剛點擊提交按鈕位置,那這種狀況如何實現呢,下面介紹三種實現些功能的方法
1、應用程序級設置:在web.config中增長一個pages節點
<pages maintainScrollPositionOnPostBack="true">
2、頁面級設置:在aspx頁面上進行設置,在頁面的page指令中增長屬性
<@page MaintainScrollPositionOnPostback="true"
3、在後臺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 提供的新功能,它們之間的區別在於:
一、 Server.Transfer - 用於把處理的控制權從一個頁面轉移到另外一個頁面,在轉移的過程當中,沒有離開服務器,內部控件(如:request, session 等)的保存的信息不變,所以,你能從頁面 A 跳到頁面 B 而不會丟失頁面 A 中收集的用戶提交信息。此外,在轉移的過程當中,瀏覽器的 URL 欄不變。
二、Response.Redirect - 發送一個 HTTP 響應到客戶端,告訴客戶端跳轉到一個新的頁面,客戶端再發送跳轉請求到服務器。使用此方法時,將沒法保存全部的內部控件數據,頁面 A 跳轉到頁面 B,頁面 B 將沒法訪問頁面 A 中 Form 提交的數據。
三、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()" />
<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]:末頁] <input id=PageNum size=2 type=text /><input id=btgo type=button value=go onclick=javascript:goPage(event) />" 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();
--------------------------------------------------