asp.net 学习笔记

aspnetpager分页使用

Imports System.Data
Imports System.Data.SqlClient

Partial Class test_aspnetpager
    Inherits System.Web.UI.Page
    Dim cn As New SqlConnection


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        AspNetPager1.AlwaysShow = True
        AspNetPager1.PageSize = 15

        If Not Page.IsPostBack Then
            Dim rowid As Long
            cn = New SqlConnection(ConfigurationManager.ConnectionStrings("pay_info_tooConnectionString").ConnectionString)
            Dim cm As New SqlCommand("select count(*) from info_all", cn)
            cm.Connection.Open()
            Dim dr As SqlDataReader
            dr = cm.ExecuteReader

            If dr.HasRows Then

                dr.Read()
                rowid = dr(0)
            End If
            dr.Close()
            cm.Dispose()
            cm = Nothing

            AspNetPager1.RecordCount = rowid
            cn.Close()

            databind1()
        End If

    End Sub
    Sub databind1()
        cn = New SqlConnection(ConfigurationManager.ConnectionStrings("pay_info_tooConnectionString").ConnectionString)
        Dim da As New SqlDataAdapter("select * from info_all order by in_id desc", cn)
        Dim rs As New DataSet
        da.Fill(rs, AspNetPager1.PageSize * (AspNetPager1.CurrentPageIndex - 1), AspNetPager1.PageSize, "info_all")
        GridView1.DataSource = rs.Tables("info_all")
        GridView1.DataBind()

    End Sub

 

    Protected Sub AspNetPager1_PageChanging(ByVal src As Object, ByVal e As Wuqi.Webdiyer.PageChangingEventArgs) Handles AspNetPager1.PageChanging
        AspNetPager1.CurrentPageIndex = e.NewPageIndex
        databind1()

    End Sub
End Class

 

数据绑定在gridview中使用

checkbox不能直接在gridview中应用,他的值是0或1才能绑定datefiled字段,否则需用模板字段

 <asp:CheckBox ID="CheckBox1" runat="server" Text='<%# eval("in_id") %>' />   得原值
<asp:CheckBox ID="CheckBox1" runat="server" Text='<%# eval("in_id","[{0}]") %>' /> 值的两边加[]


格式字符串 结果
{0:d}     YY-MM-DD
{0:p}     百分比00.00%
{0:N2} 12.68
{0:N0} 13
{0:c2}    $12.68
{0:d}      3/23/2003      
{0:T}     12:00:00 AM
{0:男;;女}

格式字符串 资料 结果
"{0:C}" 12345.6789 -> $12,345.68
"{0:C}" -12345.6789 -> ($12,345.68)
"{0:D}" 12345 12345
"{0:D8}" 12345 -> 00012345
"{0:E}" 12345.6789 -> 1234568E+004
"{0:E10}" 12345.6789 -> 1.2345678900E+004
"{0:F}" 12345.6789 -> 12345.68
"{0:F0}" 12345.6789 -> 12346
"{0:G}" 12345.6789 -> 12345.6789
"{0:G7}" 123456789 -> 1.234568E8
"{0:N}" 12345.6789 -> 12,345.68
"{0:N4}" 123456789 -> 123,456,789.0000
"Total: {0:C}" 12345.6789 -> Total: $12345.68


{0:C}  货币;
{0:D4}由0填充的4个字符宽的字段中显示整数;
{0:000.0}四舍五入小数点保留第几位有效数字;
{0:N2}小数点保留2位有效数字;{0:N2}%   小数点保留2位有效数字加百分号;
{0:D}长日期;{0:d}短日期;{0:yy-MM-dd}   例如07-3-25;;{0:yyyy-MM-dd}  例如2007-3-25


格式字符串
1、常用的数值格式字符串:
C或c 货币格式
D或d 十进制格式
E或e 科学(指数)格式
F或f 固定小数位格式
G或g 一般格式
N或n 数字格式
P或p 百分比格式
X或x 十六进制格式

2、常用的日期格式字符串:
d      短日期
D      长日期
f      完整(长日期和短时间)
F      完整(长日期和长时间)
g      一般(短日期和短时间)
G      一般(短日期和长时间)
M或m   月和日
R或r   RFC1123格式
s      使用本地时间的ISO8601可分类
t      短时间
T      长时间
u      使用通用时间的ISO8601可分类
U      通用可分类日期/时间
Y或y   年和月

3、数字的图片格式字符
0 没有有效值则显示0
# 数字占位符
. 小数点
, 分隔符
% 百分比
E+0,E-0,e+0或e-0 将输出格式为科学或指数含义
/ 转义字符
"或' 它们之间的任何字符都被解释为字符串
{和} 用于显示单文字性花括号,如"{{"显示为"{"
;分隔格式字符串中正、负和零值的两个或三个部分


今天看到一篇关于GridView使用的文章感觉很好,特来分享,关于向服务器添加事件
1、删除前加判断
protected void gv_productJingPing_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
         e.Row.Cells[4].Attributes.Add(" "javascript:return confirm('您真的要删除["+e.Row.Cells[1].Text+"]吗?')");
    }
}

2、编辑时控制文本框的宽度
protected void gv_productJingPing_RowDataBound(object sender, GridViewRowEventArgs e)
{
     if(e.Row.RowType == DataControlRowType.DataRow)
     {
          if ((e.Row.RowState & DataControlRowState.Edit) != 0)
          {
               TextBox txtUrl = (TextBox)e.Row.Cells[2].Controls[0];
               txtUrl.Width = 230;
          }
      }
}
(说明:如果使用模板列,则可自定义列长)

3、显示图片
<asp:ImageField DataImageUrlField="imagepath" DataImageUrlFormatString="img/{0}">
</asp:ImageField>
说明:imagepath指的是数据库图片字段名,img指图片存放位置

4 、 GridView的双击/单击/键盘按键/鼠标悬浮/移出等事件
<script language="javascript">       
         function DbClickEvent(d)
         {
               window.alert("事件类型: DoubleClidk   作用对象: " + d);           
         }
         function ClickEvent(d)
         {
               window.alert("事件类型: OnClick   作用对象: " + d);           
         }
         function GridViewItemKeyDownEvent(d)
         {
               window.alert("事件类型: GridViewItemKeyDownEvent   作用对象: " + d);      
         }         
</script>
          (绑定事件)
if( e.Row.RowType == DataControlRowType.DataRow)
{
          //鼠标移动到每项时颜色交替效果
          e.Row.Attributes.Add ("OnMouseOut",   "this.style.backgroundColor='White';this.style.color='#003399'");
          e.Row.Attributes.Add("OnMouseOver", "this.style.backgroundColor='#6699FF';this.style.color='#8C4510'");
          //单击/双击 事件
          e.Row.Attributes.Add("OnDblClick", "DbClickEvent('" + e.Row.Cells[1].Text + "')");
          e.Row.Attributes.Add("OnClick", "ClickEvent('" + e.Row.Cells[1].Text + "')");
          e.Row.Attributes.Add("OnKeyDown", "GridViewItemKeyDownEvent('" + e.Row.Cells[1].Text + "')");
          //设置悬浮鼠标指针形状为"小手"
          e.Row.Attributes["style"] = "Cursor:hand";
        
}

5、将GridView的列的Visible设置为false时,该列无法更新到数据库

优化性能
SqlConnection con = new SqlConnection();
conn.ConnectionString = "server=(local);dataset=mydb;uid=sa;pwd=xxx";
SqlCommand cmd = new SqlCommand("select name1,name2 from name where id=1", conn);
conn.Open();
SqlDataReader dtr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
dtr.read();
Text1.text=dtr["name1"].ToString();
Text2.text=dtr["name2"].ToString();


双击GridView的OnRowDataBound事件;
在后台的GridView1_RowDataBound()方法添加代码,最后代码如下所示:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//如果是绑定数据行
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
{
((LinkButton)e.Row.Cells[6].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你确认要删除:/"" + e.Row.Cells[1].Text + "/"吗?')");
}
}

}

 

WebConfig加密

数据库的连接字符串标准都是放到web.config里,因为有API可以直接访问并取出数据,这样实际上非

常不安全,都是以明文形式显示的,如果WEB服务器被黑客或木马将其WebConfig配置文件获取,那数据库

将是一场灾难.加密的方式有很多种,但过于繁琐就显得很不方便,.NET 里有ASP.NET IIS 注册工具

(Aspnet_regiis.exe) 这样的一个工具,可以对站点的.config文件的节进行加密
方法:

加密:aspnet_regiis -pef "加密的web.config里面的配置节名称" "web.config文件所处的目录"
解密:aspnet_regiis -pdf "加密的web.config里面的配置节名称" "web.config文件所处的目录"

aspnet_regiis -pef "connectionStrings" "d:/introor/wwwroot/cp"

大小写区分,目录为大写目录

加密之前:
<connectionStrings>
<add name="pubsConnectionString" connectionString="Data Source=MHL/SQL2000;Initial

Catalog=pubs;User ID=sa;Password=sql2000"
   providerName="System.Data.SqlClient" />
</connectionStrings>
加密之后:
    <connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">
<EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
   xmlns="http://www.w3.org/2001/04/xmlenc#">
   <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
   <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
    <EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
     <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
     <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
      <KeyName>Rsa Key</KeyName>
     </KeyInfo>
     <CipherData>
    

<CipherValue>e15rhABrAtua53kjZ2a3U+ijC/Hr5ZhGUWGL5swkfxJaHS6hxGacw7CxyNlhnJwRc44ZE2edsKRfS

JeXPS76fe4znlE5BqaxMMMWK+yFMiuWM+Cor1DFffheRNjAB7pMYdRQoMRCBq6H18gxIGlRY1dXtUERzNLJ5ug+S/q

dj8E=</CipherValue>
     </CipherData>
    </EncryptedKey>
   </KeyInfo>
   <CipherData>
  

<CipherValue>Y1SjIK04jc0cS8Fg7EJyLoiXAUWc+I708SOsebWHeihg4kRFEF4wGvQLyrZQqFXNUIm56tIktQgap

d7px92nfwAzYFv8R2gYV/7JwjfbjpM1v27p5WgNycJbo8H4uNj4LwgPfoqy2Dl41geMFHXCOak8IWxrA8MkbpIsKHF

TJNkMo9yph+vVUMdViwaBSOKONSrXJ2k16kjHoSjJe1VP6WfMFZCeL7+nMuLf4sNZc34d0fl3S50H+kNwZre9MkUCS

Lr5pImCv5fhgHP+Ee9QwS8ahvOvRwUY7kWMr+M+jKoS+FDbhuRIkcbWaPP75XzdmyBN/vGwcMfX63faA9vdNOsl1a7

5Kd0L</CipherValue>
   </CipherData>
</EncryptedData>
</connectionStrings>

加密码后出在iis配置时出现

配置错误:未能使用提供程序“RsaProtectedConfigurationProvider”进行解密。提供程序返回错误信息为: 打不开 RSA 密钥容器。
源文件: C:/WINDOWS/Microsoft.NET/Framework/v2.0.50727/Config/web.config。

通过如下解决

aspnet_regiis -pa "NetFrameworkConfigurationKey" "NT AUTHORITY/NETWORK SERVICE"

 

文件的源文件中要引用code中的变量时,要把变量public

public user_code as string

然后在页面中就可以用啦<%=user_code%>


Asp.Net 2.0 中实现了IButtonControl接口的控件都有一个PostBackUrl属性,可以进行跨页面提交,就是用的POST方法。那么在1.x中费了一番周折的POST提交就很简单了,只要把PostBackUrl设置为提交页,在那提交页用Request.Params[]就能拿到POST的表单参数了。还能用PreviousPage.FindControl去取前一页的控件。这里用Request和PreviousPage去取值都和Server.Transfer很象,但CrossPagePo
    End Function

 


    Function getpage(ByVal weburl As String) As String
        Try
            Dim httpreq As System.Net.HttpWebRequest
            Dim httpresp As System.Net.HttpWebResponse
            Dim url As String = weburl
            Dim httpurl As New System.Uri(url)
            httpreq = CType(WebRequest.Create(httpurl), HttpWebRequest)
            httpreq.Method = "GET"
            httpresp = CType(httpreq.GetResponse, HttpWebResponse)
            Dim reader As StreamReader = New StreamReader(httpresp.GetResponseStream, System.Text.Encoding.GetEncoding("utf-8"))
            Dim resphtml As String = reader.ReadToEnd

            httpresp.Close()
            Return resphtml

        Catch ex As Exception
            Return "产生错误!"
        End Try
        Return "产生错误!"

    End Function


    Public Sub PostDataMy(ByVal URL As String, ByVal PostInfo As String)

        Dim HostUrl As New System.Uri(URL)
        Dim ReQ As HttpWebRequest
        ReQ = CType(WebRequest.Create(HostUrl), HttpWebRequest)
        ReQ.Timeout = 30000                                  '设置超时值30秒
        ReQ.Method = "POST"                                 '我们是要传送内容
        '将字符串转成字节组,记住,编码类新要选为默认
        Dim BytesData() As Byte = System.Text.Encoding.Default.GetBytes(PostInfo)
        '设置传送的数据长度
        ReQ.ContentLength = BytesData.Length
        Dim PostStream As Stream = ReQ.GetRequestStream()
        PostStream.Write(BytesData, 0, BytesData.Length)
        '以上向服务器 POST 信息。
        '以下是获取服务器返回信息

        Try

            Dim res As HttpWebResponse = CType(ReQ.GetResponse(), HttpWebResponse)
            Dim ReStream As StreamReader = New StreamReader(res.GetResponseStream, System.Text.Encoding.GetEncoding("GB2312"))
            Dim resStr As String = ReStream.ReadToEnd()
            TextBox1.Text = resStr
            Response.Write(res.StatusCode.ToString)
            res.Close()

        Catch ex As Exception

            Response.Write(ex.ToString)
        End Try
        'MsgBox(response.StatusCode.ToString)         '向网络服务器 POST 后返回的状态码,成功则返回"OK"
        '关闭
    End Sub


asp.net调用javascrpt

中不知道为什么不能放在.js中,需要考到.net项目中走一下

页面的一些变量可以放在viewstate("a")中

在gridview中的 select deleltelinkbutton 之间有一个空间,用于空格,如果选取delete 得使用e.row.cells(0).controls(2)来使用他

 

datalist中的使用 绑定

        <asp:DataList ID="DataList1" runat="server" Font-Names="宋体">
            <ItemTemplate>
<table border="1" cellpadding="0" cellspacing="0" width="800px"  bordercolorlight="#D9D9D9" bordercolordark="#FFFFFF">
 <tr>
  <td height="22" bgcolor="#E8EEED">
  <p align="center">
            <asp:Label ID="Label1" runat="server" Text="<%# bind('title') %>" Font-Bold=true></asp:Label>
             <asp:Label ID="Label2" runat="server" Text="<%# bind('adate') %>"></asp:Label>
        </td>
 </tr>
 <tr>
  <td valign="top">
  <p style="line-height: 150%">
            <br />
            <asp:Label ID="Label3" runat="server"><%#zhgs(Eval("content").ToString())%></asp:Label>
             <br /><br />
        </td>
 </tr>
</table>
            </ItemTemplate>
        </asp:DataList>

 

使用stateserver中使用session,可以用usecookies模式,不用inurl模式


在asp.net中显示安全的错误信息,可以把 debut=false;
1.<compilation debug="false" strict="false" explicit="true">
2.<customErrors mode="RemoteOnly"/>

 

全局函数放在web.config 中

<configuration>
 <appSettings>

   <add key="Config" value="/INC/XML/Config.XML" />

</appSettings>

 调用

Response.Write(ConfigurationManager.AppSettings("Config").ToString())

直接选列名

   Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim dr As DataRowView
            dr = e.Row.DataItem
            If (dr("pay_type") Is System.DBNull.Value) Then
                e.Row.BackColor = Drawing.Color.Bisque
                e.Row.Cells(4).Text = "空"
                Response.Write("ok")
            End If

        End If
    End Sub

编译dll

C:/WINDOWS/Microsoft.NET/Framework/v3.5/vbc /out:D:/Inetpub/wwwroot8/2008/App_Code/bin/test.dll /t:library D:/Inetpub/wwwroot8/2008/App_Code/index.vb


我的第一个linq

新建 cp.dbml,把数据库中的表拖进画板中,生成

Imports cpDataContext--------------------------------
Partial Class linq_1
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim cp As New cpDataContext


        Dim query1 = From p In cp.cp_tongdao _
                    Select p.id, p.zl
        GridView1.DataSource = query1
        GridView1.DataBind()

 

    End Sub
End Class

 

Imports cpDataContext
Imports infoallDataContext
Partial Class linq_1
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        AspNetPager1.Visible = True
        AspNetPager1.PageSize = 10
        If Not Page.IsPostBack Then
            bindfy()
        End If
        ' bind()
        '  infocount()
    End Sub
    Sub bind()
        Dim cp As New cpDataContext
        Dim ds = (From p In cp.cp_tongdao1s _
                 Where p.id > 1 _
                 Select p.hm, p.zl)
        For Each z In ds
            Response.Write(String.Format("{0}<bR>", z.hm.ToString))

        Next

        Response.Write(ds.Count())
        ds = Nothing
        cp.Dispose()

    End Sub
    Sub infocount()
        Dim cp As New infoallDataContext

        Dim ds As Array = (From p In cp.info_alls _
                 Select p.in_id, p.in_book).ToArray
        Response.Write(ds.Length)

    End Sub
    Sub gx()

        Dim cp As New cpDataContext
        Dim tongdao = (From p In cp.cp_tongdaos _
                     Where p.hm = "1" _
                     Select p).Single
        tongdao.hm = "1106698815"
        cp.SubmitChanges()
    End Sub

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        gx()
    End Sub
    Sub bindfy()


        Dim cp As New infoallDataContext

        Dim dsc = From p In cp.info_alls _
                 Select p
        AspNetPager1.RecordCount = dsc.Count


        Dim ds = (From p In cp.info_alls _
                 Select p).Skip((AspNetPager1.CurrentPageIndex - 1) * AspNetPager1.PageSize).Take(AspNetPager1.PageSize)

        GridView1.AutoGenerateColumns = True
        GridView1.DataSource = ds
        GridView1.DataBind()
    End Sub

    Protected Sub AspNetPager1_PageChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles AspNetPager1.PageChanged

    End Sub

    Protected Sub AspNetPager1_PageChanging(ByVal src As Object, ByVal e As Wuqi.Webdiyer.PageChangingEventArgs) Handles AspNetPager1.PageChanging
        AspNetPager1.CurrentPageIndex = e.NewPageIndex
        bindfy()
    End Sub
End Class

Imports info_all
Partial Class linq_2
    Inherits System.Web.UI.Page

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

 

    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            bind()
        End If
    End Sub
    Sub bind()
        Dim info As New infoallDataContext
        Dim result = From i In info.info_all _
                     Select n = New With {i.in_id, i.in_book, i.in_mobile, i.type_id} _
                        Order By n.in_id Descending
        GridView1.DataSource = result
        GridView1.DataBind()
    End Sub

    Protected Sub GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridView1.PageIndexChanging
        GridView1.PageIndex = e.NewPageIndex
        bind()
    End Sub

    Protected Sub GridView1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.SelectedIndexChanged

    End Sub

    Protected Sub GridView1_SelectedIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSelectEventArgs) Handles GridView1.SelectedIndexChanging

    End Sub
End Class


事条回滚


            OracleConnection con = dbclass.GetOracleConnection();
            OracleCommand com = new OracleCommand();

            //用事务对数据进行多表插入
            com.Connection = con;
            com.Transaction = con.BeginTransaction();
            try
            {
                //.....要插入的方法语句

                com.Transaction.Commit();
                return true;
            }
            catch (Exception ee)
            {
                com.Transaction.Rollback();

                string error = ee.Message.Replace("'", " ");


                return false;
            }


遍历页面中textbox

        Dim i As Integer
        For i = 1 To 3
            Dim t As TextBox
            t = Page.FindControl("textbox" & i)
            Response.Write(t.Text)
        Next


自动选取客户资源文件,

把页面的uiculcure 设为auto,系统为根据客户端语言选项,也可以在web.config中设置

新建一个global_resuoure文件夹

然后建立Resource.en.resx,Resource.resx 两个文件把其中string1改为path 值为路径 en.的path改为address

在程序中直接调用

Button1.Text = Resources.Resource.path


    <asp:TextBox ID="TextBox1" runat="server"
        Text="<%$ Resources:resource, path %>"></asp:TextBox>

局部资源文件是local_


在站点中建立局部资源文件的时候,VS.Net2005会自动建立一个App_LocalResources文件夹专门来存放局部资源文件。所谓局部资源文件,也就是给站点中单一页面文件使用的资源文件。它的命名方式一般是Default.aspx.resx和Default.aspx.zh-cn.resx。现在我在Default资源文件中添加三个键Language、lblNavigation.Text和lblNavigation.ForeColor。其中我为Default.aspx.resx的lblNavigation.ForeColor设置blue,为Default.aspx.zh-cn.resx的lblNavigation.ForeColor设置red。在页面文件中Default.aspx中从局部资源文件里获得内容的方法如下有两种:
(1). <asp:Label ID="lblLanguage" runat="server" Text="<%$ Resources:Language %>"></asp:Label>
(2). <asp:Label ID="lblNavigaion" runat="server" meta:resourcekey="lblNavigation"></asp:Label>
使用第一种方法时要注意使用符号$。使用第二种方法更加灵活,它可以一次性地为控件的很多属性设定值。

如果要编程主加入引用

Imports System.Globalization

 

7.动态切换语言设置

以上的介绍都是通过IE浏览器获取语言设置,其实我们可以自己设置使用哪种语言。

1)通过在每个页面里的Page节指定
<%@ Page Culture="en-us" UICulture="en-us" %>
如上所设,该页将使用en-us的语言设置。

注意:这只是个概要式写法,实际的页面中的Page一般都包含更多的属性。

2)通过在Web.Config里的globalization节指定
<system.web>
    <globalization culture ="auto" uiCulture ="auto"/>
</system.web>
3)当然还有一种就是通过编程动态切换语言设置啦,这也是实际项目中经常用到的方式

打开Default.aspx,切换到[源]视图,添加如下代码
        <a href="?currentculture=zh-cn">中文(中国)</a>
        &nbsp;
        <a href="?currentculture=en-us">English(USA)</a>
打开Default.aspx.cs,添加如下代码
     String s;

    protected override void InitializeCulture()
     {
         s = Request.QueryString["currentculture"];
        if (!String.IsNullOrEmpty(s))
         {
            //UICulture - 决定了采用哪一种本地化资源,也就是使用哪种语言
            //Culture - 决定各种数据类型是如何组织,如数字与日期
             Thread.CurrentThread.CurrentUICulture = new CultureInfo(s);
             Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(s);
         }
     }
记得添上这个引用
using System.Threading;

 

多种语言方案

web.config 中设置为自动
<system.web>
    <globalization culture ="auto" uiCulture ="auto"/>
</system.web>

登录时增加session("lang")的选择

在页面中加入preint事件,在其实判断

    Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
        Thread.CurrentThread.CurrentUICulture = New CultureInfo("en-us")
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-us")

        Button1.Text = Resources.Resource.path
    End Sub


方案2 重写InitializeCulture(

    Protected Overrides Sub InitializeCulture()

        Page.UICulture = "zh-cn"

        'InitializeCulture()
    End Sub


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)  
  {  
  if(e.Row.RowType == DataControlRowType.DataRow)  
  {  
         DataRow dr = (DataRow)e.Row.DataItem;  
         if(dr["Name"]== "Peter")  
         {  
               e.Row.Style["backgroundColor"]= "#F7F6F3";  
         }  
   
  }  
  }

 


文本文件写操作

        Dim sw As StreamWriter
        sw = File.CreateText(Server.MapPath(".") & "/1.html")
        sw.WriteLine("<html><body>hellow</body></html>")
        sw.Close()
        sw.Dispose()

 

 


 

发布了49 篇原创文章 · 获赞 1 · 访问量 6万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章