慢慢总结一点asp.net比较常用的代码(持续更新,有好的代码可以留言)

Session为空重新登录系统

if (Session["username"] == null)
        {
            Response.Write("<script>alert('您还没有登录请重新登录系统!');top.location.href='index.aspx';</script>");
        }


焦点设置

Page.ClientScript.RegisterStartupScript(this.GetType(),"focus","<script language=javascript>document.all('txtUserName').focus()</script>");

文本框回车响应事件

txtUserName.Attributes.Add("onkeydown","if(event.keyCode==13) event.keyCode=9");
txtPassword.Attributes.Add("onkeydown","if(event.keyCode==13) event.keyCode=9");

设置间隔时间

System.Timers.Timer和System.Threading.Timer非常类似,它们是通过.NET  Thread  Pool实现的,轻量,计时精确,对应用程序、消息没有特别的要求。System.Timers.Timer还可以应用于WinForm,完全取代上面的Timer控件。它们的缺点是不支持直接的拖放,需要手工编码。

//使用System.Timers.Timer类 
//实例化Timer类,设置间隔时间为10000毫秒; 
System.Timers.Timer t = new System.Timers.Timer(10000);
//到达时间的时候执行事件;
t.Elapsed += new System.Timers.ElapsedEventHandler(theout); 
t.AutoReset = true;//设置是执行一次(false)还是一直执行(true); 
t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件;

在gridview的GridView1_RowDataBound事件里,行变色,截取字符串长度,鼠标移动该处显示全部长度,设置风格,统计求和,考勤时间差

protected>        {

//可以显示成2013/1/6星期几(如星期四)

System.Globalization.CultureInfo>            e.Row.Cells[4].Text =Convert.ToDateTime(e.Row.Cells[4].Text).ToShortDateString()+"星期" + cultureInfo.DateTimeFormat.GetAbbreviatedDayName(Convert.ToDateTime(e.Row.Cells[4].Text).DayOfWeek).ToString();

            //鼠标经过时,行背景色变 
           >            //鼠标移出时,行背景色变 
           >

          string>            e.Row.Cells[10].Text = "<div class=/'listover150/'>" + strDISC + "</div>";
            e.Row.Cells[10].ToolTip = strDISC;//鼠标放上去显示所有

           for (int>            {

                 //设置风格

               >            }

             //字符串长度过长时截取其中35个长度
           >

 }

//设置页脚,统计求和某一列
       >        {
           >            e.Row.Cells[11].Text = "合计¥";
        }

//可算考勤时间差,Row.Cells[1]上班签到时间Row.Cells[2]下班签退时间Row.Cells[3]求出一个工作基点

 if (e.Row.Cells[1].Text != "1900-01-01 00:00:00" &&>            {
               >                {//ToShortDateString() 显示短日期如2013/1/4
                    DateTime>                    DateTime t2 = Convert.ToDateTime(e.Row.Cells[1].Text);
                    DateTime>                    e.Row.Cells[3].Text = Convert.ToString(Math.Round(Convert.ToDecimal(t1.Hour * 60 +>                    DateTime>                   >                }
                if (Convert.ToDecimal(e.Row.Cells[3].Text) < 1 && Convert.ToDateTime(e.Row.Cells[1].Text) > Convert.ToDateTime(Convert.ToDateTime(e.Row.Cells[7].Text).ToShortDateString() + " 8:45:00"))
                {
                    e.Row.Cells[1].BackColor = System.Drawing.Color.Cyan;//基点小于1并且8:45之后打卡时显示为其他颜色
                }
            }
           >            {
               >            }
               >                if (e.Row.Cells[2].Text == "1900-01-01 00:00:00" || e.Row.Cells[2].Text == "1900/1/1 0:00:00") e.Row.Cells[2].Text = "";

 }

时间差通用方法,算出两时间相差多少分钟

DateTime t1 = Convert.ToDateTime(“2013-05-01 08:28:00.000”);//上班时间
DateTime t2 = Convert.ToDateTime(“2013-05-01 17:38:00.000”);//下班时间
e.Row.Cells[1].Text = Convert.ToString(Math.Round(Convert.ToDecimal((t2.Day-t1.Day) * 60*24 + (t2.Hour-t1.Hour)*60 + (t2.Minute -t1.Minute))/(9*60) , 2));//把天折算成分钟,把小时折算成分钟,9*60的意思是一天按照9小时算,算出一个基点保留2位

密码隐藏,不显示

如下代码密码不隐藏:

<asp:TextBox ID="txtPwd" runat="server" TextMode="Password"></asp:TextBox> 
this.txtPwd.Text = sdr["userPwd"].ToString();

解决方法如下:
<asp:TextBox ID="txtPwd" runat="server" TextMode="Password"></asp:TextBox> 
this.txtPwd.Attributes.Add("value", sdr["userPwd"].ToString());

网站地址栏前加自己的图标logo

head标签里加上

<link rel="Shortcut Icon"   href="~/images/图标.ico"/>

Gridview联动绑定DropDownList

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
GridViewRow row = e.Row;
        if (e.Row.DataItem != null)
        {
//Gridview内动态注册javascript
//判断是否以注册
//if(!ClientScript.IsClientScriptIncludeRegistered(This.GetType(), "Expand"))
//如果没注册添加注册
//Page.ClientScript.RegisterStartupScriptInclude("Expand","/Script/Info.js")
//如果没注册添加注册指令区块
//string Info="<SCRIPT LANGUAGE='javascript'>expandcollapse('div" + DataBinder.Eval(e.Row.DataItem, "AgentCode").ToString() + "','one');</script>"
//Page.ClientScript.RegisterStartupScriptBlock(This.GetType(),"Expand",Info,true)
//使用动态注册Javascript
//Page.ClientScript.RegisterStartupScript(This.GetType(),"Expand",Info)
//Gridview内调用javascript
ClientScript.RegisterStartupScript(This.GetType(), "Expand", "<SCRIPT LANGUAGE='javascript'>expandcollapse('div" + DataBinder.Eval(e.Row.DataItem, "AgentCode").ToString() + "','one');</script>");
//Gridview绑定一个Gridview
gv = (GridView)e.Row.Cells[0].FindControl("GridView2");
//根据Gridview1的id作为Gridview2条件绑定方法GetA(id)
gv.DataSource = BLL.A.GetA(Convert.ToString(DataBinder.Eval(e.Row.DataItem, "ID")));
gv.DataBind();
if (e.Row.RowType == DataControlRowType.DataRow)
            {
if (((DropDownList)e.Row.FindControl("ddlcountry")) != null)
                {
                    DropDownList ddlcountry = (DropDownList)e.Row.FindControl("ddlcountry");
                    AgentCountryInfo a = new AgentCountryInfo();
                    ddlcountry.Items.Clear();
                    ddlcountry.Items.Add(new ListItem("", ""));
                    foreach (AgentCountryInfo x in BLL.Country.AgentGetCountryByA(a))
                    {
                        ddlcountry.Items.Add(new ListItem(x.countrycode, x.countrycode));
                    }
                    string hdf = ((HiddenField)e.Row.FindControl("HDFcountry")).Value;
                    //当更改时,绑定第一个为它所属的分类
                    ddlcountry.SelectedValue = hdf;//第二种方法:ddlocean.Items.FindByText(hdf).Selected = true;
                }
}
}
}
//联动绑定
protected void ddlcountry_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList d1 = (DropDownList)sender;
        GridViewRow gvr = (GridViewRow)d1.NamingContainer;
        DropDownList ddlCity = (DropDownList)GridView1.Rows[gvr.RowIndex].FindControl("ddlCity");
        AgentCityInfo a = new AgentCityInfo();
        a.CountryCode = d1.SelectedValue;

        ddlCity.Items.Clear();
        ddlCity.Items.Add(new ListItem("", ""));
        foreach (AgentCityInfo x in BLL.City.AgentGetCityByA(a))
        {
            ddlCity.Items.Add(new ListItem(x.CityCode, x.CityCode));
        }
    }

闰年计算

:能被4整除,但不能被100整除;能被100整除,又能被400整除,除了这个之外都是非闰年;

Int32 i = Int32.Parse(year);//将输入的数字转换为整型格式
bool yearleap = (i % 400 == 0) || (i % 4 == 0) && (i % 100 != 0);//采用布尔数据计算判断是否能整除
string isyearleap = yearleap ? "是" : "不是";//使用条件运算符判断比较简化

分享到源码

<!-- Baidu Button BEGIN -->
                            <div id="bdshare" class="bdshare_t bds_tools_32 get-codes-bdshare">
                                <a class="bds_qzone"></a><a class="bds_tsina"></a><a class="bds_tqq"></a><a class="bds_renren">
                                </a><a class="bds_t163"></a><span class="bds_more"></span><a class="shareCount">
                                </a>
                            </div>

                            <script type="text/javascript" id="bdshare_js" data="type=tools&uid=759741"></script>

                            <script type="text/javascript" id="bdshell_js"></script>

                            <script type="text/javascript">
                                document.getElementById("bdshell_js").src = "http://bdimg.share.baidu.com/static/js/shell_v2.js?cdnversion=" + Math.ceil(new Date() / 3600000)
                        </script>

                            <!-- Baidu Button END -->


动态添加控件

RadioButton r = new RadioButton();
r.Text = "hhc";
Panel1.Controls.Add(r);


JS获取Asp.Net服务器端控件ID

var clientID = document.getElementById("<%=TextBox1.ClientID%>");


JS执行Asp.Net/C#后台方法代码

后台代码(public或者protected)

public string ss() 
  { 
    return("我要用js实现"); 
  }
JS调用

<script language="javascript">
  var a = "<%=ss()%>";
  alert(a);
</script>

JS获取RadioButtonList和CheckBoxList的value

<head runat="server">
    <title>JS获取RadioButtonList和CheckBoxList的value</title>
    <script type ="text/javascript" language ="javascript" >
        function fn_GetRadioButtonListInfo() {
            //取得RadioButtonList的集合
            var radListItems = document.all("RadioButtonList1");
            if (radListItems == null) {
                alert("相关对象对空");
                return false;
            }
            //弹出RadioButtonList的Item的个数
            var radListItesCount = radListItems.length - 1;
            var radListCheckedValue = "";
            //遍历Item的Text和Value
            for (var i = 1; i <= radListItesCount; i++) {
                if (radListItems[i].checked)
                    radListCheckedValue = radListItems[i].value;
            }
            if (radListCheckedValue == "") {
                alert("没有选中值");
            }
            else {
                alert("选中Value 为 : " + radListCheckedValue);
            }
            return false;
        }
        function fn_GetCheckBoxListInfo() {
            //取得CheckBoxList的集合
            var ckbListItems = document.all("CheckBoxList1");
            //var ckbListItems = document.getElementById("CheckBoxList1");
            if (ckbListItems == null) {
                alert("相关对象对空");
                return false;
            }
            var chks = ckbListItems.getElementsByTagName("input");
            var ckbListCheckedValue = "";
            var ckbListItesCount = chks.length - 1;
            //遍历Item的Text和Value
            for (var i = 1; i <= ckbListItesCount; i++) {
                var chk = chks[i];
                if ((chk != null && chk.type == 'checkbox' && chk.checked)) {
                    ckbListCheckedValue += ",";
                    ckbListCheckedValue += chk.value;                    
                }
            }
            if (ckbListCheckedValue == "") {
                alert("没有选中值");
            }
            else {
                if (ckbListCheckedValue.length > 1)
                    ckbListCheckedValue = ckbListCheckedValue.substring(1); 
                alert("选中Value 为 : " + ckbListCheckedValue);
            }
            return false;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="RadioButtonList">
        <asp:RadioButtonList ID="RadioButtonList1" runat="server"
            RepeatColumns="4" RepeatDirection="horizontal">
            <asp:ListItem Value="1" Text="A1"></asp:ListItem>
            <asp:ListItem Value="2" Text="A2"></asp:ListItem>
            <asp:ListItem Value="3" Text="A3"></asp:ListItem>
            <asp:ListItem Value="4" Text="A4"></asp:ListItem>
        </asp:RadioButtonList>
        <input id="Button1" type="button" value="button" οnclick="fn_GetRadioButtonListInfo();" />
    </div>
    <div>
        <asp:CheckBoxList ID="CheckBoxList1" runat="server" 
        RepeatColumns="4"  RepeatDirection="horizontal">
            <asp:ListItem Value="1" Text="A1"></asp:ListItem>
            <asp:ListItem Value="2" Text="A2"></asp:ListItem>
            <asp:ListItem Value="3" Text="A3"></asp:ListItem>
            <asp:ListItem Value="4" Text="A4"></asp:ListItem>
        </asp:CheckBoxList>
        <input id="Button2" type="button" value="button" οnclick="fn_GetCheckBoxListInfo();" />
    </div>
    </form>
</body>

GridView和CheckBox全选

前台

<asp:TemplateField HeaderText="选择">
<HeaderTemplate>
<asp:CheckBox ID="ckb" runat="server" Text="全选" AutoPostBack="true" OnCheckedChanged="ckb_CheckedChanged" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="ckbSelected" runat="server" />
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" Width="55px" Font-Size="14px" />
<ItemStyle HorizontalAlign="Left" Width="55px" />
</asp:TemplateField>
后台

protected void ckb_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox ckb = sender as CheckBox;
        if (ckb.Checked)
        {
            for (int i = 0; i < this.gvwList.Rows.Count; i++)
            {
                CheckBox cb = (gvwList.Rows[i].FindControl("ckbSelected")) as CheckBox;
                cb.Checked = true;
            }
        }
        else
        {
            for (int i = 0; i < this.gvwList.Rows.Count; i++)
            {
                CheckBox cb = (gvwList.Rows[i].FindControl("ckbSelected")) as CheckBox;
                cb.Checked = false;
            }

        }
    }


注:欢迎喜爱编程的朋友进群交流。QQ群交流:256169347

群共享了很多pdf书籍文档


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值