天天看點

ASP.Net學習之常用子產品整理(1)

每做完一個項目,就可以有很多的經驗跟技巧學到,感謝公司能給我這麼一個機會做這麼一個大項目,讓我從一個從剛學會一點ASP.Net的菜鳥過渡到可以用c#正常手寫相關常用子產品的一個真正的程式員,一個人做項目可以學得很多很多的東西,當然其中碰到困難也隻能靠自己一個人去解決.為了讓大家更好的學習,我把常用的子產品寫成一個個方法,希望能對大家有用.每個人都有不同的算法跟代碼習慣,而且個人水準有限,歡迎大家多多指正.

前提準備:

由于項目是采用SQL資料庫,是以我們先在web.config中設定好資料庫連接配接

<appSettings>

        <add key="Conn" value="Server=(local);Database=dezai;User ID=sa;"></add>    

  </appSettings> 

  之後在CS代碼中要注意引用

  c#

  using System.Data.Sqlclient;

  using System.Data;

  using System.Configuration;

  vb.net

  Imports System.Data.Sqlclient

  Imports System.Data

  Imports System.Configuration

以下就是常用的子產品

1.會員登陸子產品

使用者控件: 

TextBox:TxtUser 使用者名  TxtPwd 密碼

Label:LblError 錯誤提示

存儲過程:user_login

<script type="text/javascript">window.attachEvent("onload",function (){AutoSizeDIV('CODE_7643')})</script>

程式代碼: [ 複制代碼到剪貼闆 ]

CREATE procedure user_login

@user_name varchar(50),

@user_password varchar(50)

as

select * from userwhere [User_Name] = @User_Name and [User_Pwd] = @User_Password

if @@rowcount>0

begin

update  [users] set user_LoginTimes=user_LoginTimes+1 where [User_Name] = @User_Name and [User_Pwd] = @User_Password

end

GO

C#.Net

<script type="text/javascript">window.attachEvent("onload",function (){AutoSizeDIV('CODE_6266')})</script>

程式代碼: [ 複制代碼到剪貼闆 ]

Private void memberlogin()    

{

SqlConnection conndb=new SqlConnection(ConfigurationSettings.AppSettings["Conn"]);

   conndb.Open();            

SqlCommand cmdlogin = new SqlCommand("User_login",conndb);

cmdlogin.CommandType = CommandType.StoredProcedure;

cmdlogin.Parameters.Add("@user_name",TxtUser.Text.Trim());

cmdlogin.Parameters.Add("@user_password",TxtPwd.Text.Trim());

SqlDataReader reader=cmdlogin.ExecuteReader();

if(reader.Read())

{

                Session["user"]=reader["user_id"].ToString();

                Session["com"]=reader["com_id"].ToString();

                string url;

                url="../user/index.aspx?userid="+ Session["userid"] +"&comid="+ Session["comid"] +"";

                Response.Redirect(url);

            }

            else

            {

                LblError.Text ="Invalid Username or password!Please try again!";

            }

}

VB.Net

<script type="text/javascript">window.attachEvent("onload",function (){AutoSizeDIV('CODE_6635')})</script>

程式代碼: [ 複制代碼到剪貼闆 ]

Private  Sub memberlogin()

Dim conndb As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("Conn")) 

   conndb.Open()            

Dim cmdlogin As SqlCommand =  New SqlCommand("User_login",conndb) 

cmdlogin.CommandType = CommandType.StoredProcedure

cmdlogin.Parameters.Add("@user_name",TxtUser.Text.Trim())

cmdlogin.Parameters.Add("@user_password",TxtPwd.Text.Trim())

Dim reader As SqlDataReader = cmdlogin.ExecuteReader() 

If reader.Read() Then

                Session("user")=reader("user_id").ToString()

                Session("com")=reader("com_id").ToString()

                Dim url As String

                url="../user/index.aspx?userid="+ Session("userid") +"&comid="+ Session("comid") +""

                Response.Redirect(url)

Else 

                LblError.Text ="Invalid Username or password!Please try again!"

End If

End Sub

2.驗證注冊使用者是否存在

使用者控件:

TextBox: TxtMemberID

Label: LblChk

c#代碼:

<script type="text/javascript">window.attachEvent("onload",function (){AutoSizeDIV('CODE_4316')})</script>

程式代碼: [ 複制代碼到剪貼闆 ]

private bool idcheck()

        {

            SqlConnection conndb= new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);

            conndb.Open();

            string memberid=TxtMemberId.Text.Trim();

            string sql="select User from users where User_Name ='"+memberid+"'";

            SqlCommand strchk=new SqlCommand(sql,conndb);

            SqlDataReader reader=strchk.ExecuteReader();

            if(reader.Read())

            {

                LblChk.Text="Sorry! this memberid was registed,Please choose another!";

                Response.Write("<script>al&#101;rt(/"Invalid member id/");</script>");

                Response.End();

                return false;

            }

            else

            {

                return true;

            }

VB.Net 代碼

<script type="text/javascript">window.attachEvent("onload",function (){AutoSizeDIV('CODE_4415')})</script>

程式代碼: [ 複制代碼到剪貼闆 ]

private Boolean idcheck()

        {

            Dim conndb As SqlConnection =  New SqlConnection(System.Configuration.ConfigurationSettings.AppSettings("conn")) 

            conndb.Open()

            Dim memberid As String = TxtMemberId.Text.Trim() 

            Dim sql As String = "select User from users where User_Name ='"+memberid+"'" 

            Dim strchk As SqlCommand = New SqlCommand(sql,conndb) 

            Dim reader As SqlDataReader = strchk.ExecuteReader() 

            If reader.Read() Then

                LblChk.Text="Sorry! this memberid was registed,Please choose another!"

                Response.Write("<script>al&#101;rt(/"Invalid member id/");</script>")

                Response.End()

                Return False

            Else 

                Return True

            End If

3.新使用者注冊

使用者控件: 

TextBox:TxtMemberId  TxtPwd  TxtEmail 

ListBox:LstIndustry

存儲過程:Users_Insert

<script type="text/javascript">window.attachEvent("onload",function (){AutoSizeDIV('CODE_8197')})</script>

程式代碼: [ 複制代碼到剪貼闆 ]

CREATE PROCEDURE Users_Insert

@User_Id int output,

@User_Type bit,

@User_Name char(100),

@User_Pwd  char(100),

@User_Email char(100)

AS

   begin tran

    INSERT INTO [Users]

    (

    [user_type],

    [user_name],

    [user_pwd],

    [user_Email]

)

values

(

@User_Type,

@User_Name,

@User_Pwd,

@User_Email

)

if @@error<>0 goto error

set @[email protected]@identity

Commit tran

return

ERROR:

    set @User_Id = 0

    rollback tran

GO

c#代碼:

<script type="text/javascript">window.attachEvent("onload",function (){AutoSizeDIV('CODE_2112')})</script>

程式代碼: [ 複制代碼到剪貼闆 ]

private void reguser()

{

SqlConnection conndb=new SqlConnection(ConfigurationSettings.AppSettings["Conn"]);

                SqlCommand cmdinsert = new SqlCommand("Users_Insert",conndb);

                cmdinsert.CommandType=CommandType.StoredProcedure;

                int intAuthorCount;

                cmdinsert.Parameters.Add("@User_Name",TxtMemberId.Text.ToString());

                cmdinsert.Parameters.Add("@User_Pwd",TxtPwd.Text.ToString());

                cmdinsert.Parameters.Add("@User_Email",TxtEmail.Text.ToString());

                cmdinsert.Parameters.Add("@User_Industry",LstIndustry.SelectedValue);

            SqlParameter  parmReturnValue = new SqlParameter("@User_id", SqlDbType.Int);

            parmReturnValue.Direction = ParameterDirection.Output; 

            cmdinsert.Parameters.Add(parmReturnValue);

                conndb.Open();

                cmdinsert.ExecuteNonQuery();

                 intAuthorCount = (int)cmdinsert.Parameters[ "@user_id"].Value; 

                             conndb.Close();

}

VB.Net代碼

<script type="text/javascript">window.attachEvent("onload",function (){AutoSizeDIV('CODE_8085')})</script>

程式代碼: [ 複制代碼到剪貼闆 ]

Private  Sub reguser()

Dim conndb As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("Conn")) 

                Dim cmdinsert As SqlCommand =  New SqlCommand("Users_Insert",conndb) 

                cmdinsert.CommandType=CommandType.StoredProcedure

                Dim intAuthorCount As Integer

                cmdinsert.Parameters.Add("@User_Name",TxtMemberId.Text.ToString())

                cmdinsert.Parameters.Add("@User_Pwd",TxtPwd.Text.ToString())

                cmdinsert.Parameters.Add("@User_Email",TxtEmail.Text.ToString())

                cmdinsert.Parameters.Add("@User_Industry",LstIndusTry.SelectedValue)

            Dim parmReturnValue As SqlParameter =  New SqlParameter("@User_id",SqlDbType.Int) 

            parmReturnValue.Direction = ParameterDirection.Output 

            cmdinsert.Parameters.Add(parmReturnValue)

                conndb.Open()

                cmdinsert.ExecuteNonQuery()

                 intAuthorCount = CType(cmdinsert.Parameters( "@user_id").Value, Integer) 

                             conndb.Close()

End Sub

4.圖檔上傳

c#.Net

<script type="text/javascript">window.attachEvent("onload",function (){AutoSizeDIV('CODE_8515')})</script>

程式代碼: [ 複制代碼到剪貼闆 ]

private void uppic()

        {

             string mPath;

   string imagePath;

   string imageType;

   string imageName;

    DateTime dtmDate;

    dtmDate = DateTime.Now;

            if(""!=this.fileup.PostedFile.FileName)

            {

                imagePath = this.fileup.PostedFile.FileName;

                imageType = imagePath.Substring(imagePath.LastIndexOf(".")+1);

                imageName=imagePath.Substring(imagePath.LastIndexOf("//")+1);

                if("jpg" != imageType && "gif" !=imageType && "png" !=imageType && "PNG" !=imageType && "GIF" !=imageType && "JPG" !=imageType)

                {

                    Response.Write("<script language='javascript'>al&#101;rt('sorry!Please choose *.jpg or *.gif or *.png');</script>");

                    return;

                }

                else

                {

                    try

                    {

                        mPath=Server.MapPath("upfile");

                        this.fileup.PostedFile.SaveAs(mPath+"//"+"dezaistudio"+dtmDate.ToString("yyyyMMddhhmmss")+imageName);

                        this.ImageSmall.ImageUrl  = "dezaistudio"+dtmDate.ToString("yyyyMMddhhmmss")+imageName;

                        Response.Write("<script language='javascript'>al&#101;rt('upload succesful');</script>");

                        TxtPicPath.Text = this.ImageSmall.ImageUrl.ToString().Trim();

                    }

                    catch

                    {

                        Response.Write("error");

                    }

                }

            }

        }

VB.Net代碼

<script type="text/javascript">window.attachEvent("onload",function (){AutoSizeDIV('CODE_7671')})</script>

程式代碼: [ 複制代碼到剪貼闆 ]

Private  Sub uppic()

             Dim mPath As String

   Dim imagePath As String

   Dim imageType As String

   Dim imageName As String

    Dim dtmDate As DateTime

    dtmDate = DateTime.Now

            If ""<>Me.fileup.PostedFile.FileName Then

                imagePath = Me.fileup.PostedFile.FileName

                imageType = imagePath.Substring(imagePath.LastIndexOf(".")+1)

                imageName=imagePath.Substring(imagePath.LastIndexOf("//")+1)

                If "jpg" <> imageType And "gif" <>imageType And "png" <>imageType And "PNG" <>imageType And "GIF" <>imageType And "JPG" <>imageType Then

                    Response.Write("<script language='javascript'>al&#101;rt('sorry!Please choose *.jpg or *.gif or *.png');</script>")

                    Return

                Else 

                    Try

                        mPath=Server.MapPath("upfile")

                        Me.fileup.PostedFile.SaveAs(mPath+"//"+"dezaistudio"+dtmDate.ToString("yyyyMMddhhmmss")+imageName)

                        Me.ImageSmall.ImageUrl  = "dezaistudio"+dtmDate.ToString("yyyyMMddhhmmss")+imageName

                        Response.Write("<script language='javascript'>al&#101;rt('upload succesful');</script>")

                        TxtPicPath.Text = Me.ImageSmall.ImageUrl.ToString().Trim()

                    Catch

                        Response.Write("error")

                    End Try

                End If

            End If

End Sub

繼續閱讀