※※※※※大公无私之asp.net常用功能搜集 2012集选
对回帖内容进行简单整理,制作简单导读目录:
布局:
63楼 布局
68楼 div兼容
js特效:
79 js拖动
82 js拖动
97 js 全选
66 弹出层
EXCEL操作
7、8楼 导出Excel
11楼 导入Excel
106楼 导出Excel
分页:
5 分页
12 分页
16、17 分页
118 分页(存储过程)
其他:
14、15 FTP类
38 TreeView
67 动态树、ASP.net文件上传等
73 异步查询用户是否存在
76 几个常用小工具
77 通用类
91、92 .net根据ip获得地址
93 虚拟键盘
134 常用工具
另外,感谢以下网友的分享:
mc_luzhi
Chinajiyong
jadilee
CODE163
ohkuy
qq283868910
tptptp00
qq283868910
tzh814
HJ850126
jarry42
[解决办法]
分页目前我只用过AspNetPager
/* 风格1 */
.paginator
{
font: 11px Arial, Helvetica, sans-serif;
padding: 10px 20px 10px 0;
margin: 0px;
}
.paginator a
{
padding: 1px 6px;
border: solid 1px #ddd;
background: #fff;
text-decoration: none;
margin-right: 2px;
}
.paginator a:visited
{
padding: 1px 6px;
border: solid 1px #ddd;
background: #fff;
text-decoration: none;
}
.paginator .cpb
{
padding: 1px 6px;
font-weight: bold;
font-size: 13px;
border: none;
}
.paginator a:hover
{
color: #fff;
background: #ffa501;
border-color: #ffa501;
text-decoration: none;
}
/* 风格2 */
.pages
{
font: 12px Arial, Helvetica, sans-serif;
padding: 5px 20px 5px 0;
margin-left: 10px;
}
.pages a, .pages .cpb
{
text-decoration: none;
float: left;
padding: 0 5px;
border: 1px solid #ddd;
background: #ffff;
margin: 0 2px;
font-size: 11px;
color: #000;
}
.pages a:hover
{
background-color: #E61636;
color: #fff;
border: 1px solid #E61636;
text-decoration: none;
}
.pages .cpb
{
font-weight: bold;
color: #fff;
background: #E61636;
border: 1px solid #E61636;
}
/* 风格3 */
.paginator
{
font: 12px Arial, Helvetica, sans-serif;
padding: 10px 20px 10px 0;
margin: 0px;
}
.paginator a
{
border: solid 1px #ccc;
color: #0063dc;
cursor: pointer;
text-decoration: none;
}
.paginator a:visited
{
padding: 1px 6px;
border: solid 1px #ddd;
background: #fff;
text-decoration: none;
}
.paginator .cpb
{
border: 1px solid #F50;
font-weight: 700;
color: #F50;
background-color: #ffeee5;
}
.paginator a:hover
{
border: solid 1px #F50;
color: #f60;
text-decoration: none;
}
.paginator a, .paginator a:visited, .paginator .cpb, .paginator a:hover
{
float: left;
height: 16px;
line-height: 16px;
min-width: 10px;
_width: 10px;
margin-right: 5px;
text-align: center;
white-space: nowrap;
font-size: 12px;
font-family: Arial,SimSun;
padding: 0 3px;
}
<webdiyer:AspNetPager ID="AspNetPager1" runat="server" AlwaysShow="True"
CssClass="paginator" CurrentPageButtonClass="cpb" Direction="LeftToRight"
FirstPageText="首页" LastPageText="尾页" LayoutType="Table" NextPageText="下一页"
onpagechanging="AspNetPager1_PageChanging" PageSize="10" PrevPageText="上一页"
ShowCustomInfoSection="Left" ShowInputBox="Never" Width="100%">
</webdiyer:AspNetPager>
DataTable dt = NewService.FindBySort();
PagedDataSource pds = new PagedDataSource();
pds.DataSource = dt.DefaultView;
pds.AllowPaging = true;
pds.CurrentPageIndex = AspNetPager1.CurrentPageIndex - 1;
pds.PageSize = AspNetPager1.PageSize;
AspNetPager1.RecordCount = dt.Rows.Count;
Repeater1.DataSource = pds;
Repeater1.DataBind();
this.AspNetPager1.CustomInfoHTML = string.Format("当前第{0}/{1}页 共{2}条记录 每页{3}条", new object[]
{
AspNetPager1.CurrentPageIndex,
AspNetPager1.PageCount,
AspNetPager1.RecordCount,
AspNetPager1.PageSize
});
//定义Range对象,此对象代表单元格区域
Range range;
int dcell = 1;
int rowindex = 0; int colindex = 0;
int rowcount = dtTemp.Rows.Count;
int colcount = dtTemp.Columns.Count;
try
{
//初始化 Application 对象 excelApp
excelApp = new Application();
//在工作薄的第一个工作表上创建任务列表
workBook = excelApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
ws = (Worksheet)workBook.Worksheets[1];
// 命名工作表的名称为
ws.Name = !string.IsNullOrEmpty(sName) ? sName : "Sheet1" ;
//创建缓存
Object[,] objdata = new object[rowcount + 1, colcount];
//创建标题
foreach (System.Data.DataColumn dc in dtTemp.Columns)
{
objdata[rowindex, colindex++] = dc.ColumnName;
}
//获取数据
for (int i = 0; i < rowcount; i++)
{
dcell = 0;
for (int j = 0; j < colcount; j++)
{
objdata[i + 1, dcell++] = dtTemp.Rows[i][dtTemp.Columns[j].ColumnName].ToString();
}
}
//写入Excel
range = ws.get_Range(excelApp.Cells[1, 1], excelApp.Cells[rowcount + 1, colcount]);
//range.NumberFormatLocal = "@";//所有字段格式化为文本格式
ws.get_Range(excelApp.Cells[2, fc], excelApp.Cells[rowcount + 1, fc]).NumberFormatLocal = "@";
range.Value2 = objdata;
System.Windows.Forms.Application.DoEvents();
//设置格式
range = ws.get_Range(excelApp.Cells[1, 1], excelApp.Cells[1, colcount]);
range.Font.Bold = true;//标题粗体
excelApp.Cells.HorizontalAlignment = Constants.xlCenter; //全局左对齐
excelApp.Cells.EntireColumn.AutoFit();
range = ws.get_Range(excelApp.Cells[1, 1], excelApp.Cells[rowcount + 1, colcount]);
range.Borders.LineStyle = 1;
//range.Font.Bold = true; //标题粗体
//显示 Excel
//excelApp.Visible = true;
workBook.SaveCopyAs(ServerPath.Replace("//", "\") + TextName + ".xls");
workBook.Close(false, null, null);
excelApp.Quit();
ws = null;
}
catch (Exception ex)
{
WriteLog.SetErrorMsg("ExportTasks", "", ex.Message); //处理错误
excelApp.Quit();
throw ex;
}
}
/// <summary>
/// 导出Excel
/// </summary>
/// <param name="dtTemp"></param>
public static void ExportCMB(System.Data.DataTable dtTemp, string ServerPath, string TextName)
{
// 定义要使用的Excel 组件接口
// 定义Application 对象,此对象表示整个Excel 程序
Application excelApp = null;
// 定义Workbook对象,此对象代表工作薄
Workbook workBook;
// 定义Worksheet 对象,此对象表示Execel 中的一张工作表
Worksheet ws = null;
//定义Range对象,此对象代表单元格区域
Range range;
int dcell = 1;
int colindex = 0;
int rowcount = dtTemp.Rows.Count;
int colcount = 14;
try
{
//初始化 Application 对象 excelApp
excelApp = new Application();
//在工作薄的第一个工作表上创建任务列表
workBook = excelApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
ws = (Worksheet)workBook.Worksheets[1];
// 命名工作表的名称为
ws.Name = "Sheet1";
//创建缓存
Object[,] objdata = new object[rowcount + 3, colcount];
objdata[0, 0] = "代发工资表";
objdata[1, 0] = "TF:QY1CWS1";
//创建标题
foreach (System.Data.DataColumn dc in dtTemp.Columns)
{
objdata[2, colindex++] = dc.ColumnName;
}
//获取数据
for (int i = 0; i < rowcount; i++)
{
dcell = 0;
for (int j = 0; j < colcount; j++)
{
objdata[i + 3, dcell++] = dtTemp.Rows[i][dtTemp.Columns[j].ColumnName].ToString();
}
}
//写入Excel
range = ws.get_Range(excelApp.Cells[1, 1], excelApp.Cells[rowcount + 3, colcount]);
ws.get_Range(excelApp.Cells[4, 12], excelApp.Cells[rowcount + 3, 12]).NumberFormatLocal = "@";
//range.NumberFormatLocal = "@";
range.Value2 = objdata;
range.Font.Size = 10;
System.Windows.Forms.Application.DoEvents();
//设置格式
excelApp.Cells.HorizontalAlignment = Constants.xlLeft; //全局左对齐
excelApp.Cells.EntireColumn.AutoFit();
range = ws.get_Range(excelApp.Cells[3, 1], excelApp.Cells[rowcount + 3, colcount]);
//range.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThick, XlColorIndex.xlColorIndexAutomatic, System.Drawing.Color.Black.ToArgb());
range.Borders.LineStyle = 1;
//显示 Excel
//excelApp.Visible = true;
workBook.SaveCopyAs(ServerPath.Replace("//", "\") + TextName + ".xls");
workBook.Close(false, null, null);
excelApp.Quit();
ws = null;
}
catch (Exception ex)
{
WriteLog.SetErrorMsg("ExportICBC", "", ex.Message); //处理错误
excelApp.Quit();
throw ex;
}
}
}
[解决办法]
再来个导出Word
public static void ExportToWord(DataGridView dgv, ProgressBar progress, SaveFileDialog savefile)
{
Microsoft.Office.Interop.Word.Document WordDoc = new Microsoft.Office.Interop.Word.Document();
Microsoft.Office.Interop.Word.Table WordTable;
object WordObj;
if (dgv.Rows.Count == 0)
{
return;
}
else
{
savefile.AddExtension = true;
savefile.DefaultExt = ".doc";
savefile.CreatePrompt = true;
savefile.Title = "导出文件保存路径";
savefile.Filter = "Word files (*.doc)
[解决办法]
*.doc";
if (savefile.ShowDialog() == DialogResult.OK)
{
progress.Visible = true;
object path = savefile.FileName;
WordObj = System.Reflection.Missing.Value;
//建立word对象
Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
WordDoc = word.Documents.Add(ref WordObj, ref WordObj, ref WordObj, ref WordObj);
//建立表格
//将数据生成word表格文件
WordTable = WordDoc.Tables.Add(WordDoc.Paragraphs.Last.Range, dgv.RowCount, dgv.ColumnCount, ref WordObj, ref WordObj);
WordTable.Columns.SetWidth(50, Microsoft.Office.Interop.Word.WdRulerStyle.wdAdjustNone);
try
{
for (int i = 0; i < dgv.Columns.Count; i++)//设置标题
{
WordTable.Cell(0, i + 1).Range.Text = dgv.Columns[i].HeaderText;
WordTable.Cell(0, i + 1).Range.Font.Size = 5;
}
for (int i = 1; i < dgv.Rows.Count; i++)//填充数据
{
for (int j = 0; j < dgv.Columns.Count; j++)
{
WordTable.Cell(i + 1, j + 1).Range.Text = dgv[j, i - 1].Value.ToString();
WordTable.Cell(i+1, j + 1).Range.Font.Size = 5;
}
progress.Value += 100 / dgv.RowCount;
}
WordDoc.SaveAs(ref path, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj);
WordDoc.Close(ref WordObj, ref WordObj, ref WordObj);
progress.Value = 100;
MessageBox.Show("数据已经成功导出到:" + savefile.FileName.ToString(), "导出完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
progress.Value = 0;
progress.Visible = false;
}
catch (Exception e)
{
MessageBox.Show(e.Message, "友情提示", MessageBoxButtons.OK);
}
finally
{
word.Quit(ref WordObj, ref WordObj, ref WordObj);
}
}
}
}
[解决办法]
导入Excel
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = null;
string path = "", f_folder, f_name;
int j = 0;
try
{
path = this.FileUpload1.FileName;
if (path == "")
{
Response.Write("<script>alert('请选择Excel文件路径!')</script>");
return;
}
f_name = System.DateTime.Now.ToString();
f_name = f_name.Replace(" ", "");
f_name = f_name.Replace("-", "");
f_name = f_name.Replace(":", "");
f_name = f_name.Replace("/", "");
f_folder = Server.MapPath(@"../upfile/" + f_name + ".xls");
this.FileUpload1.PostedFile.SaveAs(f_folder);
// string sheetname = this.txtTable_Name.Text.Trim();
dt = ExcelDataSource(f_folder, "Sheet1");
for (int i = 0; i < dt.Rows.Count; i++)
{
Cut c = new Cut();
c.Name=dt.Rows[i]["优惠券号"].ToString();
c.Cuts = dt.Rows[i]["折扣"].ToString();
if (CutsManager.Add(c) == "1")
{
j++;
}
}
if (File.Exists(Server.MapPath(@"../upfile/" + f_name + ".xls")))
{
File.Delete(f_folder);
}
string s = "成功导入输入" + j + "条!";
if (j == dt.Rows.Count)
{
Response.Write("<script>alert('" + s + "')</script>");
}
}
catch
{
Response.Write("<script>alert('数据格式出错!')</script>");
}
}
public DataTable ExcelDataSource(string filepath, string sheetname)
{
string strConn = String.Empty;
if (System.IO.Path.GetExtension(filepath).Equals(".xlsx"))
{
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties='Excel 12.0;HDR=YES';data source=" + filepath;
}
else if (System.IO.Path.GetExtension(filepath).Equals(".xls"))
{
//strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filepath + ";" + "Extended Properties=Excel 8.0;";
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties=Excel 8.0;";
}
OleDbConnection conn = new OleDbConnection(strConn);
OleDbDataAdapter oada = new OleDbDataAdapter("select * from [" + sheetname + "$]", strConn);
DataTable ds = new DataTable();
oada.Fill(ds);
conn.Close();
return ds;
}
@IsCount BIT --是否获得记录数,0为否
AS
DECLARE @SQL VARCHAR(8000)
IF @IsCount != 0
SET @SQL = 'SELECT Count(*) FROM ' + @Table + ' WHERE ' + @Condition
ELSE
BEGIN
IF @PageNumber = 1
SET @SQL = 'SELECT TOP ' + STR(@PageSize) + ' SerialNum AS 流水号,PatientName AS 病人姓名,CheckDate AS 检查日期 FROM ' + @Table + ' WHERE ' + @Condition
ELSE
SET @SQL = 'SELECT TOP ' + STR(@PageSize) + ' SerialNum AS 流水号,PatientName AS 病人姓名,CheckDate AS 检查日期 FROM ' + @Table +
' WHERE ' + @Primarykey + ' NOT IN (SELECT TOP ' + STR(@PageSize*(@PageNumber - 1))
+ ' ' + @Primarykey + ' FROM ' + @Table + ' WHERE ' + @Condition + ') AND ' + @Condition
END
EXEC(@SQL)
RETURN
调用函数
public static DataTable GetPatientInfo(string Condition, string StoreProcedure, int pageNumber, int PageSize, int isCount)
{
SqlParameter[] sqlParameter =
{
new SqlParameter("@Table","CheckRecord"),
new SqlParameter("@Primarykey","SerialNum"),
new SqlParameter("@Condition",Condition),
new SqlParameter("@PageNumber",pageNumber),
new SqlParameter("@PageSize",PageSize),
new SqlParameter("@IsCount",isCount)
};
using (SqlConnection sqlConnection = new SqlConnection(WebConfig.ConnectionString))
{
try
{
sqlConnection.Open();
SqlCommand sqlcommand = new SqlCommand(StoreProcedure, sqlConnection);
sqlcommand.CommandType = CommandType.StoredProcedure;
sqlcommand.Parameters.AddRange(sqlParameter);
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
sqlDataAdapter.SelectCommand = sqlcommand;
DataTable dt = new DataTable();
sqlDataAdapter.Fill(dt);
return dt;
}
catch (SqlException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
}
[解决办法]
再来个FTP类
public class FtpFile
{
string ftpServerIP;
public string FtpServerIP
{
get { return ftpServerIP; }
set { ftpServerIP = value; }
}
string ftpUserID;
public string FtpUserID
{
get { return ftpUserID; }
set { ftpUserID = value; }
}
string ftpPassword;
public string FtpPassword
{
get { return ftpPassword; }
set { ftpPassword = value; }
}
FtpWebRequest reqFTP;
public static string FtpServer = System.Configuration.ConfigurationSettings.AppSettings["FtpServer"];
public static string FtpUser = System.Configuration.ConfigurationSettings.AppSettings["FtpUser"];
public static string FtpPwd = System.Configuration.ConfigurationSettings.AppSettings["FtpPwd"];
private void Connect(String path)//连接ftp
{
// 根据uri创建FtpWebRequest对象
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
// 指定数据传输类型
reqFTP.UseBinary = true;
// ftp用户名和密码
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
}
public FtpFile(string ftpServerIP, string ftpUserID, string ftpPassword)
{
this.ftpServerIP = ftpServerIP;
this.ftpUserID = ftpUserID;
this.ftpPassword = ftpPassword;
}
public FtpFile()
{
this.ftpServerIP = FtpServer;
this.ftpUserID = FtpUser;
this.ftpPassword = FtpPwd;
}
//都调用这个
private string[] GetFileList(string path, string WRMethods)//上面的代码示例了如何从ftp服务器上获得文件列表
{
string[] downloadFiles;
StringBuilder result = new StringBuilder();
try
{
Connect(path);
reqFTP.Method = WRMethods;
WebResponse response = reqFTP.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);//中文文件名
string line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
// to remove the trailing '\n'
result.Remove(result.ToString().LastIndexOf('\n'), 1);
reader.Close();
response.Close();
return result.ToString().Split('\n');
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
downloadFiles = null;
return downloadFiles;
}
}
public string[] GetFileList(string path)//上面的代码示例了如何从ftp服务器上获得文件列表
{
return GetFileList("ftp://" + ftpServerIP + path, WebRequestMethods.Ftp.ListDirectory);
}
public string[] GetFileList()//上面的代码示例了如何从ftp服务器上获得文件列表
{
return GetFileList("ftp://" + ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectory);
}
public string Upload(string filedir,string filename) //上面的代码实现了从ftp服务器上载文件的功能
{
FileInfo fileInf = new FileInfo(filename);
string uri = "ftp://" + ftpServerIP + filedir + fileInf.Name;
Connect(uri);//连接
// 默认为true,连接不会被关闭
// 在一个命令之后被执行
reqFTP.KeepAlive = false;
// 指定执行什么命令
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
// 上传文件时通知服务器文件的大小
reqFTP.ContentLength = fileInf.Length;
// 缓冲大小设置为kb
int buffLength = 2048*5;
byte[] buff = new byte[buffLength];
int contentLen;
// 打开一个文件流(System.IO.FileStream) 去读上传的文件
FileStream fs = fileInf.OpenRead();
try
{
// 把上传的文件写入流
Stream strm = reqFTP.GetRequestStream();
// 每次读文件流的kb
contentLen = fs.Read(buff, 0, buffLength);
// 流内容没有结束
while (contentLen != 0)
{
// 把内容从file stream 写入upload stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
// 关闭两个流
strm.Close();
fs.Close();
return "";
}
catch (Exception ex)
{
return "Upload Error" + ex.Message;
}
}
/// <summary>
/// 下载文件
/// </summary>
/// <param name="filedir">文件夹地址:必须是服务器根级相对地址,比如"/ftpFiles/images"</param>
/// <param name="filePath">下载文件新路径,但不包含文件名,如:D:\Photo</param>
/// <param name="fileName">ftp文件绝对路径,如:ftp://127.0.0.1/Photo/1.bmp</param>
/// <returns></returns>
public string Download(string filedir,string filePath, string fileName)////上面的代码实现了从ftp服务器下载文件的功能
{
try
{
String onlyFileName = Path.GetFileName(fileName);
string newFileName = filePath + "\" + onlyFileName;
if (File.Exists(newFileName))
{
return "本地文件" + newFileName + "已存在,无法下载";
}
string url = "ftp://" + ftpServerIP + filedir + onlyFileName;
Connect(url);//连接
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 2048*5;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
FileStream outputStream = new FileStream(newFileName, FileMode.Create);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
return "";
}
catch (Exception ex)
{
return "因" + ex.Message + ",无法下载";
}
}
//删除文件
public void DeleteFileName(string filedir,string fileName)
{
try
{
string fName= Path.GetFileName(fileName);
string uri = "ftp://" + ftpServerIP + filedir+fName;
Connect(uri);//连接
// 默认为true,连接不会被关闭
// 在一个命令之后被执行
reqFTP.KeepAlive = false;
// 指定执行什么命令
reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
response.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "删除错误");
}
}
//创建目录
public string MakeDir(string dirName)
{
try
{
string uri = "ftp://" + ftpServerIP + "/" + dirName;
Connect(uri);//连接
reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
response.Close();
return "";
}
catch (WebException ex)
{
return "[Make Dir]" + ex.Message;
}
}
//删除目录
public void delDir(string dirName)
{
try
{
string uri = "ftp://" + ftpServerIP + "/" + dirName;
Connect(uri);//连接
reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
response.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//获得文件大小
public long GetFileSize(string filename)
{
long fileSize = 0;
try
{
FileInfo fileInf = new FileInfo(filename);
string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
Connect(uri);//连接
reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
fileSize = response.ContentLength;
response.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return fileSize;
}
//文件改名
public void Rename(string currentFilename, string newFilename)
{
try
{
FileInfo fileInf = new FileInfo(currentFilename);
string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
Connect(uri);//连接
reqFTP.Method = WebRequestMethods.Ftp.Rename;
reqFTP.RenameTo = newFilename;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
//Stream ftpStream = response.GetResponseStream();
//ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//获得文件明晰
public string[] GetFilesDetailList()
{
return GetFileList("ftp://" + ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectoryDetails);
}
//获得文件明晰
public string[] GetFilesDetailList(string path)
{
return GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectoryDetails);
}
}
int CurrentIndex;//当前页数
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataBinds();
}
}
protected void DataBinds()
{
SqlConnection cn = new SqlConnection("Data Source=.;Initial Catalog=Test;Integrated Security=True");//连接并实例化数据库
string sql = "select * from Student";//定义查询语句
SqlDataAdapter da = new SqlDataAdapter(sql, cn);//实例化对象Adapter
DataSet ds = new DataSet();//实例化DataSet
da.Fill(ds, "Student");//填充
PagedDataSource pds = new PagedDataSource();//初始化分页事例
pds.DataSource = ds.Tables["Student"].DefaultView;
pds.AllowPaging = true;//启动分页
pds.PageSize = 5;//每页显示的个数
CurrentIndex = int.Parse(this.Label1.Text) - 1;//获取当前页数索引
pds.CurrentPageIndex = CurrentIndex;
if (CurrentIndex == 0)
{//如果是第一页,上一页和第一页的控件不可点击
this.PreviousLB.Enabled = false;
this.FirstLB.Enabled = false;
this.NextLB.Enabled = true;
this.EndLB.Enabled = true;
}
else if (CurrentIndex == pds.PageCount - 1)
{
//如果是最后一页,下一页和最后一页空间不可点击
this.PreviousLB.Enabled = true;
this.FirstLB.Enabled = true;
this.NextLB.Enabled = false;
this.EndLB.Enabled = false;
}
else
{
this.PreviousLB.Enabled = true;
this.FirstLB.Enabled = true;
this.NextLB.Enabled = true;
this.EndLB.Enabled = true;
}
this.Label2.Text = pds.PageCount.ToString();//获取总页数
DataList1.DataSource = pds;//绑定DataList数据
DataList1.DataBind();
}
protected void FirstLB_Click(object sender, EventArgs e)//首页
{
this.Label1.Text = "1";//页数为1
DataBinds();
}
protected void PreviousLB_Click(object sender, EventArgs e)
{
this.Label1.Text = (int.Parse(Label1.Text) - 1).ToString();//页数减1
DataBinds();
}
protected void NextLB_Click(object sender, EventArgs e)//下一页
{
this.Label1.Text = (int.Parse(this.Label1.Text) + 1).ToString();//页数加1
DataBinds();
}
protected void EndLB_Click(object sender, EventArgs e)//末页
{
this.Label1.Text = Label2.Text;//页数为最后一页
DataBinds();
}
protected void JumpLB_Click(object sender, EventArgs e)
{
try
{
if (int.Parse(TextBox1.Text) > 0 && int.Parse(TextBox1.Text) <= int.Parse(Label2.Text))
{
this.Label1.Text = TextBox1.Text;
DataBinds();
}
else
{
Response.Write("<script>alert('请输入有效数字')</script>");
TextBox1.Text = null;
}
}
catch
{
Response.Write("<script>alert('系统出错')</script>");
Response.Redirect("~/Default.aspx");
}
}
<script type="text/javascript">
$(function(){
var $winH = $(window).height();//获取窗口高度
var $img = $("#show img");
var $imgH = parseInt($img.height()/2);//图片到一半的时候显示
var $srcDef = "a.gif";
runing();//页面刚载入时判断要显示的图片
//****************************************
$(window).scroll(function(){
runing();//滚动刷新
})
//****************************************
function runing(){
$img.each(function(i){//遍历img
var $src = $img.eq(i).attr("original");//获取当前img URL地址
var $scroTop = $img.eq(i).offset();//获取图片位置
if($scroTop.top + $imgH >= $(window).scrollTop() && $(window).scrollTop() + $winH >= $scroTop.top + $imgH){//判断窗口至上往下的位置
if($img.eq(i).attr("src") == $srcDef){
$img.eq(i).hide();
}
$img.eq(i).attr("src",function(){return $src}).fadeIn(300);//元素属性的交换
}
})
}
})
</script>
<div id="show">
页面内容
<div>
#region Treeview 选择实现
public static class TreeViewCheck
{
/// <summary>
/// 系列节点 Checked 属性控制
/// </summary>
/// <param name="e"></param>
public static void CheckControl(TreeViewEventArgs e, TreeNodeCollection tv)
{
if (e.Action != TreeViewAction.Unknown)
{
if (e.Node != null && !Convert.IsDBNull(e.Node))
{
CheckParentNode(e.Node);
if (e.Node.Nodes.Count > 0)
{
CheckAllChildNodes(e.Node, e.Node.Checked);
}
}
}
}
#region 私有方法
//改变所有子节点的状态
public static void CheckAllChildNodes(TreeNode pn, bool IsChecked)
{
foreach (TreeNode tn in pn.Nodes)
{
tn.Checked = IsChecked;
if (tn.Nodes.Count > 0)
{
CheckAllChildNodes(tn, IsChecked);
}
}
}
//改变父节点的选中状态,此处为所有子节点不选中时才取消父节点选中,可以根据需要修改
public static void CheckParentNode(TreeNode curNode)
{
bool bChecked = false;
if (curNode.Parent != null)
{
foreach (TreeNode node in curNode.Parent.Nodes)
{
if (node.Checked)
{
bChecked = true;
break;
}
}
if (bChecked)
{
curNode.Parent.Checked = true;
CheckParentNode(curNode.Parent);
}
else
{
curNode.Parent.Checked = false;
CheckParentNode(curNode.Parent);
}
}
}
#endregion
}
#endregion Treeview 选择实现
//TreeView节点连载
private void tv_RightList_AfterCheck(object sender, TreeViewEventArgs e)
{
TreeViewCheck.CheckControl(e, tv_selectItem.Nodes);
}
}
/*定义基本样式*/
ul.cardUl{
width:230px;
font-family:"Microsoft Yahei";
font-size:14px;
list-style-type:none;
text-align:center;
height:25px;
font-weight: bold;
line-height: 25px;
}
/*默认样式下使用css文件*/
ul.cardUl li{
font-family:"Microsoft Yahei";
width:115px;
height:25px;
background:url(images/rm1.gif) left top no-repeat;
float:left;
color:#666666;
/*另一边提供空间*/
}
ul.cardUl li a{
width:115px;
float:left;
height:25px;
background:url(images/rm1.gif) right top no-repeat;
display:block;
color:#666666;
white-space: nowrap;
}
/*文字点击使用CSS*/
ul.cardUl li.Selected{
width:115px;
background:url(images/rm2.gif) left top no-repeat;
color:#666666;
}
ul.cardUl li.Selected a{
width:115px;
background:url(images/rm2.gif) right top no-repeat;
color:#A70103;
}
/*对点击下栏显示边框的代码进行美化*/
div.hackBox{
display:none;
}
</style>
<script>
//为选项卡的默认值进行设定,方法为读取cardBar里面的li标签是否已经有selected属性,如果没有则使用默认值。
function loadTab(){
//读取cardBar下面所有li标签
var getId=document.getElementById("cardBar").getElementsByTagName("li");
//定义一个判断是否有selected的变量
var selectedItems=0;
//判断方法,循环读出li标签的className,如果有则selectedItems加1
for(i=0;i<getId.length;i++){
if (getId[i].className == "Selected"){
selectedItems+=1;
}
}
//经过循环,如果selectedItems没有数值,那么说明没有selected的标签,因此给标签加上默认的className
if (selectedItems==0){
document.getElementById("cardBar").getElementsByTagName("li")[0].className="Selected";
document.getElementById("Dcard1").style.display="block";
}
}
//让窗口打开就运行他
window.onload=loadTab;
//设定结束
//进行选项卡效果的触发
function switchTab(cardBar,cardId){
//读取cardBar下面所有li标签
var oItems = document.getElementById(cardBar).getElementsByTagName("li");
//循环清空li标签下面的selected效果
for (i=0;i<oItems.length;i++ ){
var x=oItems[i];
x.className="";
// var y=x.getElementsByTagName("a");
// y[0].style.color="#ffffff";
}
//开始选项卡效果的赋值,为选中的li标签增加selected类的属性
document.getElementById(cardId).className="Selected";
//读出cardContent 下面的所有div标签
var dvs=document.getElementById("cardContent").getElementsByTagName("div");
//循环,判断应该显示的div
for (i=0;i<dvs.length;i++ ){
if (dvs[i].id==("D"+cardId)){
dvs[i].style.display="block";
}else{
dvs[i].style.display="none";
}
}
}
</script>
<ul class="cardUl" id="cardBar">
<li id="card1"><a href="#" onMouseOver="javascript:switchTab('cardBar','card1');">戒指</a></li>
<li id="card2"><a href="#" onMouseOver="javascript:switchTab('cardBar','card2');">项链吊坠</a></li>
</ul>
<div id="cardContent">
<div id="Dcard1" class="hackBox">戒指内容</div>
<div id="Dcard2" class="hackBox">项链吊坠内容</div>
[解决办法]
来个异步查询用户名是否存在
index.aspx
<script type="text/javascript" language="javascript">
function validateloginname()
{
var loginname=document.getElementById("Text1").value;
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlHttp.onreadystatechange=getdata;
xmlHttp.Open("GET","validate.aspx?loginname="+loginname,true);
xmlHttp.Send();
}
function getdata()
{
if(xmlHttp.readystate==4)
{
if(xmlHttp.status==200)
{
var text=xmlHttp.responseText;
if(text=="1")
{
document.getElementById("td1").innerHTML="用户名已存在";
document.getElementById("Text1").style.borderColor="Black";
document.getElementById("Text1").focus();
document.getElementById("Text1").value="";
}
else
{
document.getElementById("td1").innerHTML="OK";
document.getElementById("Text1").style.borderColor="Red";
}
}
}
}
</script>
<td>
<input id="Text1" type="text" runat="server" onblur="validateloginname()" />
</td>
<td id="td1">
</td>
protected void Page_Load(object sender, EventArgs e)
{
string loginname = Request.QueryString["loginname"];
if (loginname == "mcluzhi")
{
Response.Write("1");
}
else
{
Response.Write("0");
}
}
public class Information
{
public Information()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 弹出消息框并且转向到新的URL
/// </summary>
/// /// <summary>
/// Literal弹出消息
/// </summary>
/// <param name="msg">消息内容</param>
/// <param name="lt">Literal控件</param>
public static void MessageInfor(string msg, Literal lt, string url)
{
if (url != "")//url不为空,跳转页面
{
lt.Text = "<script>alert('" + msg.Replace("'", string.Empty) + "');location.href='" + url + "'</script>";
}
else
{
lt.Text = "<script>alert('" + msg.Replace("'", string.Empty) + "')</script>";
}
}
/// <summary>
/// 弹出指定大小的新窗体
/// </summary>
public static void OpenWindowKind(string url, int width, int heigth, int top, int left)
{
string js = "<script language='JavaScript'>window.open('{0}', '', 'width={1}, height={2}, top={3}, left={4}, location=no, menubar=no, resizable=yes, scrollbars=yes, status=yes, titlebar=no, toolbar=no, directories=no');</script>";
HttpContext.Current.Response.Write(string.Format(js, url, width, heigth, top, left));
}
/// <summary>
/// 弹出新页面
/// </summary>
public static void OpenWindow(string url)
{
string js = "<script language='JavaScript'>window.open('{0}');</script>";
HttpContext.Current.Response.Write(string.Format(js,url));
}
}
javascript 模仿windows拖动 封装类
/**
* CreateDate 2011-8-22 18:34:34
*
* @type Javascript Document
*
* Description of moveElement.class
*
* @example drop.reg("span","div");
*
*/
var drop={
reg: function (handler, movediv, cursor) { // 注册鼠标移动的一些事件。
var isclick = false;
var clickleft = 0;
var clicktop = 0;
var target = this.$(handler);
var movediv = this.$(movediv);
movediv.style.position="absolute";
target.style.cursor = cursor
[解决办法]
"move";
function clickdrop(e) { // 按下鼠标左键时的事件。
e = window.event