NET常用代码
数据库连接:
<add name="Conn" connectionString="server=192.168.1.3;database=eduwhcbank1;uid=sa;pwd=^Y&U*I(O;"/>
<add name="nameConn" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\name.mdb;Persist Security Info=True" providerName="System.Data.OleDb"/>
windows身份验证:<add name="examConnectionString" connectionString="Data Source=PC-201003201022\SQLEXPRESS;Initial Catalog=exam;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
DropDownList:
public void BindNewsKind()
{
this.DropNewsKinds.DataSource = NewsKinds.GetAllNewsKinds();
this.DropNewsKinds.DataTextField = "KindName";
this.DropNewsKinds.DataValueField = "KindId";
this.DropNewsKinds.DataBind();
this.DropNewsKinds.SelectedIndex = 0;
//this.DropNewsKinds.Items.Insert(0, "请选择...");
}
DropDownList1.Items.Add(new ListItem("--" + ds.Tables["table1"].Rows[i][1].ToString(), ds.Tables["table1"].Rows[i][0].ToString()));
ListItem item = new ListItem("无分类", "-1");
ddlCategory.Items.Insert(0, item);
CustomValidator:(ValidateEmptyText属性设为True)
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
string UserName = args.Value;
if (Users.IsValidateUserName(UserName))
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}
Repeater控件中的删除:
<asp:LinkButton ID="lbnDelete" OnClientClick="javascript:return confirm('确定删除吗?')" CommandArgument='<%#Eval("Id") %>' CommandName="delete" runat="server">删除</asp:LinkButton>
protected void rptTrainPlan_ItemCommand(object sender, RepeaterCommandEventArgs e)
{
if (e.CommandName == "delete")
{
int TrainPlanId = int.Parse(e.CommandArgument.ToString());
bllTrainPlan.Delete(TrainPlanId);
BindTrainPlan();
}
}
用FindControl前提是控件要放在模板列中
CheckBox CheckSingle = this.GridUsers.Rows[i].Cells[4].FindControl("CheckSingle") as CheckBox;
string newItem = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].FindControl("TextBox1"))).Text.ToString();
string fname=((TextBox)e.Item.FindControl("TextBox3")).Text;
FileUpload fileupload = (FileUpload)Master.FindControl("ContentPlaceHolder1").FindControl(fname);
int NewsId = Convert.ToInt32(GridNews.DataKeys[e.RowIndex].Values[0]);
string id=DataList1.DataKeys[e.Item.ItemIndex].ToString();
Response.Redirect(string.Format("ShowNews.aspx?key={0}",strkey));
//获取投票者IP
string ip = Request.UserHostAddress.ToString();
RegularExpressionValidator(验证邮箱格式):ValidationExpression属性 \w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
RegularExpressionValidator(验证输入为日期):ValidationExpression属性 ([0-9]{1,2})/([0-9]{1,2})/([0-9]{4})
<%# DataBinder.Eval(Container.DataItem,"dateandtime","{0:D}")%> //----2008年10月8日 星期三
<%# Bind("dtt","{0:d}") %> //时间显示为2006-6-26
<%#Eval("AddTime","{0:yyyy年MM月dd日}") %>
limittime = ((DateTime)drw["limittime"]).ToString("yyyy年MM月dd日");
return birthday.ToString("yyyy-MM-dd");
若GridView中绑定列里面 设置 内容格式 DataFormateString ={0:d} ,则 必须把 属性 HtmlCode 设置为false,否则无法起作用.
当对此表达式操作时候,必须用Eval 如<%# Eval("字段名").ToString().Substring(0,5) %>
GridView改变编辑模式下文本框的长度:编辑列-> 右侧的ControlStyle width
update transfer set t_post=8,t_new_post=8
protected void rptTrainPlan_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Label T_userid = e.Item.FindControl("T_userid") as Label;
Label T_department = e.Item.FindControl("T_department") as Label;
DataRowView rowView=e.Item.DataItem as DataRowView;
btnDelete.CommandArgument = btnEdit.CommandArgument = btnReport.CommandArgument = rowView["id"].ToString();
}
}
protected void GridView1_RowDataBound(object sender,GridviewRowEventArgs e)
{
if(e.Row.RowType==DataControlRowType.DataRow)
{
e.Row.Cells[1].Attributes.Add("onclick","return confirm('你确定删除吗?')");
}
}
属性:
public List<string> Images
{
get
{
return ViewState["Images"] == null ? null : ViewState["Images"] as List<string>;
}
set
{
ViewState["Images"] = value;
BuildImageButtons(value);
}
}
SqlDataSource4.SelectCommand = sql;
SqlDataSource4.DataBind();
LinkButton的冒泡事件:
protected void LinkButton1_Command(object sender, CommandEventArgs e)
{
bm.Delete(Convert.ToInt32(e.CommandArgument));
Bind();
}
protected void lbtnDelComment_Click(object sender, EventArgs e)
{
// 当前点击的按钮
LinkButton lb = (LinkButton)sender;
// 获取传过来的commentId
string comId = lb.CommandArgument;
// 删除该评论
bool b = new CommentManager().Delete(comId);
}
Response.Write("<script>alert('添加成功!'); this.location='default.aspx';</script>");
Response.Write("<script>alert('该用户名不存在!'); this.location='javascript:history.back(-1)';</script>");
<asp:HiddenField ID="hidArticleId" runat="server" Value='<%# Eval("id")%>'/>
if (string.IsNullOrEmpty(txbbirthday.Text))
{
txbbirthday.Text = "1900-01-01";
}
btn.Attributes["onclick"] = "return window.confirm('真的删除吗?');";
编辑列->DeleteText属性:<div id="delete" onclick="javascript:return confirm('你确认删除吗?')">删除</div>
<asp:Button id="btndelete" runat="server" Text="删除" OnClick="btn_Ok_Click" OnClientClick="return confirm('确认要删除吗?');"></asp:Button>
ckb_haspic.Checked == true ? 1 : 0
String.IsNullOrEmpty(url)?"无":url
string path = o != null ? o.ToString() : string.Empty;
int.TryParse(Request.QueryString["id"].ToString(), out id)
<%#Eval("remark").ToString().Length <= 10 ? Eval("remark") : Eval("remark").ToString().Substring(0, 10) + "..."%>
获取登录控件中的值:
System.Web.UI.WebControls.Login login1 = (System.Web.UI.WebControls.Login)LoginView1.FindControl("Login1");
string username = "user_id='" + login1.UserName + "'";
将VS的启动服务器设置为IIS:
1.网站右键->属性页->启动选项(选择“使用自定义服务器”,基 URL:“http://localhost/zjrstadmin”)
2.IIS中建立虚拟目录 名称为zjrstadmin
int GroupID=LoginUser.UserGroupID;
int id=Request["id"]; //等等这类变量要写在具体方法的里面,不能写在外面。
Regex.Replace(yourStr, @"<script[^>]*>[\s\S]*?</script>|<[^>]*>", "", RegexOptions.IgnoreCase);
MembershipUser mUser = Membership.GetUser();
if (mUser == null)
{
Response.Redirect("../login.aspx?ReturnUrl=" + Server.UrlEncode(Request.RawUrl));
}
int _id = 0;
int.TryParse(Request.QueryString["id"], out _id);
codesmith:
新方法只在三个项目中添加:BLL IDAL SQLServerDAL
web.config中添加<add key="DAL" value="JYAdmin.SQLServerDAL"/>
SQLServerDAL-->属性-->添加命名空间
连接VSS:点击Browse按钮,文件名输入如(\\192.168.1.3)->选择srcsafe.ini
<connectionstrings>
<clear/>
项目中添加App_Themes及Defqult子文件夹
读取文件并把值赋给字符串变量:
private void gethtml()
{
string path = UiConfig.RootDir + "/template/site/" + this._TemplateName + ".html";
StreamReader reader = new StreamReader(HttpContext.Current.Server.MapPath(path));
this._HTML = reader.ReadToEnd();
reader.Close();
reader.Dispose();
}
自定义DataTable:
DataTable dt = UtilPage.GetPage("News_hot_aspx", PageIndex, 15, out ReCount, out PgCount, null);
DataTable data = new DataTable();
data.Columns.Add("d", typeof(string));
for (int i = 0; i < dt.Rows.Count; i++)
{
StringBuilder sb = new StringBuilder();
DataRow dr = data.NewRow();
sb.Append("<li><a href=\""+rooDir+"/news/n" + dt.Rows[i]["ID"].ToString() + ".aspx\">" + dt.Rows[i]["Title"].ToString() + "</a></li>\r\n");
dr["d"] = sb.ToString();
data.Rows.Add(dr);
}
this.hotNewsList.DataSource = data;
this.hotNewsList.DataBind();
dt.Clear(); data.Clear();
在现有DataTable基础上增加列:
DataTable dt = UtilPage.GetPage("Friend_Index_Hot_aspx", PageIndex, 15, out ReCount, out PgCount, null);
dt.Columns.Add("d", typeof(string));
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow dr = dt.NewRow();
string src = this.GetHeadImage(Convert.ToInt32(dt.Rows[i]["userid"].ToString()), 1);
dt.Rows[i]["d"] = src;
}
this.DLhotusers.DataSource = dt;
dt.Clear(); dt.Dispose();
iframe无刷新:
<iframe src="merchant_info.asp" width="696" marginwidth="0" height="128" marginheight="0" align="left" scrolling="no" frameborder="0" name="mv"></iframe>
<a href="merchant_info.asp?id=<%=rs("id")%>" target="mv">
在父窗口中打开:onclick="parent.location.href='iloveyou.htm'"
衔接的样式:
a {color:#000;text-deuration:none;}
a:hover{color:#fff;}