2015-112 ado.net2

CRUD:create read update delete

七. 数据绑定数据列的转换

  在gridview中添加<OnRowDataBound="GridView1_RowDataBound">

  在cs中

  protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)//判断是数据行
            {
                string cate = e.Row.Cells[2].Text;
                switch (cate)
                {
                    case "1":
                        e.Row.Cells[2].Text = "网页前端";
                        break;
                    case "2":
                        e.Row.Cells[2].Text = "数据库";
                        break;
                    case "3":
                        e.Row.Cells[2].Text = ".NET";
                        break;
                    case "4":
                        e.Row.Cells[2].Text = "PS";
                        break;
                    default:
                        break;
                }
                DateTime cdate = Convert.ToDateTime(e.Row.Cells[3].Text); //将字符串转为日期类型
                e.Row.Cells[3].Text = cdate.ToLongDateString().ToString();  //转换成其他格式的日期
            }
        }

八.数据增删

   1.添加数据

     string txet = Txtcmain.Text.Trim();
     string strsql = string.Format("insert into Rnews(Title,Text,CreatTime) values('{0}','{1}','{2}')", title, txet, DateTime.Now.ToString());
     using(con=new SqlConnection(strCon))
     {
           con.Open();
           using (cmd = new SqlCommand(strsql, con))
          {
                cmd.ExecuteNonQuery();
          }
           BindRnews();
           Response.Write("<script>alert('添加成功')</script>");
      }

  2.删除数据

     int id = Convert.ToInt32(Txtdeleid.Text.Trim());            

     string str = string.Format("select count(*) from Rnews where newsId={0}", id);            

     using(con=new SqlConnection(strCon))             {                

          con.Open();                

          using(cmd=new SqlCommand(str,con))                 {                    

                    if(Convert.ToInt32(cmd.ExecuteScalar().ToString())==0)                     {                        

                             Response.Write("<script>alert('id不存在')</script>");                   

                      }                   

                    else                     {                        

                             string strsql = string.Format("delete Rnews where newsId={0}", id);                        

                             using (cmd = new SqlCommand(strsql, con))                         {                            

                                      cmd.ExecuteNonQuery();//对数据库进行增加,删除,修改                        

                             }                       

                             BindRnews();                        

                             Response.Write("<script>alert('删除成功')</script>");                   

                      }                

            }

      }       

  3.修改语句:update biaoming set title="" where id=1

九.绑定详细数据

9.1 在gridview中,编辑列,添加TemplateField,headertext中写上标题,返回选择编辑模板,在templatefield上添加<ItemTemplate>

 <asp:TemplateField HeaderText="详情">                    

<ItemTemplate>

   <a href='newsmain.aspx?newsId=<%#Eval("newsId") %>'>详细</a></ItemTemplate>                       

   <%--  GET传值 <%#Eval("newsId") %>固定写法,绑定这一行的id--%>

  </asp:TemplateField>

9.2 在新页面中,将光标放到字段上,重构,选择封装字段,得到属性,获取内容

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace yishen1
{
public partial class newsmain : System.Web.UI.Page
{
/// <summary>
/// 连接数据库
/// </summary>
string strCon = ConfigurationManager.ConnectionStrings["qie_yishen"].ToString();
SqlConnection con;
SqlCommand cmd;
SqlDataReader read;
/// <summary>
/// 获取newsid值
/// </summary>
private int _newsid;

public int Newsid
{
get {
try
{
_newsid = Request.QueryString["newsId"] == null ? 0 : Convert.ToInt32(Request.QueryString["newsId"].ToString());
}
catch
{
_newsid = 0;
}
return _newsid; }
set { _newsid = value; }
}
public string Getnews()
{
StringBuilder sb = new StringBuilder();
using (con = new SqlConnection(strCon))
{
con.Open();
if (Newsid > 0)
{
string strsql = string.Format("select newsId,Title,Text,CreatTime from Rnews where newsId={0}", Newsid);
cmd=new SqlCommand(strsql,con);
using (read = cmd.ExecuteReader())
{
if (read.Read())
{
sb.Append("<table>");
sb.Append(string.Format("<tr><td>新闻id:</td><td>{0}</td></tr>", Newsid));
sb.Append(string.Format("<tr><td>标题:</td><td>{0}</td></tr>", read["Title"].ToString()));
sb.Append(string.Format("<tr><td>内容:</td><td>{0}</td></tr>", read["Text"].ToString()));
sb.Append(string.Format("<tr><td>创建时间:</td><td>{0}</td></tr>", read["CreatTime"].ToString()));
sb.Append("</table>");
}
else
{
sb.Append("暂无数据");
}

}
}
else
{
sb.Append("暂无数据");
}
}
return sb.ToString();
}
protected void Page_Load(object sender, EventArgs e)
{

}
}
}

9.3前台调用后台

在div中写上    <%=Getnews() %>      //在此不代表注释

9.4 post传值

     默认的是get传值,所以要设置传值方式 method=post,action=“.....”设置传到的页面

    <form id="form1" action="PostBehindPage.aspx" method="post">
    <input type="text" name="username" />
    <input type="password" name="pwd" />
    <input type="submit" />   //代表提交按钮
     </form>

    注:在post传值中,必须要设置name。

9.5 在新页面的cs中,添加代码

    protected void Page_Load(object sender, EventArgs e)
    {
          string username = Request.Form["username"].ToString();  //获取用户名
          string pwd = Request.Form["pwd"].ToString();                  //获取密码
          Response.Write(username + " " + pwd);  //显示
}

posted @ 2015-11-17 17:51  以深  阅读(150)  评论(0编辑  收藏  举报
TOP