C#WebForm实现增删改查

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

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

其次,和上文一样,创建数据库操作类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;

/// <summary>
///db 的摘要说明
/// </summary>
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();
        }
    }
}

第三步:排版test.Aspx页面



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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="css/demo.css" type="text/css" rel="stylesheet">
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table id="Table1" cellspacing="0" cellpadding="0" border="0" style="width: 100%">
            <tr>
                <td valign="middle" nowrap align="left">
                    <span class="spannone">查询条件:</span>
                    <asp:TextBox ID="txt_cx" runat="server" Width="202px" CssClass="tbnone"></asp:TextBox>
                    <asp:Button ID="bt_cx" runat="server" CssClass="btnone" Text="查询" OnClick="bt_cx_Click">
                    </asp:Button>
                </td>
                <td valign="middle" nowrap align="right">
                    <asp:Button ID="bt_add" runat="server" CssClass="btnone" Text="增加" OnClick="bt_add_Click">
                    </asp:Button>
                    <asp:Button ID="bt_del" runat="server" CssClass="btnone" Text="删除" OnClick="bt_del_Click">
                    </asp:Button>
                    <asp:Button ID="bt_save" runat="server" CssClass="btnone" Text="保存" OnClick="bt_save_Click">
                    </asp:Button>
                </td>
            </tr>
        </table>
        <hr class="hr1">
        <asp:GridView ID="gv_1" runat="server" CssClass="dgtable" AutoGenerateColumns="False"
            AllowPaging="True" DataKeyNames="dbid" PageSize="5" OnPageIndexChanging="gv_1_PageIndexChanging" onselectedindexchanging="gv_1_SelectedIndexChanging">
            <HeaderStyle Wrap="False" CssClass="dghead" ForeColor="White" />
            <RowStyle Wrap="False" CssClass="dgitem" />
            <FooterStyle BackColor="White" ForeColor="#000066" />
            <Columns>
                <asp:TemplateField SortExpression="xm1" HeaderText="姓名">
                    <ItemTemplate>
                    <asp:Label ID="xm1" runat="server" Text='<%# Eval("xm1")%>' CssClass="tdleft"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField SortExpression="xm2" HeaderText="性别">
                    <ItemTemplate>
                        <asp:Label ID="xm2" runat="server" Text='<%# Eval("xm2")%>' CssClass="tdleft"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField SortExpression="xm3" HeaderText="电话">
                    <ItemTemplate>
                        <asp:Label ID="xm3" runat="server" Text='<%# Eval("xm3")%>' CssClass="tdleft"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <HeaderStyle Wrap="False" Width="15px" />
                    <ItemTemplate>
                        <asp:ImageButton ID="ImageButton1" runat="server" CausesValidation="False" CommandName="select"
                            ImageUrl="edit.gif" ToolTip="编辑" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <AlternatingRowStyle CssClass="dgalteritem" />
        </asp:GridView>
    </div>
 
    <table border="0" cellpadding="0" cellspacing="0" bordercolor="#111111" width="100%" class="px12">
        <tr>
            <td style="height: 10px">
            </td>
        </tr>
		<tr height="30">
			<td width="3%" background="topbg.jpg" align=center><IMG height="16" src="right.GIF"></td>
			<td background="topbg.jpg" width="80"><b>信息编辑</b></td>
			<TD background="topbg.jpg" align="right">
			</TD>
		</tr>
	 </table>
	 <div class="divhid">
	      <asp:textbox id="dbid" runat="server" cssclass="tbinput"></asp:textbox>	            	             
	</div>            
    <div>
        <table>    
            <tr>
                <td style="height: 3px" colspan="2">
                </td>
            </tr>
            <tr>
                <td width="25%" height="20" class="tdlabel">
                    姓名:
                </td>
                <td width="75%">
                    <asp:TextBox ID="xm1" runat="server" CssClass="tbinput"></asp:TextBox>
                </td>
                <td>
                </td>
            </tr>
            <tr>
                <td width="25%" height="20" class="tdlabel">
                    性别:
                </td>
                <td width="75%" height="20">
                    <asp:RadioButtonList ID="xm2" runat="server" CssClass="tbinput" RepeatColumns="2"
                        Width="100px">
                        <asp:ListItem Value="男" Selected="True">男</asp:ListItem>
                        <asp:ListItem Value="女">女</asp:ListItem>
                    </asp:RadioButtonList>
                </td>
                <td>
                </td>
            </tr>
            <tr>
                <td width="25%" height="20" class="tdlabel">
                    电话:
                </td>
                <td width="75%">
                    <asp:TextBox ID="xm3" runat="server" CssClass="tbinput"></asp:TextBox>
                </td>
                <td>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

第四步:配置好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;	
}

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

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());
    }
}

总结

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

  • 7
    点赞
  • 67
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值