杂项
来源:互联网 发布:软件项目开发报告 编辑:程序博客网 时间:2024/04/30 08:36
1 button并无target属性,但且可以通过javascript实现。具体是:在单击button事件中添加
Page.RegisterStartupScript("js", "<script>window.open('xxx.aspx','main','',false); </script>");。
xxx.apsx是你要显示的页面,main是你框架取的name,id名!
2 asp.net中数字不够六位补0: int i = 123; string str = string.Format("{0:D6}", i); Response.Write(str);
3两个List去除重复项:
List<int> lstFromWeb = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; List<int> lstFromDB = new List<int> { 2, 3, 4, 7, 8 ,9};
List<int> newList = lstFromWeb.FindAll(y => !lstFromDB.Contains(y));//得到新的list 除去在fromdb含有的数据
for (int i = 0; i < newList.Count; i++)
{
Response.Write(newList[i]+",");
}
4 /// <summary>
/// 获取文件夹大小我这里转换为MB了
/// </summary>
/// <param name="dirp">文件夹目录</param>
/// <returns></returns>
private int getsize(string dirp)
{
DirectoryInfo mydir = new DirectoryInfo(dirp);
int str=0;
foreach (FileSystemInfo fsi in mydir.GetFileSystemInfos())
{
if (fsi is FileInfo)
{
FileInfo fi = (FileInfo)fsi;
str += Convert.ToInt32(fi.Length);//int.Parse(fi.Length.ToString());
}
else
{
DirectoryInfo di = (DirectoryInfo)fsi;
string new_dir = di.FullName;
getsize(new_dir);
}
}
return str/(1024*1024);//转换为MB
}
5 /// <summary>
/// 获取文件大小
/// </summary>
/// <param name="fileaddress">文件路径(相对路径)</param>
/// <returns></returns>
protected string get(string fileaddress)
{
string filename = Server.MapPath(fileaddress.Replace("~", ""));
FileInfo file = new FileInfo(filename);
if (file.Exists)
{
return filename.Substring(filename.LastIndexOf(".")).ToLower() + " - " + ((file.Length) / (1024.00 * 1024.00)).ToString("0.00") + "M";
}
else
{
return "no file";
}
}
6 asp.net调用本地应用程序
1 命名空间:using System.Diagnostics;
2 Process ps = new Process();
ps.StartInfo.FileName = @"E:\360杀毒软件\360se\360SE.exe";
ps.StartInfo.Arguments = "http://www.sogou.com ";
ps.Start();
7.按钮只能点击1此
<asp:Button ID="Button1" runat="server" Text="提交" OnClick="Button1_Click" UseSubmitBehavior="False" OnClientClick="this.value='已经留言了';this.disabled=true;"/>
其实就是 在按钮的OnClientClick写下脚本 this.value='已经留言了';this.disabled=true;
8. datalist里面找控件
1 DataList1.Items(i).FindControl("ck1")外面找好像
2在DataList1_ItemDataBound事件中找:
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Label Lable1 = (Label)e.Item.FindControl( "lblTime ");
Panel Panel2 = (Panel)e.Item.FindControl( "Panel1 ");
if ( Label1.Text == " ")
{
Panel2.Visible = true;
}
}
}
9. datatable导出为excel表格
(1)/// <summary>
/// datatable数据源导出excel表
/// </summary>
/// <param name="dt">datatable数据源</param>
/// <param name="zprice">合计(其实只要dt即可)</param>
/// <param name="title">表头</param>
public void ExcelOutTest(DataTable dt,string zprice,string title)
{//导出Excel表的方法
StringWriter sw = new StringWriter();
sw.WriteLine("烟草公司"+title+"耗材领用表");
sw.WriteLine("商品名称,出库日期,出库数量,单价,小计");//标题
foreach (DataRow dr in dt.Rows)
{//字段名
sw.WriteLine(dr["name"].ToString() + "," + dr["odate"].ToString() + "," + dr["onum"].ToString() + "," + dr["dprice"].ToString() + "," + dr["zj"].ToString());
}
sw.WriteLine("合计,,,,"+zprice);//标题
sw.Close();
string name = DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv";//以当前时间为excel表命名
Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(name));
Response.ContentType = "vnd.ms-excel.numberformat:yyyy-MM-dd ";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.Write(sw);
Response.End();
}
(2) 导出按钮
protected void BtnOutexcel_Click(object sender, EventArgs e)
{
OutKu outku = new OutKu();
string operson, stime, etime;
operson = "";
if (!string.IsNullOrEmpty(TbStime.Text))
{
stime = TbStime.Text;
}
else
{
stime = "";
}
if (!string.IsNullOrEmpty(TbEtime.Text))
{
etime = TbEtime.Text;
}
else
{
etime = "";
}
string state = "已通过";
DataTable dt = outku.Sel_OutKuByPerson(operson, state, stime, etime);
string s = "1,1,1,1,100,333,666,,1";
object[] parm = s.Split(',');
dt.Rows.Add(parm);//添加一行
string zprice = dt.Compute("sum(zj)", "").ToString();
ExcelOutTest(dt, zprice, LbTitle.Text);
}
10. dropdownlist绑定值!
public void SonSort()
{
P_infos p = new P_infos();
DSonSort.DataSource = p.AllSonSort();
DSonSort.DataValueField = "sonid";//要指定列名
DSonSort.DataTextField = "ssort";
DSonSort.DataBind();
}
11. freetextbox出错解决方法:
在web.config中
<pages validateRequest="false">
12. Gridview如何找控件:
string r = e.CommandArgument.ToString();
GridViewRow gvrow = (GridViewRow)(((Button)e.CommandSource).NamingContainer);//(这行必须有button才行(imagebutton也行),否则找不到值)
// 获取到行索引 RowIndex
int index = gvrow.RowIndex;
Label LbUrl = (Label)(GVInfo.Rows[index].Cells[7].FindControl("LbFiles")); //找label控件
13 Gridview中计算某一列值的和:
1 注意:ds.Tables[0]为查出来的表
ds.Tables[0].Compute( "sum(你要统计的字段) ", " ").ToString()来直接计算出来
2 int sum = 0;
for (int i = 0; i < this.GridView1.Rows.Count; i++)
{
GridViewRow row=this.GridView1.Rows[i];
sum=sum+Convert.ToInt32(row.Cells[21].Text.ToString());
}
Response.Write(sum.ToString());
14 Gridview通过值改变颜色:
public void ChanageFontColor( )
{
for (int i = 0; i < GvBuySheet.Rows.Count; i++)
{
Label lbstate = (Label)(GvBuySheet.Rows[i].Cells[5].FindControl("LbState"));
if (lbstate.Text == "不通过")
{
lbstate.ForeColor = System.Drawing.Color.Red;
}
else
{
lbstate.ForeColor = System.Drawing.Color.Blue;
}
}
}
15 GridView 隐藏列代码:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
string a = "1,2,3";//比如a 是你要隐藏的列,以字符串形式展现
string[] a_list = a.Split(',');
for (int i = 0; i < a_list.Length; i++)
{
int num=Convert.ToInt32(a_list[i]);
e.Row.Cells[num].Visible = false;
}
}
16. Gridview帮顶自增长编号:
(1)<%#Container.DataItemIndex+1%> 产生行号的列里绑定
(2)要在Gridview_Databind里面写:自动生成编号
if (e.Row.RowIndex != -1)
{
int id = e.Row.RowIndex + 1;
e.Row.Cells[0].Text = id.ToString();
}
17. js在html中可用,在aspx中不可用解决方法:
同样是编码问题,这个不修改webconfig而是修改文件头,
<%@ Page ContentType=”text/html” ResponseEncoding=”gb2312″ %>
18. js添加行下面是个页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<script type="text/javascript">
function contactlist(){
var table = document.getElementById("contactTable");
var tr = table.insertRow(table.rows.length);//添加一行
tr.align="center";
tr.bgcolor="#F3F4F3";
tr.height="23";
//添加五列
var td0 = tr.insertCell(0);
td0.width="20%";
var td1 = tr.insertCell(1);
td1.width="20%";
var td2 = tr.insertCell(2);
td2.width="8%";
var td3 = tr.insertCell(3);
td3.width="30%";
var td4 = tr.insertCell(4);
td4.width="20%";
//设置列内容
td0.innerHTML = "";
td1.innerHTML = "<input type='file' id='dataAudio' name='dataAudio'/><input type='hidden' name='dataAudios'/><input type='hidden' name='audioOldName'/>";
td2.innerHTML = "<input type='text' name='playDateTime' id='playDateTime' onkeyup='validateNumber(this);' size='5' maxlength='3' style='color: red' />";
td3.innerHTML = "<input type='text' name='content' id='content' size='35' maxlength='300'/>";
td4.innerHTML = "<input type='button' value='删除' onclick='removeRow(this.parentNode.parentNode)'/>";
}
function removeRow(r)
{
var root = r.parentNode;
var allRows = root.getElementsByTagName('tr');
if(allRows.length > 3){
root.removeChild(r);
}else{
alert("不能删除改行!");
}
}
function deleteAll() {
var table = document.getElementById("contactTable");
var tableLength = table.rows.length;
for(var int = 2;int < tableLength;int++) {
table.deleteRow(2);
}
}
</script >
</head>
<body>
<table id="contactTable" width="98%" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#D9D9D9">
<tr bgcolor="#F3F4F3" align="center" height="23">
<td colspan="5" align="left"><input type="button" value="添加帧" class="button" onclick="return contactlist();"/></td>
</tr>
<tr bgcolor="#F3F4F3" align="center" height="23">
<td width="20%">上传图片</td>
<td width="20%">上传声音</td>
<td width="8%">播放时间</td>
<td width="30%">内 容</td>
<td width="20%">操作</td>
</tr>
</table>
<input type='button' value='删除全部' onclick='deleteAll();'/>
</body>
</html>
19. 按钮隐藏和显示table:
<script language="javascript" type="text/javascript">
function y6()
{
document.getElementById('t6').style.display = "none"; //隐藏t6
}
function x6()
{
document.getElementById('t6').style.display = "block";//显示t6
}
</script>
//隐藏按钮
protected void Button1_Click(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(GetType(), "yes", "y6();", true);
}
//显示按钮
protected void Button2_Click(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(GetType(), "yes", "x6();", true);
}
20.js判断页面是否存在某个控件!
var obj=document.all.banid;
if(obj)
{
alert("有班");
}
else
{
alert("没班");
}
//其中“banid”就是控件的id或name
21. asp.net中Message的使用:
1 using System.Windows.Forms;
在Bin哪也要引用System.Windows.Forms;
2 MessageBox.Show("yes","系统提示");
MessageBox.Show("删除失败,请稍后重试!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Stop);
22.n个整数数取其中的最大和最小值:
int[] arr = {9,12,1, 2, 4, 5, 6 };
ArrayList list = new ArrayList(arr);
list.Sort();//排序是按从小到大的顺序
int min = Convert.ToInt32(list[0]);//第一个为小
int max = Convert.ToInt32(list[list.Count - 1]);最后一个,最大
Response.Write("最大" + max + " 最小:" + min);
23. n秒后自动关闭页面:
onload="setTimeout('self.close();',5000)"
24.Rowcommand中commandName的用法:
Gridview的RowCommand事件中各ComandName事件的处理方法:(先做如下设置)
1.将linkbutton的CommandName属性设置为“changepwd” 并绑定gridview的主键值
2. <asp:LinkButton ID="LbChangePwd" runat="server" CommandArgument='<%#Eval("uid") %>'
CommandName="changepwd">密码重置</asp:LinkButton>
protected void GVuser_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "changepwd")
{
//Response.Write("<script>alert('修改失败!');location='AllBzUsers.aspx'</script>");
BzUsers buser = new BzUsers();
string newpwd = "123";
int uid = Convert.ToInt32(e.CommandArgument.ToString()); //取选中行的主键值
if (buser.CzChangePwd(uid, newpwd))
{
Response.Write("<script>alert('修改成功!');location='AllBzUsers.aspx'</script>");
}
else
{
Response.Write("<script>alert('修改失败!');location='AllBzUsers.aspx'</script>");
}
}
if (e.CommandName == "del")
{}
if (e.CommandName == "edit")
{}
}
25.sql 创建修改表:
1标准版,sqlserver中导出的.
CREATE TABLE [dbo].[Test ](
[id] [int] primary key IDENTITY(1,1) NOT NULL, //主键(primary key)自增1(IDENTITY(1,1) )
[name] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
[aid] [datetime] NULL,
[bid] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL
)
2 自己写的创建
create table test2
(
id int primary key identity(1,1) ,
name varchar(60)
)
//1 2 创建表
3 修改表:
(1)ALTER TABLE test1 ALTER COLUMN bbid int NOT NULL
(2)alter table 表名 alter column 字段名 text(类型)
26.sql中改变字段类型:
cast(dprice as int) //dprice 是string类型,转换为int类型
27 .TextBox自动换行:
TextMode="MultiLine" style="word-wrap:break-word;height:80px;word-break:break-all;"
将上面代码加到textbox源代码中即可
28. webconfig中链接字符串和程序中如何用:
(1)<connectionStrings>
<add name="connstring" connectionString="Data Source=.;Initial Catalog=HJPX;Integrated Security=True"/>
</connectionStrings>
引用时:
public static readonly string ConnectionString = ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString;
SqlConnection con = new SqlConnection(ConnectionString);
(2)<appSettings>
<add key="StrCon" value="Data Source=.;Initial Catalog=WorkMeeting;User ID=sa;Password=123456"/>
</appSettings>
引用时:
public static readonly string ConnectionString = ConfigurationSettings.AppSettings["StrCon"].ToString();
SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["StrCon"].ToString());
29. 比较2个小时时间大小:
if(DateTime.Parse(BeginTime)>DateTime.Parse(EndTime))
30. 播放背景音乐
Response.Write("<bgsound src='1.mp3' autostart='true'>");
31.捕捉浏览器关闭方法:
<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title></title>
<style>
TD { FONT-SIZE: 9pt}
</style></head>
<body topmargin=5 leftmargin=0 scroll=AUTO>
<script language=javascript>
window.onbeforeunload = function() //author: meizz
{
var n = window.event.screenX - window.screenLeft;
var b = n > document.documentElement.scrollWidth-20;
if(b && window.event.clientY < 0 || window.event.altKey){
return "您确定退出系统吗?退出系统后播放页面不再积分!";
}
};
</script>
</body>
</html>
32. 查询结果返回红色:
(注意:Gridview不认样式,所有要用Datalist或其他)比如 bumen 字段 含关键字 TextBox1.Text (注意:Gridview不认样式,所有要用Datalist或其他)
那么只要在对应的数据项上进行替换就可以了呀
DataTable dt =返回的表
for(int i = 0 ;i<dt.Rows.count;i++){循环表各行
dt.Rows[i]["列名"] = (dt.Rows[i]["列名"] + "").Replace(Tkey.Text.ToString(), "<FONT color=#ff0000>" + Tkey.Text.ToString() + "</FONT>");
}
datalist1.DataSource=dt;
datalist1.DataBind();
33. sql 随机数语句:
select top N* from tablename(表名) order by newid()
注意: 1.N为随机条数 2.tablename为表名 3.newid()函数为随机函数
34. 存储过程的创建和使用:
1 如何创建存储过程
user testdatabase(数据库名称)
go
create procedure testname(存储过程名称)
@test1 int, @test2 nvarchar(50)
as
insert into testtable values(@test1,@test2)
return
2 如何使用
public string[] TestLogin(string uname, string upwd)
{
try
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "User_Login";//存储过程名
cmd.Connection = conn;
cmd.Parameters.Clear();
cmd.Parameters.Add("@uname", SqlDbType.NVarChar, 100).Value = uname;
cmd.Parameters.Add("@upwd", SqlDbType.NVarChar, 100).Value = upwd;
string[] result = new string[3];
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
result[0] = dr["qx"].ToString();
result[1] = dr["tname"].ToString();
result[2] = dr["unitid"].ToString();
dr.Close();
return result;
}
else
{
return null;
}
}
catch (Exception e)
{
throw e;
}
finally
{
conn.Close();
}
}
35 .错误日志:
1 新建项目→添加新项→全局应用程序类(vs2008 第1列倒数第5个)
2 在 Application_Error 方法中插入:
Exception objErr = Server.GetLastError().GetBaseException();//错误源
string msg = Server.HtmlEncode(objErr.Message);//错误要进行编码
Server.ClearError();//清空
Request.Url.AbsolutePath;//错误源产生的页面
36. 页面载入请稍等:
<body>
<form id="form1" runat="server">
<div>
<script language=javascript>
document.write('<div id=loadDiv style="position:absolute;top:50%;left:50%;margin:-100px 0 0 -100px;">'+ '<img src="images/wait.gif"/>正在加载中,请稍后……<span id="loading"></span> </div>');
var setInterval1 = setInterval("loading.innerText += '.'", 300);
var setInterval2 = setInterval("loading.innerText = ''", 15000);
function window.onload()
{
hiddenDiv.style.display="";
loadDiv.removeNode(true);
clearInterval(setInterval1);
clearInterval(setInterval2);
}
</script>
<div id=hiddenDiv style="display: none">
</div>
</div>
</form>
</body>
37 . 点击量柱状图:
Image1.Width = Unit.Pixel(Convert.ToInt32("5"));
上述代码控制image的长度
在datalist里面的如何绑定
int num = DataList1.Items.Count;//记录有多少行数据
for (int i = 0; i < num; i++)
{
Label lb1 = (Label)(DataList1.Items[i].FindControl("Label2"));//visible为false,记录Id
Image img = (Image)(DataList1.Items[i].FindControl("image1"));
img.Width = Unit.Pixel(Convert.ToInt32(lb1.Text));
}
38. radiobutton 取值问题:
1 首先多个radiobutton的GroupName设置 为相同的值
protected void Button1_Click(object sender, EventArgs e)
{
RadioButton selectedRadioButton = new RadioButton();
GetSelectedRadioButton(Page.Controls,ref selectedRadioButton);
if (selectedRadioButton.ID != null)
{
// Response.Write("selected radiobutton ID=" + selectedRadioButton.ID + "; state:" + selectedRadioButton.Checked.ToString());//id,选中状态
RadioButton rdo = (RadioButton)this.FindControl(selectedRadioButton.ID);
Response.Write(rdo.Text); //选中项的值
}
}
private void GetSelectedRadioButton(ControlCollection cc,ref RadioButton rbb)
{
foreach (Control ctrl in cc)
{
if (ctrl is RadioButton)
{
RadioButton rb = (RadioButton)ctrl;
if (rb.GroupName == "rbgp")//其中“rbgp”为你设置的groupname的值
{
if (rb.Checked)
{
rbb=rb;
}
}
}
else if (ctrl.HasControls())
{
GetSelectedRadioButton(ctrl.Controls,ref rbb);
}
}
}
39 .分享到:
<!-- JiaThis Button BEGIN -->
<script type="text/javascript" src="http://v2.jiathis.com/code/jiathis_r.js?move=0" charset="utf-8"></script>
<!-- JiaThis Button END -->
放在<body></body>之间
40.更改浏览器地址栏图标:
<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />
上述代码放进<head>区域内(注意找*.ico的图标图片)
41 及时释放资源另一种做法:
using (SqlConnection connection = new SqlConnection(connectionString))
{} //一般都是connection在前面,下面是实例
/// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string SQLString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(SQLString, connection))
{
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.SqlClient.SqlException E)
{
connection.Close();
throw new Exception(E.Message);
}
}
}
}
42 执行多条SQL语句,实现数据库事务。
/// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">多条SQL语句</param>
public static void ExecuteSqlTran(List<string> SQLStringList)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
SqlTransaction tx = conn.BeginTransaction();//声明数据库事物
cmd.Transaction = tx;//事物开始
try
{
for (int n = 0; n < SQLStringList.Count; n++)
{
string strsql = SQLStringList[n].ToString();
if (strsql.Trim().Length > 1)
{
cmd.CommandText = strsql;
cmd.ExecuteNonQuery();
}
}
tx.Commit();//事物提交
}
catch (System.Data.SqlClient.SqlException E)
{
tx.Rollback();//事物回滚
throw new Exception(E.Message);
}
}
}
- 杂项
- 杂项
- 杂项
- 杂项
- 杂项
- 杂项
- 杂项
- 杂项
- 杂项
- 杂项
- 杂项
- 杂项
- 杂项
- 杂项
- 杂项
- 杂项
- 杂项
- 杂项
- MFC仿真设置
- 最小生成树算法(prim 克鲁斯卡尔(并差集))
- ubuntu下调试android手机,并进入手机shell终端
- ffmpeg的decoder有哪些?
- 安装postgreSQL出现configure: error: zlib library not found解决方法
- 杂项
- Android Fragment
- STM32 USART1对PWM的影响,串口影响PWM
- 自然语言处理综论
- 2013!俺来了!!
- 解决oracle 11g不能导出空表
- XAF开讲
- win7下创建名为com1.php的文件提示“指定的设备名无效”
- 编写高效C语言的四大绝招