ASP.NET常用代码汇总
<script language="javascript" type="text/javascript">
function preview()
{
bdhtml=window.document.body.innerHTML;
sprnstr="<!--startprint-->";
eprnstr="<!--endprint-->";
prnhtml=bdhtml.substr(bdhtml.indexOf(sprnstr)+17);
prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr));
window.document.body.innerHTML=prnhtml;
window.print();
}
</script>
2、上传图片到数据库
string FileName = this.FileUpload1.FileName;
Stream ios = this.FileUpload1.FileContent;
byte[] buff=new byte[this.FileUpload1.FileContent.Length];
ios.Read(buff, 0, (int)this.FileUpload1.FileContent.Length);
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["con"]);
SqlCommand com = new SqlCommand("insert jpg(imgname) values(@name)",con);
con.Open();
com.Parameters.Add("@name",SqlDbType.Image,buff.Length).Value=buff;
com.ExecuteNonQuery();
ios.Close();
con.Close();
3、文件下载Demo
string path=Server.MapPath("广告.jpg");
//下载文件的名称
string filename = "广告.jpg";
System.IO.FileInfo toDownload = new System.IO.FileInfo (path);
Response.Clear();
if (System.IO.Path.GetExtension(filename) == ".jpg")
{
Response.AddHeader("Content-Disposition", "attachment;filename=NEW_" + HttpUtility.UrlEncode(toDownload.Name));
Response.ContentType = "application/x-zip-compressed";
Response.TransmitFile(path);
Response.End();
}
4、显示数据库中的图片
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["con"]);
SqlCommand com = new SqlCommand("select * from jpg ", con);
con.Open();
SqlDataReader sdr = com.ExecuteReader();
this.Response.ContentType = "image/gif";
while (sdr.Read())
{
Response.OutputStream.Write((byte[])sdr["imgname"], 0, ((byte[])sdr["imgname"]).Length);
}
con.Close();
5、在GridView页脚中添加控件
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
Label lab = new Label();
int count = mn.count();
lab.Text ="共" + count.ToString() + "条新闻";
TableCell tc = e.Row.Cells[0];
tc.Controls.Add(lab);
}
}
6、取得GridView中最后一行ID的值
private void gvbind()
{
DataSet ds = pg.First();
this.GridView1.DataSource = ds.Tables[0].DefaultView;
this.GridView1.DataBind();
ViewState["maxID"] = GridView1.DataKeys[GridView1.Rows.Count - 1].Value.ToString();//最后一行ID的值
ViewState["minID"] = GridView1.DataKeys[0].Value.ToString();//取得第一行ID的值
ViewState["CurrentPage"] = 1;
}
7、设置GridView页脚的格式
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[0].ColumnSpan = e.Row.Cells.Count;
while (e.Row.Cells.Count > 1)
{
e.Row.Cells.RemoveAt(1);
}
}
}
8、计算总页数
int count = Convert.ToInt32(数据库中总的记录数);
int pageCount = (count + 每页显示的记录数 - 1) / 每页显示的记录数;
9、分页SQL
select top 10 * from temptable order by id //第一页
select * from (select top 10 * from temptable where id<20 order by id desc) as t order by id //上一页
select top 10 * from temptable where id>100 order by id //下一页
select * from (select top 总记录数%每页显示的记录数 * from temptable order by id desc) as t order by t.id //最后页
select top 10 * from temptable where id> //到哪一页
( select max(id) from (
select top 20
id from temptable order by id )as t )
order by id
--select top 页大小 *
--from table1
--where id>
--(select max (id) from
--(select top ((页码-1)*页大小) id from table1 order by id) as T
--)
--order by id
10、文件上传以及根据大小生成缩略图
protected void Button1_Click(object sender, EventArgs e)
{
if (this.FileUpload1.HasFile)//判断上传的文件是否存在
{
string filename = this.FileUpload1.FileName;
string savepath = Server.MapPath("..""UpDateFile""Image""");
string strcheck = savepath + """" + filename;
if (System.IO.File.Exists(strcheck))//判断文件是否重名
{
int count = 2;
string temppath = "";
while (System.IO.File.Exists(strcheck))
{
temppath = count.ToString() + filename;
strcheck = savepath + temppath;
count += 1;
}
filename = temppath;
}
if (this.FileUpload1.PostedFile.ContentType.ToLower().IndexOf("image")<0)//判断上传的文件是否是图片格式
{
this.Label3.Text = "上传的文件类型错误!";
return;
}
else
{
savepath = savepath + filename;
this.FileUpload1.SaveAs(savepath);
string newname=this.getNewImage(filename);//如果上传的文件尺寸大于350像素则生成缩略图显示
string virpath=Page.Request.ApplicationPath + "/updatefile/image/" + newname;
this.Label4.Text =Server.HtmlEncode( "<img src='" + virpath + "'/>");
this.FreeTextBox1.Text = this.FreeTextBox1.Text + this.Label4.Text;
}
}
//this.FileUpload1.SaveAs(filepath + filename);
}
public bool ThumbnailCallback()
{
return false;
}
//生成缩略图
private string getNewImage(string upFileName)
{
System.Drawing.Image.GetThumbnailImageAbort myCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
Bitmap myBitmap = new Bitmap(Server.MapPath("~/updatefile/image/" + upFileName));
string newname = upFileName;
if (myBitmap.Width > 350)
{
int imgWidth = 350;//固定图片宽度
System.Drawing.Image myThumbnail = myBitmap.GetThumbnailImage(imgWidth, myBitmap.Height / (myBitmap.Width / imgWidth), myCallback, IntPtr.Zero);
Response.ContentType = "image/jpeg";
Bitmap newbmp = new Bitmap(myThumbnail);
newname="s_" + upFileName;
newbmp.Save(Server.MapPath("~/updatefile/image/" + newname ));
newbmp.Dispose();
}
return newname;
}
11、把ArrayList绑定到GridView
1.将ArrayList绑定到GridView是可以的,具体的实现请参考下述代码:
public class Info//需要用到这个类的实例来给ArrayList添加内容!!
{
public string Name;
public int VoteCount;
}
///假设我们已经有sqldatareader对象dr,并且已经获取的数据了
ArrayList myList = new ArrayList();//创建ArranList
while (dr.Read())
{
Info myinfo = new Info();//创建类Info的实例
myinfo.Name = dr["Name"].ToString();
myinfo.VoteCount = Int32.Parse(dr["VoteCount"].ToString());
myList.Add(myinfo);//添加Arranlist
}
dr.Close();
mygridView.DataSource = myList;//arrayList绑定到Gridview
mygridView.DataBind();
.aspx文件中绑定数据如下:
<%# ((Info)Container.DataItem).VoteCount %>
<%# ((Info)Container.DataItem).Name %>
12、加密函数
如果要队字符串加密可以使用FormsAuthentication.HashPasswordForStoringInConfigFile(要加密的字符串,MD5/SHA1)方法;
例:String str="aaa";
str=FormsAuthentication.HashPasswordForStoringInConfigFile(str,MD5);
13、删除GridView中选种的行
protected void Button2_Click(object sender, EventArgs e)
{
foreach (GridViewRow gr in this.GridView1.Rows)
{
CheckBox chk = (CheckBox)gr.FindControl("CheckBox1");
if (chk.Checked)
{
string id=(this.GridView1.DataKeys[gr.DataItemIndex].Value).ToString();
string sqlstr = "delete branch where id='"+ id +"'";
db.sqlcom(sqlstr);
}
}
this.gvbind();//重新绑定
}