.NET 大杂烩

目录:

1.javascript弹出提示窗口(不改变原页面样式);

2..net之EMail正则表达式验证;

3.Gridview中绑定数据常用的有两种方式;

4.获取Gridview控件中添加的Label控件或者Button控件实例有以下几种方法(不同情况时用);

5.返回"按钮"事件(返回到原页面);

6.GridView的DataBound事件中判断行的类型;

7.OnClientClick带参数事件;

8.GridView中添加统计列;

9.GridView中添加统计行;

10.FileUpload控件上传图片;

11.ImageButton控件显示图片;

12.SQL添加序号;

13.SQL时间12小时制格式;

14.SQL语言环境下的时间格式;

 

1.javascript弹出提示窗口(不改变原页面样式)

ClientScript.RegisterStartupScript(typeof(string), "", "<script>alert('提示内容.');</script>");

2..net之EMail正则表达式验证

string emailReg = @"^[\w-]+(?:\.[\w-]+)*@(?:[\w-]+\.)+[a-zA-Z]{2,7}$";
if (!Regex.IsMatch(tb_Email.Text.Trim(), emailReg))
{
     ClientScript.RegisterStartupScript(typeof(string), "", "<script>alert('Please Enter a right Email format.');</script>");
     tb_Email.Focus();
     return;
}

 3.Gridview中绑定数据常用的有两种方式:

<asp:TemplateField HeaderText="xxxx">
    <ItemTemplate>
         <%#strDate(Convert.ToString(Eval("xxxx")))%>
    </ItemTemplate>
    <HeaderStyle Width="12%"  />
    <ItemStyle Width="12%" />
</asp:TemplateField>
或者
<asp:BoundField DataField="xxxx" HeaderText="xxxx">
    <HeaderStyle Width="12%" />
</asp:BoundField>

获取表内某一行某列数据的方式也有不同,分别为:

方式一:((DataBoundLiteralControl)e.Row.Cells[i].Controls[0]).Text.Trim();//适用于TemplateField绑定的数据
方式二:e.Row.Cells[i].Text;//适用于BoundField绑定的数据

说明:e或者为Gridview的ID,i代表列数

4.获取Gridview或Repeater控件中添加的Label控件或者Button控件实例有以下几种方法(不同情况时用):

在Gridview事件中:
Label titleID = (Label)e.Row.Cells[i].FindControl("titleID"); 
Button download = (Button)e.Row.Cells[i].FindControl("btn_Download");
说明:i为列数,btn_Download为控件ID

不在Gridview事件中: 例如:点击嵌套在Gridview中LinkButton事件,如图:

protected void libCustomize_Click(object sender, EventArgs e)
        {
            LinkButton lic = sender as LinkButton;
            DataControlFieldCell dc = lic.Parent as DataControlFieldCell;
            GridViewRow r = dc.Parent as GridViewRow;
            string titleID = GridView1.DataKeys[r.RowIndex].Value.ToString();
         }
在Repeater事件中:
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType==ListItemType.AlternatingItem )
            {
                DataRowView drv = (DataRowView)e.Item.DataItem;
                Response.Write(drv.Row.ItemArray[0].ToString()+"<br />");//drv.Row.ItemArray[0]就是你要取的数据源中的第0列了,你的Uname在第几列就自己写了。。。
            }
        }
不在Repeater事件中: 例如:点击嵌套在Repeater中ImageButton事件,如图:

protected void BookImg_Click(object sender, ImageClickEventArgs e)
        {
            ImageButton btn = (ImageButton)sender;
            RepeaterItem item = (RepeaterItem)btn.Parent;
            Label titleID = item.FindControl("titleID") as Label;
            if (titleID != null && titleID.Text != "")
            {
                string str = "BookDetails.aspx?titleId=" + titleID.Text.Trim();
                Response.Redirect(str);
            }
        }
需要这样才能获取到titleID的值。

5.返回"按钮"事件(返回到原页面):

<input name="button" type="reset" id="button4" style="width: 120px;" onclick="self.location.replace('javascript:history.back()');" value="Go Back">

 6.GridView的DataBound事件中判断行的类型:

if(e.Row.RowType==DataControlRowType.DataRow)

 7.OnClientClick带参数事件:

OnClientClick=<%#"ShowModalDialog('"+ (string)DataBinder.Eval(Container.DataItem,"id")+"')"%>

注:*ShowModalDialog()为javascript方法 *(string)DataBinder.Eval(Container.DataItem,"id")为后台绑定参数 *“id”为某一列名

 8.GridView中添加统计列:

DataSet ds = dbSys.ExecuteDataSet(sql);

            if (ds != null && ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
            /*添加列从这里开始
                    BoundField bf = new BoundField();
                    bf.HeaderText = "Result of " + DateTime.Now.Year.ToString();
                    bf.DataField = "MarketTypeDesc";
                    bf.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
                    GridView3.Columns.Insert(0, bf);
            这里结束添加列*/
this.GridView3.DataSource = ds.Tables[0]; this.GridView3.DataBind(); } else { ds.Tables[0].Rows.Add(ds.Tables[0].NewRow()); GridView3.DataSource = ds.Tables[0]; GridView3.DataBind(); GridView3.Rows[0].Visible = false; } }

9.GridView中添加统计行:

DataSet ds = dbSys.ExecuteDataSet(sql);

            if (ds != null && ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
            /*添加统计行从这里开始 DataRow dr
= ds.Tables[0].NewRow(); dr["Criteria"] = "Grand Total"; dr["companyno"] = ds.Tables[0].Compute("Sum(companyno)", "1=1"); dr["Contribution"] =ds.Tables[0].Compute("Sum(Contribution)", "1=1"); ds.Tables[0].Rows.Add(dr);
            这里结束添加行*/
this.GridView2.DataSource = ds.Tables[0]; this.GridView2.DataBind(); this.BindPercent(Convert.ToDouble(dr["Contribution"].ToString()), Convert.ToDouble(dr["companyno"].ToString())); } else { ds.Tables[0].Rows.Add(ds.Tables[0].NewRow()); GridView2.DataSource = ds.Tables[0]; GridView2.DataBind(); GridView2.Rows[0].Visible = false; } }

10.FileUpload控件上传图片:

 step1:webconfig添加配置

<appSettings>
    <add key="ImageLoadFolder"  value="Rapid3DImage" />
</appSettings>

step2:cs代码

            //idFile为控件ID
            string filePath = this.idFile.PostedFile.FileName;  

            //设置存放图片目录
            string imageFolder = Server.MapPath("..") + "\\" + WebConfigrationManager.AppSettings["ImageLoadFolder"];
            //判断目录是否存在
            if (!Directory.Exists(imageFolder))  
            {
                //不存在则创建
                Directory.CreateDirectory(imageFolder);  
            }

            //获取图片完整路径+文件名
            string productImage = Path.Combine(imageFolder, Path.GetFileName(filePath));
            int i = 0;
            //判断文件名是否已经存在
            while (File.Exists(productImage))
            {
                //存在,则文件名称加1
                productImage = Path.Combine(imageFolder, Path.GetFileNameWithoutExtension(filePath) + i.ToString() + Path.GetExtension(filePath));
                i++;
            }
            //将控件上的文件保存至服务器
            idFile.PostedFile.SaveAs(productImage);
            //取文件名
            productImage = Path.GetFileName(productImage);

 11.ImageButton控件显示图片:

step1:webconfig添加配置

<appSettings>
    <add key="ImageLoadFolder"  value="Rapid3DImage" />
</appSettings>

step2:.aspx

<%@ Import Namespace="****.Lib" %>    //在前台导入命名控件以便调用step3方法
<asp:ImageButton ID="ImageButton1" runat="server" Width="90px" Height="120px" OnClick="BookImg_Click" ImageUrl='<%#ImageProcess.GetImagePath(Convert.ToString(Eval("IMAGE")))%>'/></div>  //Convert.ToString(Eval("IMAGE")为数据库保存名称

step3:.cs 类里面添加静态方法供step2调用

public static class ImageProcess
    {       

        public static string GetImagePath(string image)
        {
            string imageFolder = ConfigurationManager.AppSettings["ImageLoadFolder"];

            if (!string.IsNullOrEmpty(imageFolder))
            {
                return "../" + imageFolder + "/" + image;
            }
            else
            {
                return string.Empty;
            }
                  
        }

    }

12.SQL添加序号: 

ROW_NUMBER()over(order by getdate()) as No

13.SQL时间12小时制格式:

select substring(convert(varchar(50),convert(datetime,'18:12:45'),0),12,8)

14.SQL语言环境下的时间格式:

--设置会话的语言环境为: English
SET LANGUAGE N'English'
SELECT 
DATENAME(Month,GETDATE()) AS [Month],
DATENAME(Weekday,GETDATE()) AS [Weekday],
CONVERT(varchar,GETDATE(),109) AS [CONVERT]
/*--结果:
Month    Weekday   CONVERT
------------- -------------- -------------------------------
March    Tuesday   Mar 15 2005 8:59PM
--*/

--设置会话的语言环境为: 简体中文
SET LANGUAGE N'简体中文'
SELECT 
DATENAME(Month,GETDATE()) AS [Month],
DATENAME(Weekday,GETDATE()) AS [Weekday],
CONVERT(varchar,GETDATE(),109) AS [CONVERT]
/*--结果
Month    Weekday    CONVERT
------------- --------------- -----------------------------------------
05       星期四     05 19 2005 2:49:20:607PM
--*/

 

posted @ 2012-04-27 11:06  刀叨  阅读(236)  评论(0编辑  收藏  举报