ASP.NET小代码集合一(简单)

ASP.NET小代码集合一


*ASP.NET怎么与javascript交互?能不能提供相关实例代码研究?
<script language=c# runat=server>
public string getValue(string strValue)
{
return "test";
}
</script>



<script language=javascript>
function test()
{
var temp = <%=getValue("1")%>
var UserName = <%=Session["UserName"].ToString()%>
}


function recirle()
{
timer=setInterval('<%string s=getValue("1")%>',4000);
}
</script>


* 给DataGrid添加删除确认:
你在属性生成器里,把按钮列“删除”的文本改成这个就行了。
<div id="de" οnclick="javascript:return confirm('你确定要删除此条记录吗?')">删除</div>




1、取得当前目录下所有文件名(包括各级子目录):
string[] subdir=Directory.GetDirectories(Server.MapPath("."));
string[] filename=Directory.GetFiles(Server.MapPath("."));


2、用户验证问题
-----default.aspx----------
Session["user_id"]= User.Identity.Name;
Response.Redirect("Customer/cmControl.aspx");


-----cmControl.aspx---------
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if (!IsPostBack) ReadRecords();

}


public void ReadRecords()
{
try
{
String id=(String)Session["user_id"];
data.dbOpen();
objDataAdapter1=new OdbcDataAdapter("select * from acc where username='"+id+"'",data.objConnection);
ds1=new DataSet("ds1");
objDataAdapter1.Fill(ds1);


DataGrid1.DataSource=ds1;
DataGrid1.DataKeyField="acc_id";
DataGrid1.DataBind();
}
catch(Exception e)
{
Response.Write(e.Message);
Response.End();
}
finally
{
if(objDataAdapter1!=null)objDataAdapter1.Dispose();
if(data.objConnection!=null) data.dbClose();
}
}


这样就实现了从default.aspx转到cmcontrol.aspx页面,并根据user_id显示用户信息


3、javascript实现全屏
<script language="javascript">


function windowopen(){


newwindow=window.open("","","scrollbars")
if (document.all){
newwindow.moveTo(0,0)
newwindow.resizeTo(screen.width,screen.height)
}
newwindow.location=target
}
//-->
</script>


另:window.open("","","fullscreen=yes")


如何在IE中使弹出窗口最大化,在线等待
用javasrcipt中 window.open('','_blank','width=swidth,height=sheight')
swidth // 屏幕有效宽度
sheight // 屏幕有效高度


4、如何实现页面的自动跳转
<meta http-equiv="refresh" content="10; url=http:\\www.sohu.com">


5、webconfig设置连接字符串
用Access好像定义不了相对路径
用sql server
Data Source=(local);" +"Initial Catalog=mySQLServerDBName;"+"IntegratedSecurity=SSPI";


6、访问基于 SQL 的数据
查询 示例
简单选择 SELECT * from Employees WHERE FirstName = 'Bradley';
联接选择 SELECT * from Employees E, Managers M WHERE E.FirstName = M.FirstName;
插入 INSERT into Employees VALUES ('123-45-6789','Bradley','Millington','Program Manager');
更新 UPDATE Employees SET Title = 'Development Lead' WHERE FirstName = 'Bradley';
删除 DELETE from Employees WHERE Productivity < 10;


7、连接数据库所使用的命名空间
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>


8、连接数据库并绑定数据
SqlConnection myConnection = new SqlConnection(
"server=(local)\\NetSDK;database=pubs;Integrated Security=SSPI");
SqlDataAdapter myCommand = new SqlDataAdapter("select * from Authors", myConnection);


DataSet ds = new DataSet();
myCommand.Fill(ds, "Authors");


MyDataGrid.DataSource=ds.Tables["Authors"].DefaultView;
MyDataGrid.DataBind();


另:
SqlConnection myConnection = new SqlConnection(
"server=SQLServer;database=pubs;UID=sa;PWD=1;");
SqlDataAdapter myCommand = new SqlDataAdapter("select * from Authors", myConnection);


DataSet ds = new DataSet();
myCommand.Fill(ds, "Authors");


MyDataGrid.DataSource=ds;
MyDataGrid.DataMember="Authors";
MyDataGrid.DataBind();


DropDownList1.DataSource=ds.Tables["Authors"].DefaultView;
DropDownList1.DataTextField="字段名";
DropDownList1.DataValueField="字段名";
DropDownList1.DataBind();


9、参数传递
myCommand.SelectCommand.Parameters.Add(new SqlParameter("@State", SqlDbType.NVarChar, 2));
myCommand.SelectCommand.Parameters["@State"].Value = MySelect.Value;


10、在ASP.NET页面中如何使用SQL SERVER 2000数据库?
<script runat=server>
protected void Page_Load(Object Src, EventArgs E)
{
myConnection = new SqlConnection("server=NETSERVER;database=pubs;UID=sa;PWD=1;");


if (!IsPostBack)
{
BindGrid("au_id");
Page.DataBind();
}
}


public void BindGrid(String sortfield)
{
SqlDataAdapter myCommand = new SqlDataAdapter("select * from Authors", myConnection);


DataSet ds = new DataSet();
myCommand.Fill(ds, "Authors");

DataView Source = ds.Tables["Authors"].DefaultView;
Source.Sort = sortfield;


MyDataGrid.DataSource=ds.Tables["Authors"].DefaultView;
MyDataGrid.DataBind();
}


</script>



关键语句:
myConnection = new SqlConnection("server=NETSERVER;database=pubs;UID=sa;PWD=1;");



myConnection = new SqlConnection("server=您的SQL Server服务器名字或IP地址;database=您要连接的SQL Server中的数据库的名称;UID=登录SQL Server数据库所需要的用户名;PWD=登录SQL Server数据库所需要的密码;");


本机登录:
server=localhost;uid=sa;pwd=;database=pubs;


11、HyperLinkColumn如何傳遞兩個邦定的參數?
<asp:HyperLinkColumn DataNavigateUrlField="id" DataNavigateUrlFormatString="showsoft.aspx?&id={0}&class=c_id" DataTextField="name"></asp:HyperLinkColumn>
如何使那个c_id也能幫定呢?



答:
方法一、
<asp:datagrid runat="server" ID="mygrid">
<asp:templatecolumn HeaderText="某某">
<itemtemplate>
<a href='网址?id=<%# container.dataitem("字段一") %>&name=<%# container.dataitem("字段二") %>'
</itemtemplate>
</asp:templatecolumn>
</asp:datagrid>
方法二、
<asp:datagrid runat="server" ID="mygrid">
<asp:templatecolumn HeaderText="某某">
<itemtemplate>
<asp:HyperLink id="HyperLink" runat="server" NavigateUrl="WebForm1.aspx?id=<%# DataBinder.Eval(Container.DataItem, "id")%>&name=<%# DataBinder.Eval(Container.DataItem, "name")%>" Target="_blank"><%# DataBinder.Eval(Container.DataItem, "name")%></asp:HyperLink> </itemtemplate>
</asp:templatecolumn>
</asp:datagrid>



12、document.all("pln").innerHTML="sdffffffffffffffffffffffffdfggggggggggggggggggggggg"; 怎么换行?


方法一、
document.all("pln").innerHTML="sdffffffffffffffffffffffffdf<BR>ggggggggggggggggggggggg";
方法二、
<div id="pln" style="BACKGROUND-COLOR: red; WORD-WRAP: break-word;Z-INDEX: 29; LEFT: 499px; WIDTH: 159px; POSITION: absolute; TOP: 35px; HEIGHT: 109px">dfsdfdsf
</div>


用户验证问题:
-----default.aspx----------
Session["user_id"]= User.Identity.Name;
Response.Redirect("Customer/cmControl.aspx");


-----cmControl.aspx---------
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if (!IsPostBack) ReadRecords();

}


public void ReadRecords()
{
try
{
String id=(String)Session["user_id"];
data.dbOpen();
objDataAdapter1=new OdbcDataAdapter("select * from acc where username='"+id+"'",data.objConnection);
ds1=new DataSet("ds1");
objDataAdapter1.Fill(ds1);


DataGrid1.DataSource=ds1;
DataGrid1.DataKeyField="acc_id";
DataGrid1.DataBind();
}
catch(Exception e)
{
Response.Write(e.Message);
Response.End();
}
finally
{
if(objDataAdapter1!=null)objDataAdapter1.Dispose();
if(data.objConnection!=null) data.dbClose();
}
}


这样就实现了从default.aspx转到cmcontrol.aspx页面,并根据user_id显示用户信息



14、查询一周内信息
"select * from 表a where 表示时间的字段>='"+DateTime.Now.AddDays(-7)+"'"


15、关于数据省略显示的解决办法!
由于资料在家里,不在办公室,如果我写的程序也许有语法错误,请通过我的思路自行解决:
我在这里提供两种实现方式:
1.在服务器端datagrid绑定数据之前修改相应数据表的内容.
2.在客户端显示datagrid数据时用javascript修改显示的内容.
方法一:
dim conn as newoledbconn(.....)
conn.open()
dim objada as new oledbadapter("select * from xxx",conn)
dim ds as new dataset()
objada.fill(ds,"xxx")
dim dt as datatable=ds.tables("xxx")
'得到数据表
'假设要修改的字段名为zsc
dim i as integer
for i=0 to dt.rows.count-1
if len(dt.rows(i)("zsc"))>7 then
dt.rows(i)("zsc")=left(dt.rows(i)("zsc")) & "..."
end if
next
mygrid.datasource=dt
mygrid.databind()
conn.close()



方法二:在客户端修改
由于使用的控件是datagrid,所以,感觉客户端好像无从下手.方法如下:
<asp:datagrid runat="server" id="mygrid">
<column>
<asp:databoundcolumn.........>
<asp:databoundcolumn.........>
'以上是其它各列,对于要修改显示的列,请用模板列
<asp:templatecolumn headertext="某某">
<itemtemplate>
在这里加上相关javascript判断我没书在身边有些函数忘记
<%# container.dataitem("zsc") %>
</itemtemplate>
</asp:templatecolumn>
</column>
</asp:datagrid>


函数方法:
不管是在绑定前还是绑定后,都只用一个函数就可以实现。把要比较的字符串以参数形式传到以下函数中。
public string Tuncate(String str)
{
if (str.Length > 150)
return str.Substring(0, 150);
return str;
}


方法三、DataGrid等网格控件绑定字段做判断问题...
在输出记录的同时,判断记录条件做相应显示,在asp中很容易实现,但在.net中这个问题几乎很难.下面说说他的两种解决方法:(假设你有个字段为title,字段记录长度大于30时,截断和加上"..."),推荐第二中方法,思路比较清晰,而且很通用,用Sql语句实现,还有类型转换问题。。。


1.Sql语句实现:
string str_Sql="CASE WHEN len(title)>30 THEN left(title,30)+'...' ELSE title END as title form 数据库表"


string str_Sql="CASE WHEN len(title)>30 THEN left(title,30)+'...' ELSE content END as title form 数据库表"



len() 函数类型为char或者nvarchar或者varchar类型,当字段为text类型时,必须转换成字符类型,但别忘了,text类型只有16位字节,也就是保存的是字段的内存地址,指针,所以用了,convert(char,字段)得到是内存地址,而不是实实在在的记录...


2.直接在.net中实现:
在cs后台代码程序中编写截取30个字符函数
public string GetCharacter(string str_Value)
{
if (str_Value.Length>30)
{
return str_Value.Substring(0,30)+"....";
}
else
{
return str_Value;
}
}


在aspx文件调用它:


<%# GetCharacter(DataBinder.Eval(Container.DataItem,"title").ToString()) %>


15、日期转化成字符串的多种方法
1、
用replace函数就可以了,strname=replace("2003-18-11","-","")
2、
也可以这样:str = Year("2003-18-11")&Month("2003-18-11")&Day("2003-18-11")
3、
不如试试:DateTime.ToString("yyyyMMdd")
4、
我是这样解决的:
DateTime.Now.ToString(“yyyyMMddHHmmss”)
5、
Str = Year("2003-1-8")
m = Month("2003-1-8")
If Len(m) = 1 Then m = "0" & m
d = Day("2003-1-8")
If Len(d) = 1 Then d = "0" & d
Str = Str & m & d
6、
string d = "1998-8-1";
string t = ((System.DateTime)d.ToString("yyyy-MM-dd");
string strname=replace(t,"-","")
7、
以下刚刚测试过:
using System;
public class test
{
static void Main()
{
Console.Write((DateTime.Parse("2003-1-8")).ToString("yyyyMMdd"));
}
}
8、
string d = "1998-2-6";
Response.Write(Convert.ToDateTime(d).ToString("yyyyMMdd"));
9、
其实string.Format的意思就是为你要显示的字符串格式提供一个模板,其中包含可以替换的部分,以数字为序号,后面跟上用来替换的内容,跟前面的序号一一对应。如:
string.Format("我是{0},第{1}次上论坛","aaawww",300)


10、
cstr(format("2003-1-8","yyyymmdd"))
11、
String str()=split("2003-1-8",-)
for( int i=0;i<=str.length-1;i++)
{str=str+str(i);}
12、
如果你是用vb做脚本程序的话,可以这样来做:
format(year(2003-1-8),"0000") & format(month(2003-1-8),"00") & format(month(2003-1-8),"00")
你可以再查看一下msdn,看看关于日期和字符串格式的一些函数。
13、
str = "2003-01-08"
str1 = left(str,4)&mid(str,4,2)&right(str,2)



16、NET文件操作
System.IO命名空间


  该命名空间下类比较多,主要用于文件操作,并提供一些抽象的IO基类。
这里只列举最主要的文件操作类,使文件的操作可以自如。


 


类StreamTextWriter,StreamTextReader


主要完成文本文件的读写操作。


类System.Text.Encoding


该类完成文本的编码,虽然不在该空间下,但在这里一并介绍。


类FileStream


二进制文件的读写操作。


 


类File,FileInfo,Directory,DirectoryInfo


主要完成文件系统对文件的管理,例如列目录,复制,删除等。



文本文件的读写


 


类System.IO.StreamWriter


'不管c:\t.txt是否存在都将建立一个无内容的新文件
'追加方式用 dim oFile as new StreamWriter("c:\t.txt", true)
dim oFile as new StreamWriter("c:\t.txt")


oFile.write("田地")


oFile.close()


  使用很简单,但有一个问题StreamWriter默认用UTF8方式编码,
此种文件在windows系统当然最好用,但其他系统可能有问题。如果
希望用标准的ansi方式,则可提供一个系统默认编码方式:


dim oFile as new StreamWriter("c:\t.txt",true,System.Text.encoding.default)


或者直接指定:


dim oFile as new StreamWriter("c:\t.txt",true,System.Text.encoding.GetEncoding("gb2312"))


 


类System.IO.StreamReader


和StreamWriter非常类似


dim oFile as new StreamReader("c:\t.txt")


'读取一行
dim s as string = oFile.Readline()


if s is nothing then
'如果返回Nothing则表明到文件尾了
else
's为第一行的内容
end if


'读取全部,如果已经到末尾了,依然返回空字符串"",注意不是Nothing
s = oFile.ReadToEnd()


oFile.close()



二进制文件的读写


 


类System.IO.FileStream


读取的二进制内容放在byte数组中,其他的都比较清楚不再细述。


Dim MyFileStream As New FileStream("some.dat", FileMode.Open)


'因为FileStream.Length返回的是64位Long整数,因此需要转换
'这里只为了说明,不再做缓冲区大小的检测
dim fileSize as integer = ctype(MyFileStream.Length,integer)


Dim Buffer(FileSize) As Byte


MyFileStream.Read(Buffer, 0, FileSize)


MyFileStream.Close()


'将内容复制到一个新文件
MyFileStream = New FileStream("someother.dat", FileMode.CreateNew)
MyFileStream.Write(Buffer, 0, FileSize)
MyFileStream.Close()



文件系统的基本操作


主要包括文件列表,复制,移动,删除。目录的操作等。


  分成文件类和目录类,其中每个又有两个版本。一个只包含静态方法,
一个只包含实例方法。两者主要的选择依据是是否需要重用,如果只简单
的根据文件名删除一个文件,那么选择静态类版本更简洁快速。相反如果
需要对某个文件检查很多属性,执行很多操作,那么实例版本更高效。


类File和类FileInfo,类Directory和类DirectoryInfo


不带Info的类为静态版本,带Info的为实例版本。


 


都比较清楚简单,这里只举一个枚举目录和文件的例子:


'建立DirectoryInfo实例
Dim di As New DirectoryInfo("c:\")


'得到该目录下子目录数组
Dim diArr As DirectoryInfo() = di.GetDirectories()


'枚举所有子目录
Dim dri As DirectoryInfo
For Each dri In diArr
Console.WriteLine(dri.Name)
Next dri


'得到该目录下所有文件数组
Dim fiArr As FileInfo() = di.GetFiles()


'枚举所有文件
Dim fri As FileInfo
For Each fri In fiArr
Console.WriteLine(fri.Name)
Next fri


 


这些类可直接生成FileStream和StreamWriter,来进行文件读写的操作


'建立一个二进制文件
dim s as FileStream=File.create("c:\t.dat") 


'读一个二进制文件
s=File.openRead("c:\t.dat")


'建立一个文本文件
dim sw as StreamWriter=File.createText("c:\t.txt") 


'读文件文件
sw=File.OpenText("c:\t.txt")

转载于:https://www.cnblogs.com/flyingbird/archive/2006/10/13/528602.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值