web开发心得(SQL)(转载)

 1.
WEB程序,绝对不要使用static 静态的变量,除非你知道他的作用。
声明为static, 所有用户同时使用这个变量。所有的类实例都公用这个变量。 2.
连接表, 保留左边的表a 所有记录 加 匹配的右边的表的记录
select a.*,b.d13 as username from factor_main a left outer join hrinfo b on a.userid = b.d11a


3.视图MO_RECEIPTREPORT 字段 START_DATE 为DATETIME类型,本意是想查出某月的记录。比如,要找出1月份的记录,这样写

SELECT * FROM MO_RECEIPTREPORT WHERE START_DATE>='2004-01-01' AND START_DATE<'2004-02-01'

改成这样写
SELECT * FROM MO_RECEIPTREPORT WHERE MONTH(START_DATE)='1'

4.查询 not in <>'null'

select * from hrinfo WHERE id NOT IN (SELECT staid FROM hrinfo where staid <> 'NULL' )


5.清空表记录

truncate table usertable


7.第一次读页面
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{

8.转int型

int mn = Convert.ToInt32(

9.在cookies中记录 用户id

Response.Cookies["user"]["userid"] = user.Trim();

获取

string userid = Request.Cookies["user"]["userid"].ToString();

10.html中的 框架分割 代码 有框架 就没有<body>

<html>
<frameset border="0" framespacing="0" rows="102px,80%*" frameborder="0" cols="*" />
<frame name="top" src="top.aspx" noresize scrolling="no">
<frameset border="1" framespacing="0" rows="100%,2%" frameborder="NO" target="_parent">
<frame name="mains" src="main.aspx" scrolling="no" noresize>
<frame name="bottomFrame" src="button.aspx" noresize scrolling="no">
</frameset>
</html>

11.终止当前页面

Server.Transfer("main.htm");

12.sql 排序

select * from menu order by power

13.sql合计总数

select count(*) as cou from menu_power


14. 整合功能 #region #endregion

15. 获取当前时间

方法1:DateTime dt = DateTime.Now;

方法2: SqlCommand cmd = new SqlCommand("select getdate() ", ConnOpen());
conn.Open();
return Convert.ToDateTime(cmd.ExecuteScalar());

16. 将当前线程挂起 多少毫秒 使用线程 要用到 System.threading 命名空间

thread.sleep(70); //将当前 线程挂起70毫秒

Thread InstanceCaller= new Thread(new ThreadStart(一个方法名)); //线程的创建
InstanceCaller.Start(); //线程开始运行

17.SqlDataReader 新的理解

在使用 SqlDataReader 时,关联的 SqlConnection 正忙于为 SqlDataReader 服务,对 SqlConnection 无法执行任何其他操作,只能将其关闭。除非调用 SqlDataReader 的 Close 方法,否则会一直处于此状态。

也就是说 在未结束 SqlDataReader.Read() ,执行 Close()之前.连接Conn要保持 打开状态.

18. sql 的唯一性检索

SELECT DISTINCT userid FROM [logs]

19.控件开发 的属性

[Bindable(true),Category("Texts"),Description("align")] //主要用与控制这个属性在 属性栏中的哪个分类里面显示,控制属性是‘文本的’,数字的,选项的’
public string Align //文本的排列顺序
{
get { return align; }
set { align = value; }
}
20.求SQL:一个表中是否存在某列

方法1:
if exists (select c.* from syscolumns c inner join sysobjects o on c.id=o.id where o.id=object_id('表名') and c.name='列名')
print '存在'
else
print '不存在'

方法2:

select * from syscloumns where id = object_id('table_name') and name = 'column_name'
21.在释放所有资源时,调用该方法,

public void Dispose()
{
//GC.SuppressFinalize(this); //这句的 作用是 告诉GC不要调用this的终结器
}

22.检查连接是否在打开状态

if(conn.State.ToString().ToUpper() != "Open".ToUpper())conn.Open() ;

if(conn.State = ConnectionState.Closed )conn.Open() ;

if(conn.state!= ConnectionState.Open)conn.Open();

23.Microsoft Data Access Application Block


24.在js中 调用服务器的代码
方法1:

if(confirm(".......")
{
<%
你的服务器代码
%>
}
else
{
<%
你的服务器代码
%>
}

方法2:
if(confirm("...."))
{button1.click();}
else
{button2.click();}

将两个按钮 高度和宽度都设为 0 (不能设button.visible=false)
方法3:
if(confirm("...."))
{ document.all.textbox1.value="1";} //一定要注意在js中是这种形式。 或者用<%调用 服务器的代码%>不过我没试过
else
{ document.all.textbox1.value="2";
document.location.href="treeview.aspx"; //转向别的页面
}

代码再根据 textbox1.text值 进行判断 并分别执行不同的代码。


25.获得系统时间


string sYear = Convert.ToString(System.DateTime.Now.Year);
string sMonth = Convert.ToString(System.DateTime.Now.AddMonths(1).Month);

 

26.如何将A表的数据更新到B表?


只要求更新部分字段数据,该如何实现?

方法1:update b set col=a.col from a where a.id=b.id

方法2:update b set b.col=a.col from a,b where a.id=b.id 


方法3:update b 
set col=a.col 
from b 
inner join a 
on a.id=b.id

方法4:update b set b.col=a.col 
from b 
Left Join a 
on b.id = a.id 


27删除数据库中的表,并创建一个新的
drop table Year_KPIvalue
create table Year_KPIvalue
(
ID int Identity PRIMARY KEY,//序号,主键,自动累加
Dept varchar(20),//部门
KPIName varchar(50),//KPI名称
Time datetime,//评价时间
KPIvalue varchar(20),//KPI分值
Deptvaluer varchar(20),//评价部门名称
);


28.

/// <summary>
/// 正则表达式验证是否是数字
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
static bool IsNumeric(string str)
{
System.Text.RegularExpressions.Regex reg1
= new System.Text.RegularExpressions.Regex(@"^[-]?/d+[.]?/d*$");
return reg1.IsMatch(str);

 

29.
判断 DataGrid 内容为空时也显示表头内容.

if (ds.Tables(0).Rows.Count == 0) {
ds.Tables(0).Rows.Add(ds.Tables(0).NewRow());
gridView.DataSource = ds;
gridView.DataBind();
int columnCount = gridView.Rows(0).Cells.Count;
gridView.Rows(0).Cells.Clear();
gridView.Rows(0).Cells.Add(new TableCell());
gridView.Rows(0).Cells(0).ColumnSpan = columnCount;
gridView.Rows(0).Cells(0).Text = "No Records Found.";
}

GridView记录为空时 显示表头记录

#region 如果内容为空 则显示表头
if (ds.Tables[0].Rows.Count == 0)
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
GridView1.DataSource = ds;
GridView1.DataBind();
int columnCount = GridView1.Rows[0].Cells.Count;
GridView1.Rows[0].Cells.Clear();
GridView1.Rows[0].Cells.Add(new TableCell());
GridView1.Rows[0].Cells[0].ColumnSpan = columnCount;
//GridView1.Rows[0].Cells[0].Text = "No Records Found.";
}
else
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
#endregion


30. 查询 name不为空 的记录
SELECT * FROM TABLE WHERE (name is not null)
select * from table where (len(name)>1)
31.SQL关于日期的操作.
Dateadd(wk,datediff(wk,0,getdate()),-1) 
Dateadd(wk,datediff(wk,0,getdate()),6)

Dateadd(mm,datediff(mm,0,getdate()),0)
Dateadd(ms,-3,dateadd(mm,datediff(m,0,getdate())+1,0))

Dateadd(yy,datediff(yy,0,getdate()),0)
Dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate())+1, 0))

 

32.关于模态窗口(showModalDialog)的专题讨论! 详细见模态窗口压缩包


1.模态窗口的打开 
2.模态窗口的关闭 
3.模态窗口的传递参数。 
4.其他。。。。 


1.window.showModalDialog("DialogPage.aspx","newwin","dialogHeight: 200px; dialogWidth: 150px; dialogTop: 458px; dialogLeft: 166px; edge: Raised; center: Yes; help: Yes; resizable: Yes; status: Yes;"); 

2.window.close(); 

3.传值 
ParentPage.aspx: 
window.showModalDialog("DialogPage.aspx?para1=aaa&para2=bbb"); 

DialogPage.aspx: 
string str1=Request.QueryString["para1"].toString(); 
string str2=Request.QueryString["para2"].toString(); 

返回值 
DialogPage.aspx: 
window.returnvalue="aaa"; 

ParentPage.aspx: 
<script language="jscript">
function DeptReturn()
{
var result = window.showModalDialog('DialogPage.aspx','','width=700,height=400,top=150,left=200,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no');
if (result)
{
document.aspnetForm.ctl00_contentplaceHolder1_TextBox3.value=result; //在master页面下控件的名是这样,非master的页面 var tb=document.getElementById ("文本框控件名txtAssessid"); tb.value = result;
}
}
</script>

ParentPage.aspx.cs
ButtonDept.Attributes["onclick"] = "return DeptReturn();";

4. 
aspx页面在showmodeldialog情况下为什么一提交就重新打开一个页面? 
showmodaldialog打开的页面中在<head></head>之间加入一行:<base target="_self">

 

33.gridview 表中表 数据绑定.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) //在绑定以后执行
{
if (e.Row.RowType == DataControlRowType.DataRow) //是数据行的话
{
string _sql = "select * from Year_ComPlanAllotStandard where PlanId='" + e.Row.Cells[0].Text + "'";// 找到 是绑定 哪一行的记录
GridView TempGridView = new GridView(); //创建一个gridview
TempGridView = (GridView)e.Row.FindControl("GridViewStandard"); //将模板列中的gridview绑定到新建的girdview上
DataSet ds = DBC.ExecuDataSet(_sql); //绑定数据.
TempGridView.DataSource = ds;
TempGridView.DataBind();
}

}


34.对 gridview 的记录进行删除和更新

#region 绑定删除确认到 删除按钮
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if ((e.Row.RowType != DataControlRowType.Footer) && (e.Row.RowType != DataControlRowType.Header) && (e.Row.RowType != DataControlRowType.Pager))
{
e.Row.Cells[12].Attributes.Add("onclick", "return confirm('您确认要删除这条指标吗?')");
}
}

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string _sql = "delete Year_complanallot where id='" + GridView1.Rows[e.RowIndex].Cells[0].Text + "'";
bool _bool = DBC.Excusql(_sql);

BuildGridView();

}


protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
int index = Convert.ToInt32(e.CommandArgument);
string id = GridView1.Rows[index].Cells[0].Text;
Response.Redirect("Year_ComPlanAllotListAddEdit.aspx?edittype=1&id=" + id.Trim());

}
}
#endregion


35. 创建事务 执行 并catch{回滚}

SqlConnection con = new SqlConnection(DBC.strconntstring);
SqlTransaction transaction;
con.Open();
SqlCommand command = con.CreateCommand();

transaction = con.BeginTransaction();
command.Connection = con;
command.Transaction = transaction;

try
{
_sql = "update year_complanallot set Dept='" + TextBox1.Text + "',SortID='" + TextBox2.Text + "',PlanID='" + TextBox6.Text + "',Content='" + TextBox3.Text + "',PlanName='" + TextBox4.Text + "',forecaseTime='" + TextBox5.Text + "' where id='" + id + "'";
command.CommandText = _sql;
command.ExecuteNonQuery();
_sql = "update year_complanallotStandard set planid='" + id + "',standard='" + TextBox7.Text + "',Grade='" + TextBox8.Text + "' where id='" + Label1.Text + "'";
command.CommandText = _sql;
command.ExecuteNonQuery();
_sql = "update year_complanallotStandard set planid='" + id + "',standard='" + TextBox9.Text + "',Grade='" + TextBox10.Text + "' where id='" + Label2.Text + "'";
command.CommandText = _sql;
command.ExecuteNonQuery();
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
}
finally
{
con.Close();
}


36. 获得 插入数据记录的id
string _sql="insert tablename(field....) values(value.....) select @@IDENTITY AS 'id'";


37.绑定日期 年

/// <summary>
/// 绑定时间日期到 list
/// </summary>
protected void BuildDateTime()
{

string sql = "select getdate() ";
DateTime dt = Convert.ToDateTime(DBC.ExecuScalar(sql));


year_DropDownList.Items.Add(Convert.ToString(dt.Year - 2));
year_DropDownList.Items.Add(Convert.ToString(dt.Year - 1));
year_DropDownList.Items.Add(Convert.ToString(dt.Year));
year_DropDownList.Items.Add(Convert.ToString(dt.Year + 1));
year_DropDownList.Items.Add(Convert.ToString(dt.Year + 2));


#region 选择dropdownlist 为 当前日期

year_DropDownList.Selectedvalue = dt.Year.ToString();

#endregion
}

38.根据记录内容 自动选取dropdownlist选项

DropDownList2.Items.FindByvalue(dr["planID"].ToString()).Selected = true;


39.传递参数 到后面的页

Context.Items["zbbm"] = ((Label)e.Item.FindControl("zbbm")).Text.ToString();
Server.Transfer("year_kpikh.aspx"); 
等同于
Response.Redirect("year_complandetail.aspx&planid=1");

40.控制显示的数为两位 浮点型

Labelvalue.Text = string.Format("{0:f2}", DKpivalue);

41.很好的排序sql语句
要返回查询结果的第三页(页大小是10),

SELECT TOP 10 * FROM
(SELECT TOP 30 * FROM Customers ORDER BY Id ASC) AS Table1
ORDER BY Id DESC

42.先按 A 排序 再按 B排序

所以如果要安A、B降序排列则可以这样写:
select top 5 *
from table
order by A asc,B desc

43.去除重复项
_sql = "select DISTINCT zrbm from cgskpi_bmfj"


44.在使用 gridview 时,用到每行的id时将 id字段显示出来 用完后关闭显示.
GridView1.Columns[0].Visible = true;


45.
datagrid 绑定 数据后, 根据绑定的数据修改 显示数据.
//绑定多个协作部门


for (int i = 0; i < DataGrid1.Items.Count; i++)
{
string string_temp = DataGrid1.Items[i].Cells[6].Text.Trim();

if (string_temp != "")
{
string[] Deps = string_temp.Split(',');

bool bool_temp = false; //去掉 多余的逗号

for (int int_temp = 0; int_temp < Deps.Length; int_temp++)
{
if (bool_temp == false)
{
DataGrid1.Items[i].Cells[6].Text = oCon.GetDepartmentNameByDepId(Deps[int_temp]);
bool_temp = true;
}
else
{
DataGrid1.Items[i].Cells[6].Text += "," + oCon.GetDepartmentNameByDepId(Deps[int_temp]);
}
}

}
}

gridview 修改数据这样找

for(int i=0;i<GridView1.Rows.Count;i++)
{
CheckBox cb=(CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox1");
if (cb.Checked)
{
string PlanID = GridView1.Rows[i].Cells[1].Text;
string Dept = dept;
string Date = year;
string PlanName = GridView1.Rows[i].Cells[2].Text;
string Object = GridView1.Rows[i].Cells[4].Text;
string ObjectAssess = GridView1.Rows[i].Cells[5].Text;
string HopeObject = GridView1.Rows[i].Cells[6].Text;
string HopeObjectAssess = GridView1.Rows[i].Cells[7].Text;

string _sql = "select count(*) from year_deptplanorder where planid='" + PlanID + "'";
int _count = Convert.ToInt32(DBC.ExecuScalar(_sql));

if (_count == 0)
{

}
}
}


for (int i = 0; i < GridView1.Rows.Count; i++)
{
_sql = "select name from gb_vpart where workerid='" + GridView1.Rows[i].Cells[2].Text + "'";
GridView1.Rows[i].Cells[2].Text = DBC.ExecuScalar(_sql);
}


45.小的SQL语句 都是写在数据连接层 同 update insert 写在一起

46.抛出一段异常
if(textContent=="")
throw new Exception("留言内容为空");

47.DataReader使用方法
using(SqlDataReader dr=SqlHelper.ExecuteReader(cmdText, CommandType.StoredProcedure, parameters.ToArray()))
{
if(dr.Read()) 
mail=(Mail)SqlHelper.PutObjectProperty(new Mail(), dr);
}
48.读取web.config文件的数据
<connectionStrings>
<add name="PTMMSConnectionString" connectionString="Data Source=10.158.21.49;Initial Catalog=PTMMS;Persist Security Info=True;User ID=sa;Password=lnhr" providerName="System.Data.SqlClient" />
</connectionStrings>

首先要先在bin文件夹中 添加System.Configuration.dll文件(重要)

然后 using System.Configuration;

protected static string connectionString = ConfigurationManager.ConnectionStrings["PTMMSConnectionString"].ConnectionString;
读取 连接字符串.

49.绝对不能乱用Static

50.获得当前在线人数

Application["user_sessions"].ToString()

在Global.asax文件中添加
void Application_Start(object sender, EventArgs e)
{
// 在应用程序启动时运行的代码
Application["user_sessions"] = 0;
}
void Session_Start(object sender, EventArgs e)
{
// 在新会话启动时运行的代码
Application.Lock();
Application["user_sessions"] = (int)Application["user_sessions"] + 1;
Application.UnLock();
}

protected void Session_End(object sender, EventArgs e)
{
// 在会话结束时运行的代码。
// 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为
// InProc 时,才会引发 Session_End 事件。如果会话模式设置为 StateServer
// 或 SQLServer,则不会引发该事件。
// 或者设置Session的有效时间 ,超过有效时间则自动执行该代码
// <sessionState timeout="120">
// </sessionState>
Application.Lock();
Application["user_sessions"] = (int)Application["user_sessions"] - 1;
Application.UnLock();
}


个人的web开发心得(六)----------非常适合入门新手,都是常识

54.清空数据库表的记录

--打开库
use serp 
--清空表
truncate table month_result

55.将某部分内容 放到 panel中 可以 添加 滚动条,控制 该区域大小
<asp:Panel ID="Panel1" runat="server" Height="100%" ScrollBars="Auto" Width="100%"> //添加左右 上下 两个滚动条

<asp:Panel ID="Panel2" runat="server" Height="43px" Width="98%" ScrollBars="Vertical"> //只添加 上下滚动条。


57.用函数向cookic中存储用户标识 ,

FormsAuthentication.RedirectFromLoginPage(name, false);
name=User.Identity.Name;读取cookic的数据
作用等同于:
cookic["name"]="dwj";
name=cookic["name"].tostring();

58. string.Format使用
string sql = " select username from userinfo where username='{0}' and password='{1}'";
sql = string.Format(sql, Name.Text.Trim(), PassWord.Text.Trim());

59. 索引器的使用 类似 属性。

/// <summary>
/// 通过索引器获取查询参数
/// </summary>
public SqlParameter this[int index]
{
get
{
return this.List[index] as SqlParameter;
}
}

/// <summary>
/// 通过索引器获取查询参数 最有用的地方 SqlParameter[]不能根据字符串索引
/// </summary>
public SqlParameter this[string parameterName]
{
get
{
return this.m_paramsHash[parameterName] as SqlParameter;
}
}

/// <summary>
/// 将集合转换成数组
/// </summary>
/// <returns>SqlParameter 数组</returns>
public SqlParameter[] ToArray()
{
return (SqlParameter[])ArrayList.Adapter(this.List).ToArray(
typeof(System.Data.SqlClient.SqlParameter));
}

60.

由上面的代码可知

List 索引时 只能 按照 index 获取List中的内容
如: string temp=List[1].tostring();

this.List.Add(parameter);

Hashtable 索引的时候能够根据 name 获取Hashtable的内容
如: string temp=Hashtable["name"].tostring();

this.m_paramsHash.Add(parameter.ParameterName, parameter);

61.

ref 和 out的区别和用法(作用相同,只是out不用初始化 ref要先初始化)ref 关键字使参数按引用传递。其效果是,当控制权传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中。若要使用 ref 参数,则方法定义和调用方法都必须显式使用 ref 关键字。(PS:“ref 和 out的区别和用法(作用相同,只是out不用初始化 ref要先初始化)”这句不完全正确可以说:ref是双向的,out是单向的^_^文章不知道是别人从什么地方转载的.我看了一遍如果有什么纰漏我会在原文进行注释的)例如:

复制代码
class RefExample
{
static void Method(ref int i)
{
i = 44;
}
static void Main()
{
int val = 0; /********ref和out不同处***********/
Method(ref val);
// val is now 44
}
}

传递到 ref 参数的参数必须最先初始化。这与 out 不同,out 的参数在传递之前不需要显式初始化。(

class OutExample
{
static void Method(out int i)
{
i = 44;
}
static void Main()
{
int value; /********ref和out不同处***********/
Method(out value);
// value is now 44
}
}

 


62.取该页面的 绝对路径
string strurl = Request.Url.AbsolutePath;

63.转换日期 注意年月的大小写不同
return dataTime.ToString("yyyy-MM-dd HH:mm:ss");

64.SQL语句 使用 or and 的用法
select * from wlog where pid='211' and ldate='2006-06-30' or pid='211' and ldate='2006-06-29'
也就是说 以 or为分组条件 以and为一组

65.between语句 检索字符型 日期 什么时间到什么时间之间的记录。
select * from wlog where pid='211' and ldate between '2006-06-25' and '2006-06-30' and pid='211'

66. 在gridview中 找控件checkboxlist
SqlDataReader sdr = sc.ExecuteReader(CommandBehavior.CloseConnection);

((CheckBoxList)DataGrid1.FindControl("CheckBoxList2")).DataSource = sdr;
((CheckBoxList)DataGrid1.FindControl("CheckBoxList2")).DataTextField = "权限名称";
((CheckBoxList)DataGrid1.FindControl("CheckBoxList2")).DataBind();

在treeview中找节点

string notepath="顶层note的value/次层的note的value/第三层的note的value";

if (TreeView1.FindNode(notepath) != null)
TreeView1.FindNode(notepath).Checked = true;

67.在gridview中 隐藏主键字段
先邦定字段到 gridview
设置字段id为 gridview的DataKeyName属性

获取该行编号 用
for (int i = 0; i < GridView1.Rows.Count; i++)
GridView1.DataKeys[i].value.ToString();


68.如果查询记录为空,则返回0
select name,isnull((select num from b where name=a.name),0) from a

isnull((select num from b where name=a.name),0)

就是如果里面的select语句为null,那么返回0

69.鼠标 单击 datagrid的某行 则该行 呈现别的颜色 用于选择某行记录作处理。
private void dataGrid_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if ( ( e.Item.ItemType == ListItemType.Item ) || ( e.Item.ItemType == ListItemType.AlternatingItem ) || ( e.Item.ItemType == ListItemType.SelectedItem ) )
{
e.Item.Attributes.Add( "onMouseOver", "this.style.backgroundColor = '#BED3E9';this.style.cursor='hand'");
e.Item.Attributes.Add( "onMouseOut", "this.style.backgroundColor='white';");

}

70.将纯数字导入Excel时数据格式仍保持不变的方法
办法就是利用Excel的特性

查看例子

代码

<%@ Page language="c#" AutoEventWireup="true" %>
<script runat="server">
void Page_Load(object sender, System.EventArgs e)
{
string data1 = "000000001";
long data2 = 123456789123456789;
System.IO.StringWriter sw = new System.IO.StringWriter();
sw.WriteLine("原数字1/t转换后数字1/t原数字2/t转换数字2");
for(int i= 0;i<10;i++)
{
sw.WriteLine(data1 +"/t" + "=/"" + data1 + "/"/t" + data2 +"/t" + "=/"" + data2.ToString() + "/"");
}
sw.Close();
Response.Buffer= true;
Response.Charset="";
Response.AppendHeader("Content-Disposition","attachment;filename=aa.xls");
Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
Response.Write(sw);
Response.End();

}
</script>

71.
获取所选列的数据:DataGrid可以直接通过所选行来获取,GridView同样的代码无法运行。GridView 可以通过GridViewRow来获取。BtnAudit是模版列中的按钮。
GridViewRow grdRow = (GridViewRow)btnAudit.Parent.Parent;

string strId = grdRow.Cells[0].Text;
string memberId = grdRow.Cells[5].Text;


72.
asp.net 注册 启动 vs自带dos窗口。输入以下命令。
aspnet_regiis -r

aspnet_regiis -c

 

73.回车

/r/n


74.ViewState使用
// save in ViewState
ViewState["SortOrder"] = "DESC";

// read from ViewState
string sortOrder = (string)ViewState["SortOrder"];

ViewState声明为属性,进行调用.
string SortField {

get {
object o = ViewState["SortField"];
if (o == null) {
return String.Empty;
}
return (string)o;
}

set {
if (value == SortField) {
// 与当前排序文件相同,切换排序方向
SortAscending = !SortAscending;
}
ViewState["SortField"] = value;
}
}

// 在 ViewState 中跟踪 SortAscending 属性
bool SortAscending {

get {
object o = ViewState["SortAscending"];
if (o == null) {
return true;
}
return (bool)o;
}

set {
ViewState["SortAscending"] = value;
}
}

75.声明 该页为主页 主要用在母板页 导出 word

public override void VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for
}

76.
第一种方法:
利用MaintainScrollPositionOnPostback属性 ,固定 ie滚动条位置
考虑到一个很长的页面,如果每次POSTBACK之后,那个IE的滚动条可能都会回到最开始的地方(最上面),而不会保留其原先已经有的位置,这样用户会比较麻烦,又要把滚动条移动到原来的地方,在asp.net 2.0中,可以设置MaintainScrollPositionOnPostback属性为TRUE即可,即
<%@ Page Language="VB" AutoEventWireup="false" MaintainScrollPositionOnPostback="true" CodeFile="MaintainScrollPosition.aspx.vb" Inherits="MaintainScrollPosition" %>
第二种方法:
滚动条定位的问题1.1早就内置属性了,如page_load里写this.SmartNavigate=ture,即可


77.在行命令事件中获取 第几行的索引
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
string id = GridView1.Rows[Convert.ToInt32(e.CommandArgument)].Cells[0].Text;
}
此方法有时 取不到值

78.获取远程用户的IP
HttpContext.Current.Request.UserHostAddress;

79.
union子句
union操作符将两个查询结果合并为一个结果集。为连接查询合并两个表时:列的数日和顺序在查中必须一致;数据类型兼容
语法:
select 语句
union [ all ]
select 语句
注意:
1 .union运算从最终结果集中删除重复记录,如想不删除重复记录使用all关键字
2 .第一个select语句中不能用order by或compute子句,只能是最后一个select语名后用

例:查询计算机系的学生式年龄不大于19岁的学习,按年龄倒排序
select * from department where dept = ' computer ' ;
union ;
select * from student where age <= 19
order by age desc
注:两表中字段一致

80. js关于document和window对象
Posted on 2006-09-13 10:24 孤叶(学习.net框架)
[document对象]

该对象是window和frames对象的一个属性,是显示于窗口或框架内的一个文档。

属性

alinkColor 活动链接的颜色(ALINK)
anchor 一个HTMI锚点,使用<A NAME=>标记创建(该属性本身也是一个对象)
anchors array 列出文档锚点对象的数组(<A NAME=>)(该属性本身也是一个对象)
bgColor 文档的背景颜色(BGCOLOR)
cookie 存储于cookie.txt文件内的一段信息,它是该文档对象的一个属性
fgColor 文档的文本颜色(<BODY>标记里的TEXT特性)
form 文档中的一个窗体(<FORM>)(该属性本身也是一个对象)
forms anay 按照其出现在文档中的顺序列出窗体对象的一个数组(该属性本身也是一个对象)
lastModified 文档最后的修改日期
linkColor 文档的链接的颜色,即<BODY>标记中的LINK特性(链接到用户没有观察到的文档)
link 文档中的一个<A HREF=>标记(该属性本身也是一个对象)
links array 文档中link对象的一个数组,按照它们出现在文档中的顺序排列(该属性本身也是一个对象)
location 当前显示文档的URL。用户不能改变document.location(因为这是当前显示文档的位置)。但是,可以改变window.location (用其它文档取代当前文档)window.location本身也是一个对象,而document.location不是对象
referrer 包含链接的文档的URL,用户单击该链接可到达当前文档
title 文档的标题((TITLE>)
vlinkColor 指向用户已观察过的文档的链接文本颜色,即<BODY>标记的VLINK特性

方法

clear 清除指定文档的内容
close 关闭文档流
open 打开文档流
write 把文本写入文档
writeln 把文本写入文档,并以换行符结尾

[window对象]

它是一个顶层对象,而不是另一个对象的属性即浏览器的窗口。

属性

defaultStatus 缺省的状态条消息
document 当前显示的文档(该属性本身也是一个对象)
frame 窗口里的一个框架((FRAME>)(该属性本身也是一个对象)
frames array 列举窗口的框架对象的数组,按照这些对象在文档中出现的顺序列出(该属性本身也是一个对象)
history 窗口的历史列表(该属性本身也是一个对象)
length 窗口内的框架数
location 窗口所显示文档的完整(绝对)URL(该属性本身也是一个对象)不要把它与如document.location混淆,后者是当前显示文档的URL。用户可以改变window.location(用另一个文档取代当前文档),但却不能改变document.location(因为这是当前显示文档的位置)
name 窗口打开时,赋予该窗口的名字
opener 代表使用window.open打开当前窗口的脚本所在的窗口(这是Netscape Navigator 3.0beta 3所引入的一个新属性)
parent 包含当前框架的窗口的同义词。frame和window对象的一个属性
self 当前窗口或框架的同义词
status 状态条中的消息
top 包含当前框架的最顶层浏览器窗口的同义词
window 当前窗口或框架的同义词,与self相同

方法

alert() 打开一个Alert消息框
clearTimeout() 用来终止setTimeout方法的工作
close() 关闭窗口
confirm() 打开一个Confirm消息框,用户可以选择OK或Cancel,如果用户单击OK,该方法返回true,单击Cancel返回false
blur() 把焦点从指定窗口移开(这是Netscape Navigator 3.0 beta 3引入的新方法)
focus() 把指定的窗口带到前台(另一个新方法)
open() 打开一个新窗口
prompt() 打开一个Prompt对话框,用户可向该框键入文本,并把键入的文本返回到脚本
setTimeout() 等待一段指定的毫秒数时间,然后运行指令事件处理程序

事件处理程序

Onload() 页面载入时触发
Onunload() 页面关闭时触发


81.遍历整个treeview的所有节点


/// <summary>
/// 每个节点链接的地址
/// </summary>
public string Url
{
set
{
if (TreeViewUserList.Nodes.Count > 0)
{
AllUrl(TreeViewUserList.Nodes,value);
}
}
}

/// <summary>
/// 遍历所有节点赋予url(抵归)
/// </summary>
/// <param name="tnc"></param>
/// <param name="value"></param>
private void AllUrl(TreeNodeCollection tnc,string value)
{
foreach (TreeNode tn in tnc)
{
if (tn.ChildNodes.Count > 0)
{
AllUrl(tn.ChildNodes,value);
}
else
{
tn.NavigateUrl = value + "?pid=" + tn.value;
}
}
}


82.关于节点的一系列操作
该节点在选定的时候是展开的状态
NewNode.SelectAction = TreeNodeSelectAction.Expand;
该节点是折叠的状态
NewNode.Collapse();
该节点是展开的状态
NewNode.Expand();
该节点是选定的状态
tmpNd.Selected = true;
在根添加一个节点
TreeViewUserList.Nodes.Add(NewNode);
在刚增加的根节点上增加一个子节点
TreeViewUserList.Nodes[TreeViewUserList.Nodes.Count - 1].ChildNodes.Add(tmpNd);
不允许在增加子节点。
tmpNd.PopulateOnDemand = false;

在填充节点时触发事件.
protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e)
{// Call the appropriate method to populate a node at a particular level.
switch (e.Node.Depth)
{
case 0:
// Populate the first-level nodes.
PopulateCategories(e.Node);
break;
case 1:
// Populate the second-level nodes.
PopulateProducts(e.Node);
break;
default:
// Do nothing.
break;
}
}

83.用html设置左边的从上到下的框
<table>
<tr> 
<td rowspan="3"

84.

/// <summary>
/// 点击某行记录任意处,选定该行记录为选定状态 ,必须与js配合使用
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowState == DataControlRowState.Normal && e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onclick", " __doPostBack('gvM','" + "Select$" + (e.Row.RowIndex) + "')");

}

if (e.Row.RowState == DataControlRowState.Alternate && e.Row.RowType == DataControlRowType.DataRow)
{

e.Row.Attributes.Add("onclick", " __doPostBack('gvM','" + "Select$" + (e.Row.RowIndex) + "')");
}
if ((e.Row.RowState == (DataControlRowState.Selected | DataControlRowState.Normal)
&& e.Row.RowType == DataControlRowType.DataRow))
{
e.Row.Attributes.Add("onclick", " __doPostBack('gvM','" + "Select$" + (e.Row.RowIndex) + "')");
}

if ((e.Row.RowState == (DataControlRowState.Selected | DataControlRowState.Alternate)
&& e.Row.RowType == DataControlRowType.DataRow))
{
e.Row.Attributes.Add("onclick", " __doPostBack('gvM','" + "Select$" + (e.Row.RowIndex) + "')");
}


}


<script language="javascript" type="text/javascript">
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}

</script>


85.查找gridview的选定值
string bh = GridView1.SelectedDataKey.value.ToString();


86.js调用后台代码

执行按钮buttonok 的单击事件
<script type="text/javascript">

function onOk() {
__doPostBack('buttonok','');
}
</script>

<script language="javascript" type="text/javascript">
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}

</script>

 

87.把分数的计算放到SQL中

SELECT [year], pid, flag, zkpy,
(SELECT AVG(zfs)
FROM vRyTotal
WHERE pid = dbo.YTotal.pid AND n = dbo.YTotal.year)
AS jxpjf,
(SELECT AVG(zqsz)
FROM dbo.yPlan_GwYTotal
WHERE pid = dbo.YTotal.pid AND year = dbo.YTotal.year)
AS zqsz,
(SELECT AVG(zfs)
FROM vRyTotal
WHERE pid = dbo.YTotal.pid AND n = dbo.YTotal.year)
* 0.7 + zkpy * 0.2 +
(SELECT AVG(zqsz)
FROM dbo.yPlan_GwYTotal
WHERE pid = dbo.YTotal.pid AND year = dbo.YTotal.year)
* 0.1 AS zf
FROM dbo.YTotal

 

88.取得exacl多个工作簿的表名
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source=d://a.xls;
Extended Properties=Excel 8.0;";
using(OleDbConnection conn = new OleDbConnection(strConn))
{
conn.Open();
DataTable dt= conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,null);
DataGrid1.DataSource = dt;
DataGrid1.DataBind();
} 上面这个dt里面就有表名在
你可以用dt.rows[i]["TABLE_NAME"]来取得表名

89.在web.config中设置 验证为登陆也后,在解决方案管理器中就要把登陆后的mian页设为起始页,不要把登陆页再设置为起始页。

<authentication mode="Forms">
<forms loginUrl="Login.aspx"></forms>
</authentication>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值