这两天,做一个模拟的电话簿(某IT经理给我的作业),包括2张表,一个是分组表tb_Group(GroupID, GroupName),一个是联系人表tb_Person(PersonName,GroupID,CellPhone,Remark),实现联系人的增删改查,看似很简单的东西,也学到了挺多东西。按照要求,把添加,查找和编辑的功能,放在了不同的页面:(其实,我认为完全没有必要分为这么多页面,每个页面都有字段的输入框,可以复合利用嘛,但是,要求这样做,就这么做吧!)

1. 添加页面:对姓名,分组,手机号进行不为空的验证,对手机号进行格式验证,添加成功后,跳转到查找页面。

2. 查找页面:对姓名,手机号,备注进行组合模糊查找,分组查找,所有字段组合查找。对记录进行排序,和分页。对记录进行删除。点击编辑时,跳转到编辑页面,并把该行的值传递过去。

3. 编辑页面:和添加页面完全一样,只是数据是从查找页面反射过来的,同样对编辑后的数据进行验证。 保存编辑后,跳转到查找页面。

 

在过程中遇到的障碍:

1. 绑定分组的DropDownList的Items,页面载入时,怎样来显示为不选择,怎样对未选择分组进行验证。方法是在tb_Group中加入一条空记录(GroupID=1,GroupName为空),载入时显示该空记录,如果状态为选中该空记录,提示选择分组。验证控件为:



< 
  asp:comparevalidator  
  id 
  ="GroupNull" 
   runat 
  ="server" 
   Display 
  ="Dynamic" 
   ControlToValidate 
  ="DdlGroup" 
   Type 
  ="String" 
   ValueToCompare 
  ="1" 
   Operator 
  ="NotEqual" 
   ErrorMessage 
  ="请选择分组" 
    
  ></ 
  asp:comparevalidator 
  >



2. 手机号码的验证:本来想把验证手机号格式和手机号不为空一起验证,用RegularExpressionValidator控件验证手机号格式,但是,没能同时验证不为空,只得又添加一个RequiredFieldValidator来验证不为空。

3. 点击GridView中的“编辑”时,把数据传递到编辑页面,但是不知道Group的值怎么传递过去。朋友给解决的:

查找页代码:



Find 
  
    //行编辑事件
    protected void GrdPerson_RowEditing(object sender, GridViewEditEventArgs e)
    {
         GrdPerson.EditIndex = e.NewEditIndex;
        string PersonName= GrdPerson.Rows[e.NewEditIndex].Cells[0].Text.ToString();
        string GroupName = GrdPerson.Rows[e.NewEditIndex].Cells[1].Text.ToString();     
        string CellPhone = GrdPerson.Rows[e.NewEditIndex].Cells[2].Text.ToString();
        string Remark = GrdPerson.Rows[e.NewEditIndex].Cells[3].Text.ToString();
        string s_url;
        //多值页面传递
        s_url = "EditPerson.aspx?PersonName=" + PersonName + "&GroupName=" + GroupName+"&CellPhone="+CellPhone+"&Remark="+Remark;
        Response.Redirect(s_url);
    }


编辑页代码:


Edit 
  
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGroup();
        }
        
        TxtName.Text = Request.QueryString["PersonName"];
        TxtCell.Text = Request.QueryString["CellPhone"];
        TxtRemark.Text = Request.QueryString["Remark"];
        string GroupID = Request.QueryString["PersonName"];
        DdlGroup.SelectedIndex=DdlGroup.Items.IndexOf(DdlGroup.Items.FindByValue(GroupID));        
        string GroupName = Request.QueryString["GroupName"];
        string value = dalGroup.SelectByGroupName(GroupName);
        DdlGroup.SelectedValue = value;

    }


 

4. 排序:即在Gridview的标题栏,点击某字段,按该字段的顺序和逆序排列。另外写篇日志吧!

 

程序主要代码:

Utility类:



Code 
  
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

/// <summary>
/// Utility 的摘要说明
/// </summary>
public class Utility
{
    static string connString = ConfigurationManager.AppSettings["connString"].ToString();
    public Utility()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }

    /// <summary>
    /// 执行SQL语句,返回DataTable
    /// </summary>
    /// <param name="strSql"></param>
    /// <param name="name"></param>
    /// <returns></returns>
    public DataTable ExcuteSql(string strSql, string name)
    {
        DataTable dt = new DataTable();
        SqlConnection con = new SqlConnection(connString);
        SqlDataAdapter adp = new SqlDataAdapter(strSql, con);
        try
        {
            con.Open();
            adp.Fill(dt);
            return dt;
        }
        finally
        {
            con.Close();
            adp.Dispose();
        }
    }

    /// <summary>
    /// 执行SQL语句,返回执行状态
    /// </summary>
    /// <param name="strSql"></param>
    /// <returns></returns>
    public bool ExcuteSql(string strSql)
    {
        bool ret ;
        SqlConnection con = new SqlConnection(connString);
        SqlCommand cmd = new SqlCommand(strSql, con);
        try
        {
            con.Open();
            int i = cmd.ExecuteNonQuery();
            if (i > 0)
                return ret = true;
            else
                return ret = false;
        }
        finally
        {
            con.Close();
        }
    }
}

dropDownList的Items动态绑定:



 

public 
   DataTable SelectAll()
    {
         
  string 
   strSql  
  = 
    
  @" 
  select * from tb_Group order by GroupId 
  " 
  ;
        DataTable dt  
  = 
   utility.ExcuteSql(strSql,  
  " 
  tb_Group 
  " 
  );
         
  return 
   dt;
    }

 



Code 
  
 //绑定下拉项
    private void BindGroup()
    {
        DdlGroup.DataSource = dalGroup.SelectAll();
        DdlGroup.DataTextField = "GroupName";
        DdlGroup.DataValueField = "GroupId";
        DdlGroup.DataBind();
    }


 

添加记录:



Code 
  
    //添加
    public bool Insert(string name, string groupid, string cellphone, string remark)
    {
        string strSql = @"insert tb_Person(PersonName,groupid,cellphone,remark) values('{0}','{1}','{2}','{3}')";
        strSql = string.Format(strSql, new string[] { name, groupid, cellphone, remark });
        return utility.ExcuteSql(strSql);
    }

 


Code 
  
 protected void BtnAdd_Click(object sender, EventArgs e)
    {
        string name = TxtName.Text.Trim().ToString();
        string group = DdlGroup.SelectedValue.ToString();
        string cellPhone = TxtCell.Text.Trim().ToString();
        string remark = TxtRemark.Text.Trim().ToString();


        if (dalPerson.Insert(name, group, cellPhone, remark))
        {
            Response.Redirect("FindPerson.aspx");
        }
        else
        {
            Response.Write("<script>alert('添加失败,请重新添加!')</script>");
        }
        
        
    }


 

 

查找记录:



Code 
  
    //条件查询
    public DataTable SelectByCondition(string byCondition)
    {
        string strSql = @"select PersonName,groupname,cellphone,remark from tb_Person a left join tb_Group b on a.groupid=b.groupid where 1=1 {0}";
        strSql = string.Format(strSql, byCondition);
        DataTable dt = utility.ExcuteSql(strSql, "tb_Person");
        return dt;
    }


 

 

Code 
  
 protected void BtnFind_Click(object sender, EventArgs e)
    {
        string name = TxtName.Text.Trim().ToString();
        string group = DdlGroup.SelectedValue.ToString();
        string cellphone = TxtCell.Text.Trim().ToString();
        string remark = TxtRemark.Text.Trim().ToString();

        StringBuilder sbCondition = new StringBuilder();

        if (name.Length > 0)
        {
            sbCondition.Append("and PersonName like '%" + name + "%'");
        }
        if (DdlGroup.SelectedValue != "1")
        {
            sbCondition.Append("and b.groupid = '" + group + "'");
        }
        if (cellphone.Length > 0)
        {
            sbCondition.Append("and cellphone like '%" + cellphone + "%'");
        }
        if (remark.Length > 0)
        {
            sbCondition.Append("and remark like '%" + remark + "%'");
        }
        string bycondition = sbCondition.ToString();
        DataTable dt = dalPerson.SelectByCondition(bycondition);
        GrdPerson.DataSource = dt;
        GrdPerson.DataBind();
    }


 

删除记录:


Code 
  
    //删除记录
    public bool delete(string PersonName)
    {
        string strSql = @"delete tb_Person  where PersonName='{0}'";
        strSql = string.Format(strSql, new string[] { PersonName });
        return utility.ExcuteSql(strSql);
    }

Code 
  
//行删除事件
    protected void GrdPerson_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string PersonName = GrdPerson.Rows[e.RowIndex].Cells[0].Text;
        dalPerson.delete(PersonName);
        BindAll();
    }


 

编辑记录:

点击编辑,跳转到编辑页面,并把该行的值传递过去。



Code 
  
    //行编辑事件
    protected void GrdPerson_RowEditing(object sender, GridViewEditEventArgs e)
    {
         GrdPerson.EditIndex = e.NewEditIndex;
        string PersonName= GrdPerson.Rows[e.NewEditIndex].Cells[0].Text.ToString();
        string GroupName = GrdPerson.Rows[e.NewEditIndex].Cells[1].Text.ToString();     
        string CellPhone = GrdPerson.Rows[e.NewEditIndex].Cells[2].Text.ToString();
        string Remark = GrdPerson.Rows[e.NewEditIndex].Cells[3].Text.ToString();
        string s_url;
        //多值页面传递
        s_url = "EditPerson.aspx?PersonName=" + PersonName + "&GroupName=" + GroupName+"&CellPhone="+CellPhone+"&Remark="+Remark;
        Response.Redirect(s_url);
    }


     编辑页面的代码:



Code 
  
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGroup();
        }
        
        TxtName.Text = Request.QueryString["PersonName"];
        TxtCell.Text = Request.QueryString["CellPhone"];
        TxtRemark.Text = Request.QueryString["Remark"];
        string GroupID = Request.QueryString["PersonName"];
        DdlGroup.SelectedIndex=DdlGroup.Items.IndexOf(DdlGroup.Items.FindByValue(GroupID));        
        string GroupName = Request.QueryString["GroupName"];
        string value = dalGroup.SelectByGroupName(GroupName);
        DdlGroup.SelectedValue = value;

    }


 


Code 
  
//编辑
    protected void BtnEdit_Click(object sender, EventArgs e)
    {
        string name = TxtName.Text.Trim().ToString();
        string group = DdlGroup.SelectedValue.ToString();
        string cellPhone = TxtCell.Text.Trim().ToString();
        string Remark = TxtRemark.Text.Trim().ToString();
        if (dalPerson.Update(name, group, cellPhone, Remark))
        {

            Response.Redirect("FindPerson.aspx");
        }
        else
        {
            Response.Write("<script>alert('更新失败,请重新操作!')</script>");
        }

    }