• asp.net两层架构常用


    web.config:
    <appSettings>
    <add key="DBConnectionString" value="server=(local);database=SztcBusiness;uid=sa;pwd="/>
    </appSettings>
    GridView页面代码:
     <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="537px" AllowPaging="True" OnPageIndexChanging="GridView1_PageIndexChanging1" OnRowDeleting="GridView1_RowDeleting" DataKeyNames="NewsID">
                                         <Columns>
                                                <asp:BoundField DataField="NewsID" HeaderText="ID" ReadOnly="True" SortExpression="NewsID"  />
                                                <asp:BoundField DataField="UserName" HeaderText="用户名" SortExpression="UserName"   />
                                                <asp:BoundField DataField="Type" HeaderText="买/卖" ReadOnly="True" SortExpression="Type" />
                                                <asp:BoundField DataField="ProductName" HeaderText="商品名" SortExpression="ProductName" />
                                                <asp:BoundField DataField="ProductType" HeaderText="商品类型" SortExpression="ProductType" />
                                                <asp:BoundField DataField="Description" HeaderText="商品描述" SortExpression="Description"  Visible="False" />
                                                <asp:BoundField DataField="Price" HeaderText="商品价格" SortExpression="Price"  />
                                                <asp:BoundField DataField="PublishTime" HeaderText="发布时间" SortExpression="PublishTime"  Visible="False"   />
                                                <asp:BoundField DataField="Expire" HeaderText="有效时间" SortExpression="Expire"  Visible="False" />
                                             
                                                <asp:HyperLinkField DataNavigateUrlFields="NewsID" DataNavigateUrlFormatString="Edit.aspx?NewsID={0}"
                                                    HeaderText="编辑" Text="编辑" />
                                             <asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
                                            </Columns>
                                        </asp:GridView>
    GridView页面数据绑定代码:
    string sqlStr = "Select * from News where UserName='" + Session["UserName"].ToString() + "'order by PublishTime desc";
     DataSet ds = new DataSet();
     SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["DBConnectionString"]);
     try
            { 
    conn.Open();
                SqlCommand cmd = new SqlCommand(sqlStr, conn);
                SqlDataReader sdr = cmd.ExecuteReader();
                if (sdr.Read())
                {  sdr.Close();
                    SqlDataAdapter da = new SqlDataAdapter(sqlStr, conn);
                    da.Fill(ds);
                    GridView1.DataSource = ds.Tables[0].DefaultView;
                    GridView1.DataBind();
                    Label2.Text = "查询结果(第" + (GridView1.PageIndex + 1).ToString() + "页,共" + GridView1.PageCount.ToString() + "页)";
                }
                else
                {
                    Label2.Text = "你还未发布任何信息!";
               
                }
        }
            catch (Exception ex)
            {
                Response.Write("数据库错误,错误原因:" + ex.Message);

            }
            finally
            {
                
    conn.Close();
            }
    GridView分页PageIndexChanging事件代码:
     
    GridView1.PageIndex = e.NewPageIndex;
     GridView1Bind();
    GridView删除事件代码:
    int NewsID = int.Parse(GridView1.DataKeys[e.RowIndex].Values[0].ToString()); //取出要删除记录的主键值
    string SqlStr = "delete from News where NewsID=" + NewsID ;
    try
           {
    SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["DBConnectionString"]);
               conn.Open();
                SqlCommand comm = new SqlCommand(SqlStr, conn);
                comm.ExecuteNonQuery();          //执行删除
                conn.Close();
               GridView1Bind();
                Label2.Text = "删除记录成功!";
            }
            catch (Exception ex)
            {
                Response.Write("数据库错误,错误原因:" + ex.Message);
              
            }
    实现记录详细信息代码:
    string sqlStr = "Select * from News where NewsID=" + Convert.ToInt32(Request["NewsID"].ToString());
    SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["DBConnectionString"]);
     try
                {
              
    conn.Open();
                SqlCommand cmd = new SqlCommand(sqlStr, conn);
                SqlDataReader sdr = cmd.ExecuteReader();
                if (sdr.Read())
                {
                    DropDownList1.SelectedValue = sdr["ProductType"].ToString();
                    TextBoxName.Text = sdr["ProductName"].ToString();
                    TextBoxDescription.Text = sdr["Description"].ToString();
                    TextBoxPrice.Text = sdr["Price"].ToString();
                    DropDownList2.SelectedValue = sdr["Expire"].ToString();
                    DropDownList3.SelectedValue = sdr["Type"].ToString();
             
      }
                else
                {
                    Response.Write("数据库错误,没查询到该商品信息!");
                }
          
     }
            catch (Exception ex)
            {
                Response.Write("数据库错误,错误原因:" + ex.Message);

            }
            finally
            {
           
    conn.Close();
         
      }
    更新代码:
    string SqlStr = "update News set ProductName='" + TextBoxName.Text + "',Price='" + TextBoxPrice.Text + "',Description='" + TextBoxDescription.Text + "',PublishTime='" + DateTime.Now + "',ProductType='" + DropDownList1.SelectedItem.Text + "',Expire=" + int.Parse(DropDownList2.SelectedItem.Text) + ",Type='" + DropDownList3.SelectedItem.Text + "' where NewsID=" + Convert.ToInt32(Request["NewsID"].ToString());
            SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["DBConnectionString"]);
            try
            {

                conn.Open();
                SqlCommand cmd = new SqlCommand(SqlStr, conn);
                int flag = cmd.ExecuteNonQuery();
                if (flag > 0)
                {
                    Label2.Text = "成功修商品信息信息!";
                }
                else
                {
                    Label2.Text = "数据库错误";

                }
            }
            catch (Exception ex)                                //异常处理
            {
                Response.Write("数据库错误,错误原因:" + ex.Message);

            }
            finally
            {
           
    conn.Close();
            }
    验证用户是否存在方法:
     
    private int userNameValidate()
      {
    SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["DBConnectionString"]);//创建连接数据库对象
    SqlCommand selectCmd = new SqlCommand("select * from Users where UserName='" + TextBoxUserName.Text.Trim() + "'", conn); //创建操作数据库对象
     int i = 0;
            try
            {
                conn.Open();   //打开连接
                SqlDataReader sdr = selectCmd.ExecuteReader();//从数据库读取记录
                if (sdr.Read())
                {
                    i = 1;
                    Label1.Text = "对不起,已经存在该用户!";
                }
             
            }
            catch (System.Exception ee)
            {
                Response.Write("<script language=javascript>alert('" + ee.Message.ToString() + "')</script>");
            }
            finally
            {
                conn.Close();
            }
            return i;
        }
    注册代码:
    protected void ButtonRegister_Click(object sender, EventArgs e)
        {
            int i = userNameValidate();
            if (i == 0)
            {
                SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["DBConnectionString"]);//创建连接数据库对象
                SqlCommand insertCmd = new SqlCommand("insert into Users values(@UserName,@UserPwd,@Sex,@Email,@RealName,@Phone,@MobilePhone,@QQ,@Address)", conn);
              
    nsertCmd.Parameters.Add("@UserName", SqlDbType.VarChar, 50); // 为Command对象添加参数
                insertCmd.Parameters.Add("@UserPwd", SqlDbType.VarChar,50);
                insertCmd.Parameters.Add("@Sex", SqlDbType.VarChar, 50);
                insertCmd.Parameters.Add("@Email", SqlDbType.VarChar, 50);
                insertCmd.Parameters.Add("@RealName", SqlDbType.VarChar, 50);
                insertCmd.Parameters.Add("@Phone", SqlDbType.VarChar, 50);
                insertCmd.Parameters.Add("@MobilePhone", SqlDbType.VarChar, 50);
                insertCmd.Parameters.Add("@QQ", SqlDbType.VarChar, 50);
                insertCmd.Parameters.Add("@Address", SqlDbType.VarChar, 50);


                insertCmd.Parameters["@UserName"].Value = TextBoxUserName.Text;    //给参数赋值
                insertCmd.Parameters["@UserPwd"].Value = TextBoxUserPwd.Text;
                insertCmd.Parameters["@Sex"].Value = RadioButtonListSex.SelectedItem.Text;
                insertCmd.Parameters["@Email"].Value = TextBoxEmail.Text;
                insertCmd.Parameters["@RealName"].Value = TextBoxRealName.Text;
                insertCmd.Parameters["@Phone"].Value = TextBoxPhone.Text;
                insertCmd.Parameters["@MobilePhone"].Value = TextBoxMobilePhone.Text;
                insertCmd.Parameters["@QQ"].Value = TextBoxQQ.Text;
                insertCmd.Parameters["@Address"].Value = TextBoxAddress.Text;

                try
                {
                    conn.Open();      //打开连接
                    int flag = insertCmd.ExecuteNonQuery();  //执行插入
                    if (flag > 0)
                    {
                        Response.Write("<script language=javascript>alert('成功完成注册!')</script>");
                    }
                    else
                    {
                        Response.Write("<script language=javascript>alert('注册失败!请检查输入是否符合要求')</script>");
                    }
                    Response.Redirect("login.aspx");
                }
                catch (System.Exception ee)
                {
                    Response.Write("<script language=javascript>alert('" + ee.Message.ToString() + "')</script>");
                }
                finally
                {
                    conn.Close();        //关闭连接       
                }
                  }
        }
    实现年、月、日下拉列表代码:
     private ArrayList alDay;
     private void InitData()
        {
       alDay = new ArrayList();
             for (int i = 1; i <= 30; i++)
                alDay.Add(i.ToString());
         DropDownList2.DataSource = alDay;
            DropDownList2.DataBind();
         }
    修改密码代码:
     protected void ButtonPublish_Click(object sender, EventArgs e)
        {
    SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["DBConnectionString"]);
            SqlCommand selectCmd = new SqlCommand("select * from Users where UserName='" + Session["UserName"].ToString() + "' and UserPwd='" + txtOldPwd.Text.Trim() + "'", conn);
            try
            {
                conn.Open();
                SqlDataReader sdr = selectCmd.ExecuteReader();
                if (sdr.Read())
                {
                    sdr.Close();
                    SqlCommand updateCmd = new SqlCommand("update  Users set UserPwd='" + txtNewPwd.Text.Trim() + "' where UserName='" + Session["UserName"].ToString() + "'", conn);
                    int i = updateCmd.ExecuteNonQuery();
                    if (i > 0)
                    {
                        Label2.Text = "成功修改密码!";
                        
                    }
                    else
                    {
                        Label2.Text = "修改密码失败!";
                    }
                }
                else
                {
                    Label2.Text = "您输入的密码错误,检查后重新输入!";
                }
            }
            catch (System.Exception ee)
            {
                Response.Write("<script language=javascript>alert('" + ee.Message.ToString() + "')</script>");
            }
            finally
            {
                conn.Close();
            }
          }

           

  • 相关阅读:
    [改善Java代码]在equals中使用getClass进行类型判断
    [改善Java代码]equals应该考虑null值的情景
    [改善Java代码]覆写equals方法时不要识别不出自己
    [改善Java代码] 推荐使用序列化实现对象的拷贝
    [改善Java代码]避免对象的浅拷贝
    [改善Java代码]让工具类不可实例化
    [改善Java代码]建议40:匿名类的构造函数很特殊
    [改善Java代码]使用匿名类的构造函数
    [改善Java代码]使用静态内部类提高封装性
    [改善Java代码]构造函数尽量简化
  • 原文地址:https://www.cnblogs.com/yan2007/p/1560463.html
Copyright © 2020-2023  润新知