模块代码锦集

如项目是采用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.会员登陆模块
2.验证注册用户是否存在
3.新用户注册
4.图片上传
5.两种添加数据到dropdownlist的方法
6.发送邮件

7.datalist嵌套

 

1.会员登陆模块
TextBox:TxtUser 用户名  TxtPwd 密码
Label:LblError 错误提示
//存储过程:
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
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
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#代码:
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 代码
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
//存储过程:
/*
作者:dezai
用途:新进会员的增加注册,同时注册与其相关的企业名录
日期:2006-3-1
*/


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 @user_Id=@@identity

Commit tran
return
ERROR:
    set @User_Id = 0
    rollback tran
GO

//c#代码:
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代码
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
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代码

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

5.两种添加数据到dropdownlist的方法
方法一:
public void initdrop(int flag)
  {
   string CS=Application.Get("myConnectionString").ToString();
   string myQuery="";
   
   if(flag==1)myQuery= "SELECT * from links order by myorder ";
   
   myConnection = new OleDbConnection(CS);
   // Open the connection.
   myConnection.Open();

   myCommand= new OleDbCommand(myQuery);
   // Assign the connection property.
   myCommand.Connection  = myConnection;
   objDataReader=myCommand.ExecuteReader();
    

   while(objDataReader.Read())
   {
    DropDownList1.Items.Add(new ListItem(objDataReader["title"].ToString(),objDataReader["friendlinks"].ToString()));
   }
  
   if(objDataReader!=null)objDataReader.Close();
   if(myConnection!=null)myConnection.Close();

  }


方法二:
1?string?sql="select?*?from?newsclass?order?by?orderid?desc";?
2?
3?oledbconnection?conn=new?oledbconnection();?
4?conn.connectionstring=connectionstring;?
5?conn.open();?
6?
7?dataset?ds=new?dataset();?
8?oledbdataadapter?da=new?oledbdataadapter(sql,conn);?
9?da.fill(ds,"classtable");?
10?
11?//将数据添加到?dropdownlist?
12?ddl.datasource=ds;?
13?ddl.datatextfield?=?"classname";?
14?ddl.datavaluefield?=?"classid";?
15?ddl.databind();?
16?
17?ds.dispose();?
18?conn.close;?
19?conn.dispose();?
20?


6.发送邮件
MailMessage newmail = new MailMessage();
newmail.From="*********@citiz.net";
newmail.BodyFormat=MailFormat.Html;
newmail.Priority = MailPriority.High;
newmail.To="partsorder@sohu.com";
newmail.Subject=subject;
newmail.Body=body;
newmail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate","1"); //basic authentication
newmail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "username");//set your username here
newmail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "password");//set your password here
MailAttachment attachment = new MailAttachment(saveName);
newmail.Attachments.Add(attachment);
SmtpMail.SmtpServer="www.citiz.net";
SmtpMail.Send(newmail);

 7.datalist嵌套

 xxx.aspx

< asp:datalist id = " DataListpro1 "  runat = " server " >
                                    
< ItemTemplate >
                                        
< table cellSpacing = " 0 "  cellPadding = " 0 "  width = " 100 "  border = " 0 " >
                                            
< tr >
                                                
< td >& nbsp; </ td >
                                            
</ tr >
                                        
</ table >
                                        
< table cellSpacing = " 1 "  cellPadding = " 3 "  width = " 768 "  bgColor = " #cb6397 "  border = " 0 " >
                                            
< tr >
                                                
< td align = " left "  bgColor = " #ffffff " ><% # DataBinder.Eval(Container.DataItem,  " Class1_1_Name " , " {0} " %></ td >
                                            
</ tr >
                                            
< tr >
                                                
< td vAlign = " top "  align = " left "  width = " 760 "  bgColor = " #ffffff " >
                                                    
< asp:datalist id = " DataListpro2 "  runat = " server "  OnItemDataBound = " DataListpro2_ItemDataBound " >
                                                        
< itemtemplate >
                                                            
< table width = " 100% "  border = " 0 "  cellpadding = " 0 "  cellspacing = " 2 " >
                                                                
< tr >
                                                                    
< td width = " 114 "  align = " center "  bgcolor = " #eeeeee "  height = " 20 " ><% # DataBinder.Eval(Container.DataItem,  " Class1_2_Name " , " {0} " %></ td >
                                                                    
< td colspan = " 3 "  align = " left "  valign = " top "  bgcolor = " #ffffff " >
                                                                        
< asp:DataList ID = " DataListpro3 "  runat = " server "  RepeatColumns = " 3 " >
                                                                            
< ItemTemplate >
                                                                                
< table width = " 206 "  border = " 0 "  cellspacing = " 1 "  cellpadding = " 2 " >
                                                                                    
< tr >
                                                                                        
< td bgcolor = " #efefef "  height = " 20 " >& nbsp; < class = " a4 "  href = ' <%# DataBinder.Eval(Container.DataItem, "id","productDetail.aspx?id={0}") %> ' ><% # DataBinder.Eval(Container.DataItem,  " name " , " {0} " %></ a ></ td >
                                                                                    
</ tr >
                                                                                
</ table >
                                                                            
</ ItemTemplate >
                                                                        
</ asp:DataList >
                                                                    
</ td >
                                                                
</ tr >
                                                            
</ table >
                                                        
</ itemtemplate >
                                                    
</ asp:datalist ></ td >
                                            
</ tr >
                                        
</ table >
                                    
</ ItemTemplate >
                                
</ asp:datalist >

xxx.aspx.cs

void  bindleft()
        
{
        
            
string CS=Application.Get("myConnectionString").ToString();
            
string myQuery="";    
                
            myQuery 
= "SELECT Class1_1_Name,id  from [class1_1]  order by id desc";


                

            OleDbConnection myConnection 
= new OleDbConnection(CS);
            myConnection.Open();
                
            OleDbDataAdapter objDataAdapter
=new OleDbDataAdapter(myQuery,myConnection);
            
            DataSet ds 
= new DataSet();
            objDataAdapter.Fill(ds,
"product");
                
        

                
            
this.DataListpro1.DataSource=ds.Tables["product"].DefaultView;
            
this.DataListpro1.DataBind();


            ds.Clear();
            
if(myConnection!=null)myConnection.Close();
        }

        
public   void  DataListpro1_ItemDataBound( object  sender, System.Web.UI.WebControls.DataListItemEventArgs e)
        
{
            DataList myda;
            myda
=(DataList)(e.Item.FindControl("DataListpro2"));
            
        

            
string temp=Convert.ToString(DataBinder.Eval(e.Item.DataItem, "Class1_1_Name" ));
            
string myid=Convert.ToString(DataBinder.Eval(e.Item.DataItem, "id" ));
            
//
            
            
string CS=Application.Get("myConnectionString").ToString();
            
string myQuery="";
            
            
if(temp.Trim()=="")
                
return;
            
else
                myQuery
= "SELECT [Class1_2_Name],[id],[Class1_1_Name] from [Class1_2] where [Class1_1_Name]='"+temp+"'  order by id desc";
        
    
            
            OleDbConnection myConnection 
= new OleDbConnection(CS);
            myConnection.Open();
            
            OleDbDataAdapter objDataAdapter
=new OleDbDataAdapter(myQuery,myConnection);
        
            DataSet ds 
= new DataSet();
            
            
            
            objDataAdapter.Fill(ds,
"productpro2");
            
            DataTable dt
=ds.Tables["productpro2"]; 
            
            
//dt.Columns.Add("myid",typeof(string)); 
            
        
            
//foreach (DataRow myRow in dt.Rows)
            
//{
            
//    myRow["myid"]=myid;
                
            
//}

            
if(myConnection!=null)myConnection.Close();
            myda.DataSource
=dt.DefaultView;

            
            myda.DataBind();
        }

        
public   void  DataListpro2_ItemDataBound( object  sender, System.Web.UI.WebControls.DataListItemEventArgs e)
        
{
            DataList myda;
            myda
=(DataList)(e.Item.FindControl("DataListpro3"));
            
        

            
string temp=Convert.ToString(DataBinder.Eval(e.Item.DataItem, "Class1_2_Name" ));
            
string temp1=Convert.ToString(DataBinder.Eval(e.Item.DataItem, "Class1_1_Name" ));
            
//
            string CS=Application.Get("myConnectionString").ToString();
            
string myQuery="";
            
        
            myQuery
= "SELECT * from [product] where Class1='"+ temp1 +"'  and Class2='"+temp+"' and myvisible='是'   order by outdate desc";
        
            
            OleDbConnection myConnection 
= new OleDbConnection(CS);
            myConnection.Open();
            
            OleDbDataAdapter objDataAdapter
=new OleDbDataAdapter(myQuery,myConnection);
        
            DataSet ds 
= new DataSet();
            objDataAdapter.Fill(ds,
"productpro3");
            
            
if(myConnection!=null)myConnection.Close();

            myda.DataSource
=ds.Tables["productpro3"].DefaultView;
            myda.DataBind();
        }

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值