您的位置:首页 > 编程语言 > ASP

[ASP.NET]工作中经常使用到的方法

2009-08-20 12:57 501 查看
目录:
1、给删除按钮添加是否确认提示;
2、DataSet中取值;
3、字符串截取方法;
4、GridView事件中获取GridView中的控件;
5、获取GridView的DataKeyNames中主键的ID值;
6、ViewState的应用;
7、Gridview分页页码突出显示;
8、链接打开模式窗口;
9、替换字符串里的单引号;
10、VS2005显示行号:
11、GridView中的RowDataBound 事情对数据列的处理;
12、C#读取记事本文件;
13、使用LinkButton实现点击下载文件;
14、c#使用正则表达式验证网络地址URL;
15、页面弹出提示信息;
16、判断两个时间比较大小;
17、在‘页面’找引用‘用户控件’时的取值;
18、GridView上面显示页码;
19、fckeditor简要配置说明;
20、完成添加后,提示用户是否继续?;
21、DataSet循环;
22、常用快捷键;
23、asp.net页面应用返回按钮;
24、javascript 控制前进和后退;
25、图片链接新页面;
26、CS强制换行;
27、jquery验证输入控件;

--SQL--
1、SQL查询某天范围内的数据:
2、SQL添加外键关系
---------------------------------------------------------------------------------------
1、给删除按钮添加是否确认提示:
前台方法:OnClientClick="return window.confirm('你确定要删除吗?')"
后台方法:btnDelete.Attributes.Add("onclick", "return confirm('您确定要删除吗?');");

2、DataSet中取值:
lblTitle.Text = ds.Tables[0].Rows[0]["Title"].ToString();

3、字符串截取方法:
public string StringFormat(int len, string str)
{
return (str.Length > len) ? str.Substring(0, len) + " ..." : str;
}

4、GridView事件中获取GridView中的控件:
LinkButton lbtnManager = e.Row.FindControl("lbtnManager") as LinkButton;

5、获取GridView的DataKeyNames中主键的ID值:
int id = Convert.ToInt32((sender as GridView).DataKeys[e.Row.RowIndex].Value.ToString());

6、ViewState的应用:
[网站前台,尽量禁用ViewState;当然也最好不要使用PostBack]
public string vsEName
{
get
{
if (EnableViewState)
{
object obj = ViewState["eName"];
if (obj != null)
return (string)obj;
else
return string.Empty;
}
else
return string.Empty;
}
set
{
if (EnableViewState)
ViewState["eName"] = value;
}
}
7、Gridview分页页码突出显示:
protected void gvEquipment_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
TableRow row = e.Row.Controls[0].Controls[0].Controls[0] as TableRow;
foreach (TableCell cell in row.Cells)
{
System.Web.UI.Control lb = cell.Controls[0];
if (lb is Label)
{
((Label)lb).ForeColor = System.Drawing.Color.Red;
((Label)lb).Font.Size = new FontUnit("12px");
}
else if (lb is LinkButton)
{
((LinkButton)lb).Text = "[" + ((LinkButton)lb).Text + "]";
}
}
}
}
8、链接打开模式窗口
页面:
<script language="javascript" type="text/javascript">
function orberopen(href)
{
window.open(href,'','width=580,height=515,top=10,left=20,scrollbars=yes,resizable=yes');
}
</script>
后台绑定:
litDescription.Text = "<a href='#' title='查看详情' class='afont' onclick=/"orberopen('" + aLinkURL + "')/">" + desc + "</a>";

9、替换字符串里的单引号:
public static string ReplaceString(string theValue)
{
if (theValue != null) theValue = theValue.Replace("'", "''");
return theValue;
}
10、VS2005显示行号:
后台代码:工具→选项→文本编辑器→C#→显示→(选上)行号
HTML前台:工具→选项→文本编辑器→HTML→(选上)行号

11、GridView中的RowDataBound 事情对数据列的处理
protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{

}
}
12、C#读取记事本文件
protected void GetVistorCount()
{
try
{
string path = @Server.MapPath("App_Data/VisitorCount.txt");
string text = System.IO.File.ReadAllText(path);
int number = Convert.ToInt32(text);
new FileInfo(path).Attributes = FileAttributes.Normal;
System.IO.File.WriteAllText(path,Convert.ToString(number+1));
labVisitor.Text = number.ToString();
}catch( Exception e)
{

}
}
13、使用LinkButton实现点击下载文件
1.页面代码:
<asp:LinkButton ID="lbtnAttachName" runat="server" OnClick="lbtnAttachName_Click"></asp:LinkButton>
后台代码:
protected void lbtnAttachName_Click(object sender, EventArgs e)
{
string url = "~/FileDown.aspx?fileName=" + lbtnAttachName.Text.Trim() + "&filePath=~/uploadfile/ArticleAttach/";
Response.Redirect(url);
}

2.时间里跳到一个页面里面的方法为:
try
{
string fileName = Request.QueryString["fileName"];
string filePath = Request.QueryString["filePath"];
string File_address = Server.MapPath(filePath) + fileName;
if (!File.Exists(File_address))
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('文件不存在,下载失败!'); history.back(); ", true);
return;
}
Response.Buffer = true;
string contentType = "application/octet-stream";
//输出流
Response.Clear();
Response.AppendHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
Response.Charset = "UTF-8"; // 客户端浏览器的字符集UTF-8.注意在IE--Internet选项--高级里,选中:始终用UTF-8发送URL链接
Response.ContentType = contentType;
using (FileStream fs = File.OpenRead(File_address))
{
string strFileSize = fs.Length.ToString();
Response.AppendHeader("Content-Length", strFileSize);
byte[] b = new byte[1024];
while (fs.Read(b, 0, b.Length) > 0)
{
Response.BinaryWrite(b);
}
Response.Flush();
fs.Close();

Response.End();
}

}
catch (Exception ex)
{

}

14、c#使用正则表达式验证网络地址URL
public bool ValidateUrl(string _strUrl)
{
string patten = @"^http://(www/.){0,1}.+/.(com|net|cn)$"; //正则表达式
Regex r = new Regex(patten); //声明一个Regex对象
Match m = r.Match(_strUrl); //使用Match方法进行匹配
if (m.Success) //匹配成功
{
return true;
}
else
{
return false;
}
}

15、页面弹出提示信息
普通页面:
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('文件不存在,下载失败!'); history.back() ", true);

用户控件使用:
Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('请选择完成时间!');", true);

其他方式:
ClientScriptManager cs = this.ClientScript;
cs.RegisterArrayDeclaration("Hello", "1, 2, 3");
cs.RegisterClientScriptBlock(this.GetType(), "HelloWorld",
"function helloWorld(){alert('RegisterClientScriptBloc_Test');}", true);
cs.RegisterClientScriptInclude("HelloWorld", "HelloWorld.js");
// cs.RegisterClientScriptResource();
cs.RegisterExpandoAttribute(this.Button1.ClientID, "Hello", "World");
cs.RegisterHiddenField("hello", "world");
cs.RegisterOnSubmitStatement(this.GetType(), "HelloWorld", "return window.confirm('Do you really want to submit the form?')");
cs.RegisterStartupScript(this.GetType(), "HelloWorld", "<script>alert('The page has loaded!')</script>");

16、判断两个时间比较大小
string startDate ='2009-8-14 10:16:55';
string endDate = '2009-8-14 10:17:13';

DateTime time1 = DateTime.Parse(startDate);
DateTime time2 = DateTime.Parse(endDate);
if (time1 >= time2)
{
throw new Exception("会议结束时间不能小于等于会议开始时间,请重新选择!");
}

17、在‘页面’找引用‘用户控件’时的取值。
1.得到控件:用户控件.FindControl("控件ID")
Demo:reportTable.FindControl("btSubmit")
2.得到属性:用户控件.属性名称
Demo:reportTable.UserID;

18、GridView上面显示页码:
<Columns>
......
</Columns>
<PagerSettings Position="TopAndBottom" />

19、fckeditor简要配置说明
1.把fckeditor文件夹放到项目下,及FredCK.FCKeditorV2.dll放到项目Bin目录下。
2.web.config配置
<appSettings>
<!--FCKeditor用户附件上传路径-->
<add key="FCKeditor:UserFilesPath" value="Web/PublicSource/UpLoad/"/>
</appSettings>
3.页面顶部配置
<%@ Register Assembly="FredCK.FCKeditorV2" Namespace="FredCK.FCKeditorV2" TagPrefix="FCKeditorV2" %>
4.页面使用位置配置
<FCKeditorV2:FCKeditor ID="txtContents" runat="server" Height="550px" Width="450px"
BasePath="~/fckeditor/" ToolbarSet="">
</FCKeditorV2:FCKeditor>

20、完成添加后,提示用户是否继续?
ClientScript.RegisterClientScriptBlock(this.GetType(), "提示信息",
" if( window.confirm('新闻添加成功 (*^__^*),您是否想继续添加?'))"
+ " { window.location.href='NewsEdit.aspx' } "
+ " else { window.location.href='NewsList.aspx' } "
, true);

21、DataSet循环:
if (ds.Tables.Count == 1 && ds.Tables[0].Rows.Count != 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
imagesPath.Add(ds.Tables[0].Rows[i]["ImagesPath"].ToString());
}
return imagesPath;
}

22、常用快捷键
1. Ctrl + K + D :格式化代码。前台后台代码都适用。(vs 2005以上版本)
2. Ctrl + K + C :批量注释代码。
3. Ctrl + K + U : 批量取消注释代码。
4. Shift + Del 删除当前行。
5. Ctrl + Shift + A : 添加新项。
6. Ctrl + J :调出智能提示。
7. Ctrl + Alt + L : 调出解决方案资源管理器。
8. Ctrl + M + M : 折叠/收缩 Region 指令区代码。
9. F7 : 从前台源代码视图切换到后台代码视图。
10. Shift + F7 : 从前台源代码视图切换到可视化视图。
11. Ctrl + I : 渐进式搜索。
12. F9 : 添加/删除断点。
13. F10: 逐过程调试。
14. F11 : 逐语句调试。
15. F5 :启动调试。
16. Ctrl + F5 : 开始执行(不调试)。
17: Shift + F5 : 停止调试。
18: Ctrl + Shift + F5 : 重新启动调试。
19: Ctrl + Alt + I : 调出立即窗口(立即窗口非常有用,在调试过程中,可以监控任何变量的值。)
20. Ctrl + Alt + O :调出输出窗口(可以查看编译过程中的错误或警告信息).
21. Tab : 先选中代码,再按tab 键可以缩进代码。
22. Shift + tab :选中代码,可反向缩进代码。(对于格式化js 很有用)
23. Shift + Alt + Enter : 全屏显示与切换。

23、asp.net页面应用返回按钮
<input id="Button1" type="button" value="返回" class="button2"
onclick="window.location.href('CollegeDoc.aspx')" />

24、javascript 控制前进和后退:使用history对象
history.back();//相当于用户单击“后退”按钮
history.forward();//相当于用户单击“前进”按钮
history.go(-2);//相当于用户单击两次“后退”按钮

25、图片链接新页面
<img height="30" alt="" src="images/index11.jpg" width="529" style="cursor:pointer"
border="0" onclick="javascript:window.location.href ='AcademyLog.aspx?type=News'"/>

26、CS强制换行
style="word-wrap: break-word; "

27、jquery验证输入控件
1.给项目添加jquery使用文件包
2.页面添加引用
<script src="../js/jquery_last.js" type="text/javascript"></script>
<link type="text/css" rel="stylesheet" href="../css/validator.css" />
<script src="../js/formValidator.js" type="text/javascript" charset="UTF-8"></script>
<script src="../js/formValidatorRegex.js" type="text/javascript" charset="UTF-8"></script>
<script type="text/javascript" src="../js/datepicker/WdatePicker.js" defer="defer"></script>
3.页面输入控件及引用配置
<script type="text/javascript">
$(document).ready(function(){
$.formValidator.initConfig({formid:"form1",onerror:function(msg){}});
$("#txtTitle").formValidator({onshow:"请输入新闻标题",onfocus:"新闻标题为必填项!"}). inputValidator({min:1,onerror:"新闻标题不能为空"});
});
</script>

<asp:TextBox ID="txtTitle" runat="server" Width="539px" MaxLength="60"></asp:TextBox>
<div id="txtEquipmentNameTip" style="width:250px"></div>

--SQL--
1、SQL查询某天范围内的数据:
Select * from Notepad where 1=1 and UploadDate > '2009-7-24 0:00:00' and UploadDate < '2009-7-24 23:59:59' order by UploadDate desc

2、SQL添加外键关系
-- alter table 需要建外键的表add constraint 外键名字(FK_字段名) foreign key(外键字段) references 外键表(外键字段) ,
alter table MeetingRoom
add constraint FK_Responder foreign key(Responder) references web_Users(UserId)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: