ASP.NET筆記(本人收集整理)
来源:互联网 发布:淘宝店铺宝贝视频教程 编辑:程序博客网 时间:2024/06/06 01:26
ASP.NET筆記
字符轉日期
string strDate;
DateTime FmtDate=Convert.ToDateTime(this.TxtGetDate.Text);
strDate = FmtDate.ToString("yyyy/MM/dd hh:mm:ss");
今天日期
string strDate=null;
strDate = DateTime.Now.ToShortDateString();
簡繁轉換
'源串
dim strText as string ="要?往?片机的字符串"
'要導出的字
dim arrbytOut() as byte
'??
arrbytOut = System.Text.Encoding.GetEncoding("GB2312").GetBytes(strText)
2》
string tmp = "";
byte[] tmpBy = System.Text.Encoding.UTF8.GetBytes(tmp);
byte[] newBy=System.Text.Encoding.Convert(System.Text.Encoding.UTF8,System.Text.Encoding.Default,tmpBy);
3》
改webconfig不就行了
<?xml version="1.0" encoding="utf-8" ?>
<globalization requestEncoding="utf-8" responseEncoding="utf-8" />
改成
<?xml version="1.0" encoding="gb2312" ?>
<globalization requestEncoding="gb2312" responseEncoding="gb2312" />
文本框
Asp.net中TextBox的TextChanged为什么不起作用?
把AutoPostBack设置为true, 也要敲一下回车才能激活事件.
在DropDownList中邦定了数据源后,我还要追一个item?
Dropdwonlist1.Items.Insert(0,new ListItem("--请您选择--",""));
或
Dropdwonlist1.Items.Insert(0,new ListItem("--请选择--","-1"));
實例:
在ASP.NET 2.0中,可以在数据绑定时,通过设置DropDownList的AppendDataBoundItems属性为true,在数据绑定之前添加一个新的项目,并且这个新加的项目会保存在ViewState之中。下面就是一个实现的例子:
C#代码
<%...@ Page Language="C#" %>
<%...@ Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">...
ICollection CreateDataSource()
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new DataColumn("id", typeof(Int32)));
dt.Columns.Add(new DataColumn("text", typeof(string)));
for (int i = 0; i < 6; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "列表项目 " + i.ToString();
dt.Rows.Add(dr);
}
DataView dv = new DataView(dt);
return dv;
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("<li>DropDownList1 您选择的项目:" + DropDownList1.SelectedValue
+ " ; " + DropDownList1.SelectedItem.Text);
Response.Write("<li>DropDownList2 您选择的项目:" + DropDownList2.SelectedValue
+ " ; " + DropDownList2.SelectedItem.Text);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.AppendDataBoundItems = true;
DropDownList1.Items.Add(new ListItem("-- 请选择一个选择项 --", ""));
DropDownList2.DataSource = DropDownList1.DataSource = CreateDataSource();
DropDownList2.DataTextField = DropDownList1.DataTextField = "text";
DropDownList2.DataValueField = DropDownList1.DataValueField = "id";
DropDownList1.DataBind();
DropDownList2.DataBind();
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>DropDownList 补充例子</title>
</head>
<body>
<form id="form1" runat="server">
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="请选择" Value=""></asp:ListItem>
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="得到选择的值" OnClick="Button1_Click" />
</form>
</body>
</html>
VB.NET代码
<%...@ Page Language="VB" AutoEventWireup="true" %>
<%...@ Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">...
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Response.Write("<li>DropDownList1 您选择的项目:" + DropDownList1.SelectedValue + _
" ; " + DropDownList1.SelectedItem.Text)
Response.Write("<li>DropDownList2 您选择的项目:" + DropDownList2.SelectedValue + _
" ; " + DropDownList2.SelectedItem.Text)
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
If Not IsPostBack Then
DropDownList1.AppendDataBoundItems = True
DropDownList1.Items.Add(New ListItem("-- 请选择一个选择项 --", ""))
DropDownList2.DataSource = CreateDataSource()
DropDownList1.DataSource = CreateDataSource()
DropDownList2.DataTextField = "text"
DropDownList1.DataTextField = "text"
DropDownList2.DataValueField = "id"
DropDownList1.DataValueField = "id"
DropDownList1.DataBind()
DropDownList2.DataBind()
End If
End Sub
Function CreateDataSource() As ICollection
Dim dt As DataTable = New DataTable()
Dim dr As DataRow
dt.Columns.Add(New DataColumn("id", GetType(System.Int32)))
dt.Columns.Add(New DataColumn("text", GetType(String)))
For i As Integer = 0 To 6
dr = dt.NewRow()
dr(0) = i
dr(1) = "列表项目 " + i.ToString()
dt.Rows.Add(dr)
Next
Dim dv As DataView = New DataView(dt)
Return dv
End Function
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>DropDownList 补充例子</title>
</head>
<body>
<form id="form1" runat="server">
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="请选择" Value=""></asp:ListItem>
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="得到选择的值" OnClick="Button1_Click" />
</form>
</body>
</html>
另外,还可以使用下面的方法添加:
protected void DropDownList1_DataBound(object sender, EventArgs e)
{
DropDownList1.Items.Insert(0,new ListItem("--请选择--", ""));
}
在ASP.NET中用三个DropDownList控件方便的选择年月日【原创】
aspx页面上有三个DropDownList控件,
DropDownList1 表示年,DropDownList2表示月,DropDownList3表示天;
注意用将这三个DropDownList控件的AutoPostBack属性设为True。
用户可以方便地选择年月日,并且每月的日期会随着用户选择不同的年,月而发生相应的变化
其后台cs文件代码如下:
private void Page_Load(object sender, System.EventArgs e)
{
DateTime tnow=DateTime.Now;//现在时间
ArrayList AlYear=new ArrayList();
int i;
for(i=2002;i<=2010;i++)
AlYear.Add(i);
ArrayList AlMonth=new ArrayList();
for(i=1;i<=12;i++)
AlMonth.Add(i);
if(!this.IsPostBack )
{
DropDownList1.DataSource=AlYear;
DropDownList1.DataBind();//绑定年
//选择当前年
DropDownList1.SelectedValue=tnow.Year.ToString();
DropDownList2.DataSource=AlMonth;
DropDownList2.DataBind();//绑定月
//选择当前月
DropDownList2.SelectedValue=tnow.Month.ToString();
int year,month;
year=Int32.Parse(DropDownList1.SelectedValue);
month=Int32.Parse(DropDownList2.SelectedValue);
BindDays(year,month);//绑定天
//选择当前日期
DropDownList3.SelectedValue=tnow.Day.ToString();
}
}
//判断闰年
private bool CheckLeap(int year)
{
if((year%4==0)&&(year%100!=0)||(year%400==0))
return true;
else return false;
}
//绑定每月的天数
private void BindDays( int year,int month)
{ int i;
ArrayList AlDay=new ArrayList();
switch(month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
for(i=1;i<=31;i++)
AlDay.Add(i);
break;
case 2:
if (CheckLeap(year))
{for(i=1;i<=29;i++)
AlDay.Add(i);}
else
{for(i=1;i<=28;i++)
AlDay.Add(i);}
break;
case 4:
case 6:
case 9:
case 11:
for(i=1;i<=30;i++)
AlDay.Add(i);
break;
}
DropDownList3.DataSource=AlDay;
DropDownList3.DataBind();
}
//选择年
private void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
{
int year,month;
year=Int32.Parse(DropDownList1.SelectedValue);
month=Int32.Parse(DropDownList2.SelectedValue);
BindDays(year,month);
}
//选择月
private void DropDownList2_SelectedIndexChanged(object sender, System.EventArgs e)
{
int year,month;
year=Int32.Parse(DropDownList1.SelectedValue);
month=Int32.Parse(DropDownList2.SelectedValue);
BindDays(year,month);
}
如何给DropDownList控件添加边框[整理]
<span style="border-right: gray 1px solid; border-top: gray 1px solid;
border-left: gray 1px solid; border-bottom: gray 1px solid;">
<asp:DropDownList ID="ddlSearch" runat="server">
<asp:ListItem Value="title">标题</asp:ListItem>
<asp:ListItem Value="content">内容</asp:ListItem>
<asp:ListItem Value="author">作者</asp:ListItem>
</asp:DropDownList>
</span>
Asp.Net Table控件动态生成表格操作实例(代码调试通过)
<form id="Form1" method="post" runat="server">
<asp:Label id="Label1" style="Z-INDEX: 101; LEFT: 256px; POSITION:
absolute; TOP: 40px" runat="server">Asp.Net Table控件动态生成表格操作实例</asp:Label>
<asp:Button id="Button1" style="Z-INDEX: 105; LEFT: 272px; POSITION:
absolute; TOP: 120px" runat="server"
Text="生 成"></asp:Button>
<asp:Table id="Table1" style="Z-INDEX: 104; LEFT: 272px; POSITION:
absolute; TOP: 160px" runat="server"
GridLines="Both"></asp:Table>
<asp:DropDownList id="DropDownList2" style="Z-INDEX: 103; LEFT:
344px; POSITION: absolute; TOP: 88px"
runat="server">
<asp:ListItem Value="1">1列</asp:ListItem>
<asp:ListItem Value="2">2列</asp:ListItem>
<asp:ListItem Value="3">3列</asp:ListItem>
<asp:ListItem Value="4">4列</asp:ListItem>
<asp:ListItem Value="5">5列</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList id="DropDownList1" style="Z-INDEX: 102; LEFT:
280px; POSITION: absolute; TOP: 88px"
runat="server">
<asp:ListItem Value="1">1行</asp:ListItem>
<asp:ListItem Value="2">2行</asp:ListItem>
<asp:ListItem Value="3">3行</asp:ListItem>
<asp:ListItem Value="4">4行</asp:ListItem>
<asp:ListItem Value="5">5行</asp:ListItem>
</asp:DropDownList>
</form>
.aspx.cs
private void Button1_Click(object sender, System.EventArgs e)
{
int numrows;
int numcells;
int i=0;
int j=0;
int row=0;
TableRow r;
TableCell c;
//产生表格
numrows=Convert.ToInt32(DropDownList1.SelectedValue);
numcells=Convert.ToInt32(DropDownList2.SelectedValue);
for(i=0;i<numrows;i++)
{
r=new TableRow();
if(row/2!=0)
{
r.BorderColor=Color.Red;
}
row+=1;
for(j=0;j<numcells;j++)
{
c=new TableCell();
c.Controls.Add(new LiteralControl
("row"+j+",cell"+i));
r.Cells.Add(c);
}
Table1.Rows.Add(r);
}
}
DropDownList 控件 DataTextField 和 DataValueField 分开绑定
<SCRIPT runat="server">
Sub Page_Load
If Not Page.IsPostBack Then
Dim URLs = New SortedList()
URLs.Add("Google", "http://www.google.com")
URLs.Add("MSN", "http://search.msn.com")
URLs.Add("Yahoo", "http://www.yahoo.com")
URLs.Add("Lycos", "http://www.lycos.com")
URLs.Add("AltaVista", "http://www.altavista.com")
URLs.Add("Excite", "http://www.excite.com")
'-- Bind SortedList to controls
RadioButtons.DataSource = URLs
RadioButtons.DataTextField = "Key"
RadioButtons.DataValueField = "Value"
RadioButtons.DataBind()
CheckBoxes.DataSource = URLs
CheckBoxes.DataTextField = "Key"
CheckBoxes.DataValueField = "Value"
CheckBoxes.DataBind()
DropDownList.DataSource = URLs
DropDownList.DataTextField = "Key"
DropDownList.DataValueField = "Value"
DropDownList.DataBind()
ListBox.DataSource = URLs
ListBox.DataTextField = "Key"
ListBox.DataValueField = "Value"
ListBox.DataBind()
End If
End Sub
</SCRIPT>
使用列表控件的 SelectedIndex 和 SelectedItem 属性访问有关所选项的信息。
示例
// The index:
int ListItemIndex;
// Value of the item:
string ListItemValue;
ListItemIndex = ListBox1.SelectedIndex;
ListItemValue = ListBox1.SelectedItem.Value.ToString();
在ASP.NET使用javascript的一点小技巧
我们在进行ASP.NET开发时,经常会用到一些javascript脚本,比如:
private void Button1_Click(object sender, System.EventArgs e)
{
Response.Write( "") ;
}
经常是重复的书写这些脚本,如果我们能做成一个相应的函数就好了,直接就可以拿来使用。很多人都有自己的一些javascript的函数,但是大部分向这样的:
///
/// 服务器端弹出alert对话框
///
/// 提示信息,例子:"请输入您姓名!"
/// Page类
public void Alert(string str_Message,Page page)
{
if(!page.IsStartupScriptRegistered ("msgOnlyAlert"))
{
page.RegisterStartupScript("msgOnlyAlert","");
}
}
但是,用的时候,每次都要继承这个类,用起来还是有些麻烦,如果函数是静态的函数,类是静态的类的话,我们不要继承就可以使用。但是我们怎么写呢?
看看这段代码
#region public static void MessageBox( Page page, string msg )
///
/// 弹出对话框
///
/// 当前页面的指针,一般为this
/// 消息
public static void MessageBox( Page page, string msg )
{
StringBuilder StrScript = new StringBuilder();
StrScript.Append( "" );
if ( ! page.IsStartupScriptRegistered( "MessageBox" ) )
{
page.RegisterStartupScript( "MessageBox", StrScript.ToString() );
}
}
#endregion
这样的话我们就能方便使用很多已有的js脚本。
PS:其实很多常用的方法都能写成静态函数进行调用的。偶再附几个例子作为一个参考。
MD5加密:
///
/// MD5 Encrypt
///
/// text
/// md5 Encrypt string
public string MD5Encrypt(string strText)
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] result = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(strText));
return System.Text.Encoding.Default.GetString(result);
}
取指定长度的随机数:
#region public static string GetRandNum( int randNumLength )
///
/// 取得随机数
///
/// 随机数的长度
///
public static string GetRandNum( int randNumLength )
{
System.Random randNum = new System.Random( unchecked( ( int ) DateTime.Now.Ticks ) );
StringBuilder sb = new StringBuilder( randNumLength );
for ( int i = 0; i < randNumLength; i++ )
{
sb.Append( randNum.Next( 0, 9 ) );
}
return sb.ToString();
}
#endregion
全局變量,在單擊按鈕會丟失值?:
public static string AddState;即可
asp.net页面保持滚动条的位置
在asp.net中,postback非常常用。最近发现一个小技巧,可以在postback后保持滚动条的位置。
非常简单。在<%@ Page %>中加入一个属性:
SmartNavigation="true"
这样在IE中可以做到保持滚动条位置,并且页面不会闪。
如果还要Firfox支持,则可以在Page_Load()中加入:
Page.MaintainScrollPositionOnPostBack = true;
这个属性是.Net2.0的,我把2个方法同时使用,经测试可以满足要求。
用ASP.NET向Javascript传递变量
如果字符变量是字符型像alert()等要这样用alert("<%=Num%>");
还有Num一定要是public申明
动易如何解决下拉菜单会被swf文件遮住的问题?
问题:在下拉菜单下面添加了swf文件后,下拉菜单会被swf文件遮住,如何解决?
如:
解决:要让下拉菜单显示在swf前面,在调用swf的代码中,加上“<param name="wmode" value="Opaque"> ”代码即可。
举例:
<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0' width="772" height="150"><param name='movie' value='http://www.powereasy.net/Express_AD/images/cms_red2.swf'><param name='quality' value='autohigh'><param name="wmode" value="Opaque"><embed src='http://www.powereasy.net/Express_AD/images/cms_red2.swf' quality='autohigh' width="772" height="150" pluginspage='http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash' type='application/x-shockwave-flash'></embed></object>
效果:
说明:
Flash在输出时的Html选项窗口中,有个“窗口模式”的选项,如下图所示:
以下是Flash的帮助文档对“窗口模式”的相关说明:
选择"窗口模式"选项,该选项控制 object 和 embed 标记中的 HTML wmode 属性。窗口模式修改 Flash 内容边框或虚拟窗口与 HTML 页中内容的关系,如下表所示:
"窗口"不会在 object 和 embed 标记中嵌入任何窗口相关属性。Flash 内容的背景不透明并使用 HTML 背景颜色。HTML 无法呈现在 Flash 内容的上方或下方。这是默认设置。
"不透明无窗口"将 Flash 内容的背景设置为不透明,并遮蔽 Flash 内容下面的任何内容。"不透明无窗口"将 HTML 内容显示在 Flash 内容的上方或上面。
"透明无窗口"将 Flash 内容的背景设置为透明。此选项使 HTML 内容显示在 Flash 内容的上方和下方。
注意在某些情况下,当 HTML 图像复杂时,透明无窗口模式的复杂呈现方式可能会导致动画速度变慢。
若选择了“窗口”,则输出的Html代码中没有“<param name="wmode" value="***">”代码。
若选择了“不透明无窗口”,则输出的Html代码中有“<param name="wmode" value="opaque"> ”
若选择了“透明无窗口”,则输出的Html代码中有“<param name="wmode" value="transparent"> ”
即:
"opaque" 表示在无窗口状态动画背景不透明。
"transparent"表示在无窗口状态动画背景透明。
DataGrid控件查詢問題(當數據綁定到datagrid控件後,翻頁到後一頁,當前就不是第一頁了,就會發生此種情況)
如果控件定義分頁後,(查詢出錯,提示currpageindex大於PageCount,或小於0),注意查詢在datagrid控件綁定前,使控件CurrentPageIndex=0,還原到第一頁
如:
strSql = "SELECT ask_productid as 請購單號,ask_department as 請購部門,ask_askdate as 請購日期,ask_staff as 請購人,ask_submitstate as 提交狀態,ask_finishstate as 完成狀態,ask_finishdate as 完成日期,ask_overstate as 結束狀態,ask_assignstate as 分發狀態";
strSql = strSql + " from AskProduct_Master ";
strSql = strSql + " where Ask_department like '" + (string)Session["Department"] + "%'";
strSql = strSql + " And Ask_productid='" + TxtAskBill.Text.Trim() + "'";
SqlDataAdapter DaSearch = new SqlDataAdapter(strSql, Conn);
DaSearch.Fill(myDs);
GridM.DataSource = myDs;
//控件綁定前,還原
GridM.CurrentPageIndex = 0;
GridM.DataBind();
正則表達式
[1-9]/d* 不是0開頭的正整數
-?[^/D]+/.?[^/D]+ 正負小數
怎样用正则表达式截取截取小数点前面的值。
String str1 = "33.3";
String regex = "([^.]*).*";
String str2 = str1.replaceAll(regex, "$1");
在分頁中行數未滿的行加入空行填充
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
//在相應表中加入空行
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
NewMethod();
}
private void NewMethod()
{
string connstr = "server=.;database=Northwind;uid=sa;pwd=wz";
string strsql = "select top 25 * from Orders";
SqlConnection cn = new SqlConnection(connstr);
cn.Open();
SqlDataAdapter da = new SqlDataAdapter(strsql, cn);
DataSet ds = new DataSet();
da.Fill(ds);
cn.Close();
DataTable dt = ds.Tables[0];
int mypage = dt.Rows.Count % Grid.PageSize;
for (int i = mypage; i < Grid.PageSize; i++)
{
DataRow dr = dt.NewRow();
dr[0] = DBNull.Value;
dt.Rows.Add(dr);
}
Grid.DataSource = dt;
Grid.DataBind();
}
protected void Grid_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
{
Grid.CurrentPageIndex = e.NewPageIndex;
NewMethod();
}
}
如何控制水晶报表每页只有25行
在水晶报表里面操作,操作如下:
1、右键单击“详细数据”节的灰色横头,选择“节专家”,进入“节专家”对话框;
2、在“公用”选项卡,选中“在后面页新建页”复选框;
3、单击后面的“x+2”按钮,进入“公式工作室 - 格式公式编辑器”对话框;
4、输入“RecordNumber mod 25 = 0”,并单击左上角的“保存并关闭”按钮。
注意:是 Crystal Report 语法。
/// 25 是你想一页想有有多少条纪录数
asp及asp.net的urlencode问题
我想在asp中加一个链接,指向asp.net网页,但asp.net的网址是经过 HttpUtility.UrlEncode变形和HttpUtility.UrlDecode变回的,而asp的server.urlencode却产 生不了和HttpUtility.UrlEncode一样的编码,请问有没有解决办法
补充:原来asp.net的是"web.aspx?str="+HttpUtility.UrlEncode(str)
和HttpUtility.UrlDecode(Request.QueryString["str"].ToString().Trim())
而asp的是"web.aspx?str="+server.urlencode(str)
结果:已经找出解决方法,在asp提交端"web.aspx?str="+server.urlEncode( server.URLpathencode(str))
asp.net提交端为:"web.aspx?str="+ HttpUtility.UrlEncode( str,System.Text.Encoding.GetEncoding("gb2312"))
asp.net接收端为:str= HttpUtility.UrlDecode(Request.QueryString["str"].ToString().Trim(),System.Text.Encoding.GetEncoding("gb2312"))
其中str为需要传递的变量
IIS6中破除ASP上傳200KB的限制
一、修改IIS设置,允许直接编辑配置数据库,如下图所示:
screen.width-400)this.width=screen.width-400" border=0 dypop="按此在新窗口浏览图片">
二、先在服务里关闭iis admin service服务
找到windows/system32/inesrv/下的metabase.xml,
打开,找到ASPMaxRequestEntityAllowed 把他修改为需要的值,默认为204800,即200K 把它修改为你所需的大小即可。如:51200000(50M)
然后重启iis admin service服务
Visual C#常用函数和方法集汇总
1、DateTime 数字型
System.DateTime currentTime=new System.DateTime();
1.1 取当前年月日时分秒
currentTime=System.DateTime.Now;
1.2 取当前年
int 年=currentTime.Year;
1.3 取当前月
int 月=currentTime.Month;
1.4 取当前日
int 日=currentTime.Day;
1.5 取当前时
int 时=currentTime.Hour;
1.6 取当前分
int 分=currentTime.Minute;
1.7 取当前秒
int 秒=currentTime.Second;
1.8 取当前毫秒
int 毫秒=currentTime.Millisecond;
(变量可用中文)
1.9 取中文日期显示——年月日时分
string strY=currentTime.ToString("f"); //不显示秒
1.10 取中文日期显示_年月
string strYM=currentTime.ToString("y");
1.11 取中文日期显示_月日
string strMD=currentTime.ToString("m");
1.12 取当前年月日,格式为:2003-9-23
string strYMD=currentTime.ToString("d");
1.13 取当前时分,格式为:14:24
string strT=currentTime.ToString("t");
2、字符型转换 转为32位数字型
Int32.Parse(变量) Int32.Parse("常量")
3、 变量.ToString()
字符型转换 转为字符串
12345.ToString("n"); //生成 12,345.00
12345.ToString("C"); //生成 ¥12,345.00
12345.ToString("e"); //生成 1.234500e+004
12345.ToString("f4"); //生成 12345.0000
12345.ToString("x"); //生成 3039 (16进制)
12345.ToString("p"); //生成 1,234,500.00%
4、变量.Length 数字型
取字串长度:
如: string str="中国";
int Len = str.Length ; //Len是自定义变量, str是求测的字串的变量名
5、字码转换 转为比特码
System.Text.Encoding.Default.GetBytes(变量)
如:byte[] bytStr = System.Text.Encoding.Default.GetBytes(str);
然后可得到比特长度:
len = bytStr.Length;
6、System.Text.StringBuilder("")
字符串相加,(+号是不是也一样?)
如:
System.Text.StringBuilder sb = new System.Text.StringBuilder("");
sb.Append("中华");
sb.Append("人民");
sb.Append("共和国");
7、变量.Substring(参数1,参数2);
截取字串的一部分,参数1为左起始位数,参数2为截取几位。
如:string s1 = str.Substring(0,2);
8、取远程用户IP地址
String user_IP=Request.ServerVariables["REMOTE_ADDR"].ToString();
9、穿过代理服务器取远程用户真实IP地址:
if(Request.ServerVariables["HTTP_VIA"]!=null){
string user_IP=Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}else{
string user_IP=Request.ServerVariables["REMOTE_ADDR"].ToString();
}
10、存取Session值
Session["变量"];
如,赋值:
Session["username"]="小布什";
取值:
Object objName=Session["username"];
String strName=objName.ToString();
清空:
Session.RemoveAll();
11、用超链接传送变量
String str=Request.QueryString["变量"];
如在任一页中建超链接:<a href=Edit.aspx?fbid=23>点击</a>
在Edit.aspx页中取值:String str=Request.QueryString["fdid"];
12、创建XML文档新节点
DOC对象.CreateElement("新建节点名");
13、将新建的子节点加到XML文档父节点下
父节点.AppendChild(子节点);
14、 删除节点
父节点.RemoveChild(节点);
15、向页面输出:Response
Response.Write("字串");
Response.Write(变量);
跳转到URL指定的页面:
Response.Redirect("URL地址");
16、查指定位置是否空字符
char.IsWhiteSpce(字串变量,位数)——逻辑型;
如:
string str="中国 人民";
Response.Write(char.IsWhiteSpace(str,2)); //结果为:True, 第一个字符是0位,2是第三个字符。
17、查字符是否是标点符号
char.IsPunctuation('字符') --逻辑型
如:
Response.Write(char.IsPunctuation('A')); //返回:False
18、把字符转为数字,查代码点,注意是单引号。
(int)'字符'
如:
Response.Write((int)'中'); //结果为中字的代码:20013
19、把数字转为字符,查代码代表的字符:(char)代码
如:
Response.Write((char)22269); //返回“国”字。
20、 清除字串前后空格: Trim()
21、字串替换
字串变量.Replace("子字串","替换为")
如:
string str="中国";
str=str.Replace("国","央"); //将国字换为央字
Response.Write(str); //输出结果为“中央”
再如:(这个非常实用)
string str="这是<script>脚本";
str=str.Replace("<","<font><</font>"); //将左尖括号替换为<font> 与 < 与 </font> (或换为<,但估计经XML存诸后,再提出仍会还原)
Response.Write(str); //显示为:“这是<script>脚本”
如果不替换,<script>将不显示,如果是一段脚本,将运行;而替换后,脚本将不运行。
这段代码的价值在于:你可以让一个文本中的所有HTML标签失效,全部显示出来,保护你的具有交互性的站点。
具体实现:将你的表单提交按钮脚本加上下面代码:
string strSubmit=label1.Text; //label1是你让用户提交数据的控件ID。
strSubmit=strSubmit.Replace("<","<font><</font>");
然后保存或输出strSubmit。
用此方法还可以简单实现UBB代码。
22、取i与j中的最大值:Math.Max(i,j)
如 int x=Math.Max(5,10); // x将取值 10
加一点吧 23、字串对比......
23、字串对比一般都用: if(str1==str2){ } , 但还有别的方法:
(1)、
string str1; str2
//语法: str1.EndsWith(str2); __检测字串str1是否以字串str2结尾,返回布尔值.如:
if(str1.EndsWith(str2)){ Response.Write("字串str1是以"+str2+"结束的"); }
(2)、
//语法:str1.Equals(str2); __检测字串str1是否与字串str2相等,返回布尔值,用法同上.
(3)、
//语法 Equals(str1,str2); __检测字串str1是否与字串str2相等,返回布尔值,用法同上.
24、查找字串中指定字符或字串首次(最后一次)出现的位置,返回索引值:IndexOf() 、LastIndexOf(), 如:
str1.IndexOf("字"); //查找“字”在str1中的索引值(位置)
str1.IndexOf("字串");//查找“字串”的第一个字符在str1中的索引值(位置)
str1.IndexOf("字串",3,2);//从str1第4个字符起,查找2个字符,查找“字串”的第一个字符在str1中的索引值(位置)
25、在字串中指定索引位插入指定字符:Insert() ,如:
str1.Insert(1,"字");在str1的第二个字符处插入“字”,如果str1="中国",插入后为“中字国”;
26、在字串左(或右)加空格或指定char字符,使字串达到指定长度:PadLeft()、PadRight() ,如:
<%
string str1="中国人";
str1=str1.PadLeft(10,'1'); //无第二参数为加空格
Response.Write(str1); //结果为“1111111中国人” , 字串长为10
%>
27、从指定位置开始删除指定数的字符:Remove()
28.反转整个一维Array中元素的顺序。
har[] charArray = "abcde".ToCharArray();
Array.Reverse(charArray);
Console.WriteLine(new string(charArray));
29.判断一个字符串中的第n个字符是否是大写
string str="abcEEDddd";
Response.Write(Char.IsUpper(str,3));
C# 开发和使用中的33个技巧
1.怎样定制VC#DataGrid列标题?
DataGridTableStyle dgts = new DataGridTableStyle();
dgts.MappingName = "myTable"; //myTable为要载入数据的DataTable
DataGridTextBoxColumn dgcs = new DataGridTextBoxColumn();
dgcs.MappingName = "title_id";
dgcs.HeaderText = "标题ID";
dgts.GridColumnStyles.Add(dgcs);
。。。
dataGrid1.TableStyles.Add(dgts);
2.检索某个字段为空的所有记录的条件语句怎么写?
...where col_name is null
3.如何在c# Winform应用中接收回车键输入?
设一下form的AcceptButton.
4.比如Oracle中的NUMBER(15),在Sql Server中应是什么?
NUMBER(15):用numeric,精度15试试。
5.sql server的应用like语句的存储过程怎样写?
select * from mytable where haoma like ‘%’ + @hao + ‘%’
6.vc# winform中如何让textBox接受回车键消息(假没没有按钮的情况下)?
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if(e.KeyChar != (char)13)
return;
else
//do something;
}
7.为什么(Int32)cmd.ExecuteScalar()赋值给Int32变量时提示转换无效?
Int32.Parse(cmd.ExecuteScalar().ToString());
8.DataSource为子表的DataGrid里怎样增加一个列以显示母表中的某个字段?
在子表里手动添加一个列。
DataColumn dc = new DataColumn("newCol", Type.GetType("System.String"));
dc.Expression = "Parent.parentColumnName";
dt.Columns.Add(dc); //dt为子表
9.怎样使DataGrid显示DataTable中某列的数据时只显示某一部分?
select ..., SUBSTR(string, start_index, end_index) as ***, *** from ***
10.如何让winform的combobox只能选不能输入?
DropDownStyle 属性确定用户能否在文本部分中输入新值以及列表部分是否总显示。
值:
DropDown --- 文本部分可编辑。用户必须单击箭头按钮来显示列表部分。
DropDownList --- 用户不能直接编辑文本部分。用户必须单击箭头按钮来显示列表部分。
Simple --- 文本部分可编辑。列表部分总可见。
11.怎样使winform的DataGrid里显示的日期只显示年月日部分,去掉时间?
sql语句里加上to_date(日期字段,'yyyy-mm-dd')
12.怎样把数据库表的二个列合并成一个列Fill进DataSet里?
dcChehao = new DataColumn("newColumnName", typeof(string));
dcChehao.Expression = "columnName1+columnName2";
dt.Columns.Add(dcChehao);
Oracle:
select col1||col2 from table
sql server:
select col1+col2 from table
13.如何从合并后的字段里提取出括号内的文字作为DataGrid或其它绑定控件的显示内容?即把合并后的字段内容里的左括号(和右括号)之间的文字提取出来。
Select COL1,COL2, case
when COL3 like ‘%(%’ THEN substr(COL3, INSTR(COL3, ‘(’ )+1, INSTR(COL3,‘)’)-INSTR(COL3,‘(’)-1)
end as COL3
from MY_TABLE
14.当用鼠标滚轮浏览DataGrid数据超过一定范围DataGrid会失去焦点。怎样解决?
this.dataGrid1.MouseWheel+=new MouseEventHandler(dataGrid1_MouseWheel);
private void dataGrid1_MouseWheel(object sender, MouseEventArgs e)
{
this.dataGrid1.Select();
}
15.怎样把键盘输入的‘+’符号变成‘A’?
textBox的KeyPress事件中
if(e.KeyChar == '+')
{
SendKeys.Send("A");
e.Handled = true;
}
16.怎样使Winform启动时直接最大化?
this.WindowState = FormWindowState.Maximized;
17.c#怎样获取当前日期及时间,在sql语句里又是什么?
c#: DateTime.Now
sql server: GetDate()
18.怎样访问winform DataGrid的某一行某一列,或每一行每一列?
dataGrid[row,col]
19.怎样为DataTable进行汇总,比如DataTable的某列值‘延吉'的列为多少?
dt.Select("城市='延吉'").Length;
20.DataGrid数据导出到Excel后0212等会变成212。怎样使它导出后继续显示为0212?
range.NumberFormat = "0000";
21.
① 怎样把DataGrid的数据导出到Excel以供打印?
② 之前已经为DataGrid设置了TableStyle,即自定义了列标题和要显示的列,如果想以自定义的视图导出数据该怎么办?
③ 把数据导出到Excel后,怎样为它设置边框啊?
④ 怎样使从DataGrid导出到Excel的某个列居中对齐?
⑤ 数据从DataGrid导出到Excel后,怎样使标题行在打印时出现在每一页?
⑥ DataGrid数据导出到Excel后打印时每一页显示’当前页/共几页’,怎样实现?
①
private void button1_Click(object sender, System.EventArgs e)
{
int row_index, col_index;
row_index = 1;
col_index = 1;
Excel.ApplicationClass excel = new Excel.ApplicationClass();
excel.Workbooks.Add(true);
DataTable dt = ds.Tables["table"];
foreach(DataColumn dcHeader in dt.Columns)
excel.Cells[row_index, col_index++] = dcHeader.ColumnName;
foreach(DataRow dr in dt.Rows)
{
col_index = 0;
foreach(DataColumn dc in dt.Columns)
{
excel.Cells[row_index+1, col_index+1] = dr[dc];
col_index++;
}
row_index++;
}
excel.Visible = true;
}
private void Form1_Load(object sender, System.EventArgs e)
{
SqlConnection conn = new SqlConnection("server=tao; uid=sa; pwd=; database=pubs");
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from authors", conn);
ds = new DataSet();
da.Fill(ds, "table");
dataGrid1.DataSource = ds;
dataGrid1.DataMember = "table";
}
②dataGrid1.TableStyles[0].GridColumnStyles[index].HeaderText; //index可以从0~dataGrid1.TableStyles[0].GridColumnStyles.Count遍历。
③ Excel.Range range;
range=worksheet.get_Range(worksheet.Cells[1,1],xSt.Cells[ds.Tables[0].Rows.Count+1,ds.Tables[0].Columns.Count]);
range.BorderAround(Excel.XlLineStyle.xlContinuous,Excel.XlBorderWeight.xlThin,Excel.XlColorIndex.xlColorIndexAutomatic,null);
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle =Excel.XlLineStyle.xlContinuous;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].Weight =Excel.XlBorderWeight.xlThin;
range.Borders[Excel.XlBordersIndex.xlInsideVertical].ColorIndex =Excel.XlColorIndex.xlColorIndexAutomatic;
range.Borders[Excel.XlBordersIndex.xlInsideVertical].LineStyle = Excel.XlLineStyle.xlContinuous;
range.Borders[Excel.XlBordersIndex.xlInsideVertical].Weight = Excel.XlBorderWeight.xlThin;
④ range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
⑤ worksheet.PageSetup.PrintTitleRows = "$1:$1";
⑥ worksheet.PageSetup.CenterFooter = "第&P页 / 共&N页";
22.当把DataGrid的Cell内容赋值到Excel的过程中想在DataGrid的CaptionText上显示进度,但不显示。WHY?
...
dataGrid1.CaptionText = "正在导出:" + (row + 1) + "/" + row_cnt;
System.Windows.Forms.Application.DoEvents();
...
处理当前在消息队列中的所有Windows消息。
当运行Windows窗体时,它将创建新窗体,然后该窗体等待处理事件。该窗体在每次处理事件时,均将处理与该事件关联的所有代码。所有其他事件在队列中等待。在代码处理事件时,应用程序并不响应。如果在代码中调用DoEvents,则应用程序可以处理其他事件。
如果从代码中移除DoEvents,那么在按钮的单机事件处理程序执行结束以前,窗体不会重新绘制。通常在循环中使用该方法来处理消息。
23.怎样从Flash调用外部程序,如一个C#编译后生成的.exe?
fscommand("exec", "应用程序.exe");
① 必须把flash发布为.exe
② 必须在flash生成的.exe文件所在目录建一个名为fscommand的子目录,并把要调用的可执行程序拷贝到那里。
24.有没有办法用代码控制DataGrid的上下、左右的滚动?
dataGrid1.Select();
SendKeys.Send("{PGUP}");
SendKeys.Send("{PGDN}");
SendKeys.Send("{^{LEFT}"); // Ctrl+左方向键
SendKeys.Send("{^{RIGHT}"); // Ctrl+右方向键
25.怎样使两个DataGrid绑定两个主从关系的表?
DataGrid1.DataSource = ds;
DataGrid1.DataMember = "母表";
...
DataGrid2.DataSouce = ds;
DataGrid2.DataMember = "母表.关系名";
26.assembly的版本号怎样才能自动生成?特别是在Console下没有通过VStudio环境编写程序时。
关键是AssemblyInfo.cs里的[assembly: AssemblyVersion("1.0.*")],命令行编译时包含AssemblyInfo.cs
27.怎样建立一个Shared Assembly?
用sn.exe生成一个Strong Name:keyfile.sn,放在源程序目录下
在项目的AssemblyInfo.cs里[assembly: AssemblyKeyFile("..//..//keyfile.sn")]
生成dll后,用gacutil /i myDll.dll放进Global Assembly Cach.
28.在Oracle里如何取得某字段第一个字母为大写英文A~Z之间的记录?
select * from table where ascii(substr(字段,1,1)) between ascii('A') and ascii('Z')
29.怎样取得当前Assembly的版本号?
Process current = Process.GetCurrentProcess();
FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(current.MainModule.FileName);
Console.WriteLine(myFileVersionInfo.FileVersion);
30.怎样制作一个简单的winform安装程序?
① 建一个WinForm应用程序,最最简单的那种。运行。
② 添加新项目->安装和部署项目,‘模板’选择‘安装向导’。
③ 连续二个‘下一步’,在‘选择包括的项目输出’步骤打勾‘主输出来自’,连续两个‘下一步’,‘完成’。
④ 生成。
⑤ 到项目目录下找到Setup.exe(还有一个.msi和.ini文件),执行。
31.怎样通过winform安装程序在Sql Server数据库上建表?
① [项目]—[添加新项]
类别:代码;模板:安装程序类。
名称:MyInstaller.cs
② 在SQL Server建立一个表,再[所有任务]—[生成SQL脚本]。
生成类似如下脚本(注意:把所有GO语句去掉):
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[MyTable]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[MyTable]
CREATE TABLE [dbo].[MyTable] (
[ID] [int] NOT NULL ,
[NAME] [nchar] (4) COLLATE Chinese_PRC_CI_AS NOT NULL
) ON [PRIMARY]
ALTER TABLE [dbo].[MyTable] WITH NOCHECK ADD
CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED
(
[ID]
) ON [PRIMARY]
③ [项目]—[添加现有项]。mytable.sql—[生成操作]-[嵌入的资源]。
④ 将MyInstaller.cs切换到代码视图,添加下列代码:
先增加:
using System.Reflection;
using System.IO;
然后:
private string GetSql(string Name)
{
try
{
Assembly Asm = Assembly.GetExecutingAssembly();
Stream strm = Asm.GetManifestResourceStream(Asm.GetName().Name + "." + Name);
StreamReader reader = new StreamReader(strm);
return reader.ReadToEnd();
}
catch (Exception ex)
{
Console.Write("In GetSql:"+ex.Message);
throw ex;
}
}
private void ExecuteSql(string DataBaseName,string Sql)
{
System.Data.SqlClient.SqlConnection sqlConn = new System.Data.SqlClient.SqlConnection();
sqlConn.ConnectionString = "server=myserver; uid=sa; password=; database=master";
System.Data.SqlClient.SqlCommand Command = new System.Data.SqlClient.SqlCommand(Sql,sqlConn);
Command.Connection.Open();
Command.Connection.ChangeDatabase(DataBaseName);
try
{
Command.ExecuteNonQuery();
}
finally
{
Command.Connection.Close();
}
}
protected void AddDBTable(string strDBName)
{
try
{
ExecuteSql("master","create DATABASE "+ strDBName);
ExecuteSql(strDBName,GetSql("mytable.sql"));
}
catch(Exception ex)
{
Console.Write("In exception handler :"+ex.Message);
}
}
public override void Install(System.Collections.IDictionary stateSaver)
{
base.Install(stateSaver);
AddDBTable("MyDB"); //建一个名为MyDB的DataBase
}
⑤ [添加新项目]—[项目类型:安装和部署项目]—[模板:安装项目]—[名称:MySetup]。
⑥ [应用程序文件夹]—[添加]—[项目输出]—[主输出]。
⑦ 解决方案资源管理器—右键—[安装项目(MySetup)]—[视图]—[自定义操作]。[安装]—[添加自定义操作]—[双击:应用程序文件夹]的[主输出来自***(活动)]。
32.怎样用TreeView显示父子关系的数据库表(winform)?
三个表a1,a2,a3, a1为a2看母表,a2为a3的母表。
a1: id, name
a2: id, parent_id, name
a3: id, parent_id, name
用三个DataAdapter把三个表各自Fill进DataSet的三个表。
用DataRelation设置好三个表之间的关系。
foreach(DataRow drA1 in ds.Tables["a1"].Rows)
{
tn1 = new TreeNode(drA1["name"].ToString());
treeView1.Nodes.Add(tn1);
foreach(DataRow drA2 in drA1.GetChildRows("a1a2"))
{
tn2 = new TreeNode(drA2["name"].ToString());
tn1.Nodes.Add(tn2);
foreach(DataRow drA3 in drA2.GetChildRows("a2a3"))
{
tn3 = new TreeNode(drA3["name"].ToString());
tn2.Nodes.Add(tn3);
}
}
}
33.怎样从一个form传递数据到另一个form?
假设Form2的数据要传到Form1的TextBox。
在Form2:
// Define delegate
public delegate void SendData(object sender);
// Create instance
public SendData sendData;
在Form2的按钮单击事件或其它事件代码中:
if(sendData != null)
{
sendData(txtBoxAtForm2);
}
this.Close(); //关闭Form2
在Form1的弹出Form2的代码中:
Form2 form2 = new Form2();
form2.sendData = new Form2.SendData(MyFunction);
form2.ShowDialog();
====================
private void MyFunction(object sender)
{
textBox1.Text = ((TextBox)sender).Text;
}
一段javascript实现缩略图的好代码,可以实现缩略图,代码如下
<script language="javascript">
//显示缩略图
function DrawImage(ImgD,width_s,height_s){
/*var width_s=139;
var height_s=104;
*/
var image=new Image();
image.src=ImgD.src;
if(image.width>0 && image.height>0){
flag=true;
if(image.width/image.height>=width_s/height_s){
if(image.width>width_s){
ImgD.width=width_s;
ImgD.height=(image.height*width_s)/image.width;
}else{
ImgD.width=image.width;
ImgD.height=image.height;
}
}
else{
if(image.height>height_s){
ImgD.height=height_s;
ImgD.width=(image.width*height_s)/image.height;
}else{
ImgD.width=image.width;
ImgD.height=image.height;
}
}
}
/*else{
ImgD.src="";
ImgD.alt=""
}*/
}
</script>
调用时,很简单,比如一段ASP代码的
<img src="../memberphoto/<%=rs("picpath")%>" align="middle" onload="DrawImage(this,200,200)"></div>
- ASP.NET筆記(本人收集整理)
- 学习 .Net 的经典网站(本人收集整理)
- asp.net 常见问题收集整理(不断收集中)
- VB.net C# 代码转换工具-2篇 (本人收集整理)
- ADO.net整理收集
- 本人网上收集整理的shell教程,非常详细
- asp.net收集
- Asp.net资料收集
- asp.net 技巧收集
- asp.net工具收集
- ASP.net技术收集
- ASP.NET教程收集
- asp.net 资料收集
- asp常用函数收集整理
- ASP.NET常识整理
- ASP.NET常识整理
- ASP.NET常识整理
- Asp.Net 整理(文件)
- 新打包的 CppReference.chm
- C#创建和使用ActiveX组件
- 使用强大的反射取消事件的订阅。
- .Net中常见问题及解决方法归类
- 你的.net 2.0 真的能与1.1 安全正确地运行在同一台电脑上吗? 小心Server Application Unavailable 错误
- ASP.NET筆記(本人收集整理)
- 偶然发现这里也有我的博客
- 全球最著名的16位黑客列传(上)
- 给ACAD增加个命令,修改外部DWG文件,给所有LINE加扩展数据的完整的ARX代码...
- SQL Server 中用代码复制表
- 二十世纪的数学
- log4j:ERROR Attempted to append to closed appender named [null].
- Spring--quartz中cronExpression配置说明
- 网页调用rm播放器代码 - 附详细说明