即日起在codingBlog上分享您的技术经验即可获得积分,积分可兑换现金哦。

C#WebForm实现增删改查

编程语言 widenstage 70℃ 0评论
本文目录
[隐藏]

        上文,我们使用pb和c#WinForm使用分别实现了增删改查,本文,我们C#WebForm技术来实现一下。首先,说明一点,WinForm和WebForm基本是一样,代码基本雷同,就是使用的控件不一样,页面排版上有点不同。数据库仍然采用sqlserver,表仍然采用table_test,字段不说了,参考前两篇文章。

1.首先,在vs中创建一个ASP.NET空网站,test

2.其次,和上文一样,创建数据库操作类db.cs

web程序,会把类db.cs放在App_code文件夹中,代码如下:

using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;

/// 
///db 的摘要说明
/// 
public class db
{

    public static string connectionstring = "server=localhost;database=db;uid=sa;pwd=password";
 public db()
 {
        //
        //TODO: 在此处添加构造函数逻辑
        //
 }

    public static SqlConnection OpenDB()
    {
        try
        {
            SqlConnection oConn = new SqlConnection(connectionstring);
            oConn.Open();

            return oConn;
        }
        catch
        {
            throw;
        }
    }

    public static void CloseDB(SqlConnection oConn)
    {
        try
        {
            oConn.Close();
        }
        catch
        {
            throw;
        }
    }

    public static DataSet Execute(string strCommandString)
    {
        try
        {
            SqlConnection oConn = OpenDB();

            DataSet oDataSet = new DataSet();
            SqlDataAdapter oDataAdapter = new SqlDataAdapter(strCommandString, oConn);
            oDataAdapter.Fill(oDataSet);

            CloseDB(oConn);

            return oDataSet;
        }
        catch
        {
            throw;
        }
    }

    public static int ExecuteNonQuery(string strCommandString)
    {
        int li_count = 0;
        SqlConnection oConn = null;
        SqlCommand oComm = null;
        try
        {
            oConn = new SqlConnection(connectionstring);
            oComm = new SqlCommand();
            oConn.Open();
            oComm.Connection = oConn;
            oComm.CommandText = strCommandString;
            li_count = oComm.ExecuteNonQuery();
            return li_count;
        }
        catch
        {
            return 0;
        }
        finally
        {
            if (oConn != null) oConn.Close();
        }
    }

    public static int ExecuteReid(string strCommandString)
    {
        int li_count = 0;
        SqlConnection oConn = null;
        SqlCommand oComm = null;
        try
        {
            oConn = new SqlConnection(connectionstring);
            oComm = new SqlCommand();
            oConn.Open();
            oComm.Connection = oConn;
            oComm.CommandText = strCommandString;
            li_count = Convert.ToInt32(oComm.ExecuteScalar().ToString());
            return li_count;
        }
        catch
        {
            return 0;
        }
        finally
        {
            if (oConn != null) oConn.Close();
        }
    }
}

3.第三步:排版test.Aspx页面




<%@ Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="test" %>




    
    


    
查询条件:

信息编辑
姓名:
性别:
电话:

4.第四步:配置好demo.css

.hr1
{
 width: 100%;
 height: 1px;
 background-color: green;
}
.btnone
{
 font-size: 9pt;
 color: black;
 font-family: 宋体, Arial;
 text-align: center;
}
.tbinput
{
 border-right: buttonface 1px solid;
 border-top: buttonface 1px solid;
 font-size: 9pt;
 border-left: buttonface 1px solid;
 width: 100%;
 color: black;
 border-bottom: buttonface 1px solid;
 font-style: normal;
 font-family: 宋体, Arial;
 font-variant: normal;
 text-decoration: none;
 border-color: #93BEE2 #93BEE2 #93BEE2 #93BEE2 ; 
        border: 1px #93BEE2 solid;  
}
.spanerror
{
 font-size: 9pt;
 color: red;
 font-family: 宋体, Arial;
}
.spannone
{
 font-size: 9pt;
 font-family: 宋体, Arial;
}
.tdright
{
 font-size: 9pt;
 vertical-align: baseline;
 overflow: hidden;
 color: black;
 font-family: 宋体, Arial;
 position: static;
 height: 14px;
 width:100%;
 text-align:right;
 text-decoration: none;
}
.tdcenter
{
 font-size: 9pt;
 vertical-align: baseline;
 overflow: hidden;
 color: black;
 width:100%;
 font-family: 宋体, Arial;
 position: static;
 height: 14px;
 text-align:center;
 text-decoration: none;
}
.tdleft
{
 font-size: 9pt;
 vertical-align: baseline;
 overflow: hidden;
 width:100%;
 color: black;
 font-family: 宋体, Arial;
 position: static;
 height: 14px;
 text-align:left;
 text-decoration: none;
}

.dgtable
{
 width: 100%; 
}
.dgitem
{
 font-size: 9pt;
 color: black;
 font-family: 宋体;
 height: 25px;
}
.dghead
{
 font-weight: normal;
 font-size: 9pt;
 overflow: visible;
 font-family: 宋体;
 height: 25px;
 background-color: #5D7B9D; 
 text-align: center;
 text-decoration: none;
}

.dgfoot
{
 font-weight: bold;
 font-size: 10pt;
 overflow: hidden;
 color: black;
 font-family: 宋体;
 height: 25px;
 text-align: right;
 text-decoration: none;
}
.divhid
{
 display: none;
}
.px12 {
 font-family: "Verdana", "宋体", Arial;
 font-size: 12px;
 text-decoration: none;
 color: #000000;
}
.tdlabel
{
 font-size: 9pt;
 font-family: 宋体, Arial;
 background-color:Silver; 
 text-align:right; 
}

5.第五步:编写代码实现增删改查

using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class test : System.Web.UI.Page
{
    
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bindgv("");
        }
    }

    private void bindgv(string as_where)
    {
        string ls_sql = "select dbid,xm1,xm2,xm3 from table_test "+as_where+" order by dbid";    
        DataSet ds = db.Execute(ls_sql);
        
        gv_1.DataSource = ds.Tables[0].DefaultView;
        try
        {
            gv_1.DataBind();

            int rc = gv_1.Rows.Count;
            for (int i = 0; i < rc; i++)
            {
                GridViewRow e = gv_1.Rows[i];
                if (e.RowType == DataControlRowType.DataRow)
                {
                    e.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#bbCCFF'");
                    e.Attributes.Add("onmouseout", "this.style.backgroundColor=c;");
                    e.Attributes["style"] = "Cursor:hand";
                }
            }

            if (gv_1.Rows.Count == 0)
            {
                ds.Tables[0].Clear();
                ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
                gv_1.DataSource = ds;
                gv_1.DataBind();
                int columnCount = gv_1.Rows[0].Cells.Count;
                gv_1.Rows[0].Cells.Clear();
                gv_1.Rows[0].Cells.Add(new TableCell());
                gv_1.Rows[0].Cells[0].ColumnSpan = columnCount;
                gv_1.Rows[0].Cells[0].Text = "没有任何记录..";
                gv_1.RowStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;
            }
        }
        catch
        {
        }
    }

    protected void bt_add_Click(object sender, EventArgs e)
    {
        dbid.Text = "";
        xm1.Text = "";
        xm3.Text = "";

    }
    protected void bt_del_Click(object sender, EventArgs e)
    {
        if (dbid.Text.Equals(""))
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('请首先选择要删除的记录!');", true);
        }
        else
        {
            string ls_sql = "delete from table_test where dbid=" + dbid.Text;
            db.ExecuteNonQuery(ls_sql);
            bindgv("");
            dbid.Text = "";
            xm1.Text = "";
            xm3.Text = "";
            Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('删除成功!');", true);
        }
    }

    protected void bt_save_Click(object sender, EventArgs e)
    {
        // *** 将信息更新到数据库 
        if (dbid.Text == "")
        {
            string ls_sql = "INSERT INTO table_test ( xm1,xm2,xm3 )  VALUES (  @@xm1, @@xm2, @@xm3 ); SELECT dbid FROM table_test WHERE (dbid = @@IDENTITY)";
            ls_sql = ls_sql.Replace("@@xm1", "'" + xm1.Text.ToString() + "'");
            ls_sql = ls_sql.Replace("@@xm2", "'" + xm2.SelectedValue + "'");
            ls_sql = ls_sql.Replace("@@xm3", "'" + xm3.Text.ToString() + "'");

            int li_ret1 = db.ExecuteReid(ls_sql);
            if (li_ret1 > 0)
            {
                dbid.Text = li_ret1.ToString();
            }
            else
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('保存失败!');", true);
                return;
            }
        }
        else
        {
            string ls_sql = "update table_test set xm1=@@xm1,xm2=@@xm2,xm3=@@xm3  where dbid = " + dbid.Text;
            ls_sql = ls_sql.Replace("@@xm1", "'" + xm1.Text.ToString() + "'");
            ls_sql = ls_sql.Replace("@@xm2", "'" + xm2.SelectedValue+ "'");
            ls_sql = ls_sql.Replace("@@xm3", "'" + xm3.Text.ToString() + "'");
            db.ExecuteNonQuery(ls_sql);
        }
        bindgv("");
        Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('保存成功!');", true);
    }

    protected void bt_cx_Click(object sender, EventArgs e)
    {
         bindgv(getwhere());         
    }

    private string getwhere()
    {
        string ls_where = "";
        if (txt_cx.Text.Equals(""))
        {
            ls_where = "";
        }
        else
        {
            ls_where = " where (xm1 like '%" + txt_cx.Text.ToString() + "%') or (xm2 like '%" + txt_cx.Text.ToString() + "%') or (xm3 like '%" + txt_cx.Text.ToString() + "%')";
        }
        return ls_where;
    }

    protected void gv_1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {
        dbid.Text = gv_1.DataKeys[e.NewSelectedIndex].Value.ToString();

        // *** 注意模板模式,空格也算一个控件,所以从第二个控件取值
        xm1.Text = ((Label)(gv_1.Rows[e.NewSelectedIndex].Cells[0].Controls[1])).Text;
        xm2.SelectedValue = ((Label)(gv_1.Rows[e.NewSelectedIndex].Cells[1].Controls[1])).Text;       
        xm3.Text = ((Label)(gv_1.Rows[e.NewSelectedIndex].Cells[2].Controls[1])).Text;
        
    }
    protected void gv_1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gv_1.PageIndex = e.NewPageIndex;
        bindgv(getwhere());
    }
}

6.总结

         通过上面的代码,我们可以看出winform和webform编程基本没有什么区别,只是数据库控件一个用的是DataGridView,一个用的Gridview,不同之处就是这两个控件使用上一点不同。使用webfrom编写web程序,页面排版需要用些时间,代码基本一样。web毕竟和桌面应用程序有点不同,需要了解前端的HTML、CSS、JavaScript这些知识。WebForm开发web应用还是很容易的,不到1000行代码就搞定了增删改查。

转载请注明:CodingBlog » C#WebForm实现增删改查

喜欢 (0)or分享 (0)
发表我的评论
取消评论

*

表情