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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章