ASP.NET | 从零到一实战分析对后台数据库增加数据、模糊查找、精确查找并展示

新建:

新建数据库mydb.mdf、添加表:

更新数据库; 右击数据库,选择属性,复制连接字符串;(这里之前做过了,就简单点过不做细节。点击这里可以看详细步骤截图参考_《用ASP.NET做一个简单的数据流动展示》) 到web.config:

注意相对路径|DataDirectory|......

 <connectionStrings>
    <add name="DefaultConnection"
      connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=aspnet-manages-c703b6e8-d35a-4082-aadf-60f5ad784980;AttachDbFilename=|DataDirectory|\aspnet-manages-c703b6e8-d35a-4082-aadf-60f5ad784980.mdf;Integrated Security=SSPI"
      providerName="System.Data.SqlClient"/>
    <add name ="connstr" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\mydb.mdf;Integrated Security=True"/>
  </connectionStrings>

删除,重建default窗口文件; 设计,插入表:

设计: 顶行合并; 输入文字; 顶行内容居中; 二列添加textbox;

改id: Name_TextBox Cate_TextBox Price_TextBox Time_TextBox Address_TextBox Contact_TextBox

合并末行,加个button,修改text,加个GridView:

新建一个common类: 右击App_Code:

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

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

/// <summary>
/// common 的摘要说明
/// </summary>
public class common
{
    public common()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }

    public static SqlConnection myconn()
    {
        string connstr = ConfigurationManager.ConnectionStrings["connstr"].ToString();
        SqlConnection myconn = new SqlConnection(connstr);
        return myconn;
    }
}

回来default窗口,双击设计界面里边入库按钮,开始编写逻辑:

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

using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;

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

    protected void Button1_Click(object sender, EventArgs e)
    {
        insertDB();
        displayDB();
    }

    //套路:1.connstr-sqlconn-open打开数据库
    //2.cmdstr-sqlcmd(cmdstr,conn)-cmd.ex执行数据库操作,或者其他;
    //3.关闭
    protected void insertDB()
    {
        SqlConnection myconn = common.myconn();
        myconn.Open();

        double Pricevalue = Convert.ToDouble(Price_TextBox.Text.Trim());
        string cmdstr = @"insert into Tproduct(Fname,Fcategory,Fprice,Ftime,Faddress,Fcontactname)
                values('" + Name_TextBox.Text + "' , '" + Cate_TextBox.Text + "' , " + Pricevalue + " , '" + Time_TextBox.Text + "' , '" + Address_TextBox.Text + "' , '" + Contact_TextBox.Text + "' )";
        SqlCommand mycmd = new SqlCommand(cmdstr,myconn);
        mycmd.ExecuteNonQuery();

        mycmd.Dispose();
        myconn.Close();
        Response.Write("<script>alert('入库成功')</script>");
    }

    protected void displayDB()
    {
        string connstr = ConfigurationManager.ConnectionStrings["connstr"].ToString();
        SqlConnection myconn = new SqlConnection(connstr);
        myconn.Open();

        string cmdstr = @"select * from Tproduct";

        SqlDataAdapter myda = new SqlDataAdapter(cmdstr,myconn);//查出

        DataSet myds = new DataSet();//转型
        myda.Fill(myds);

        GridView1.DataSource = myds;//赋能控件
        GridView1.DataKeyNames = new string[] { "id" };
        GridView1.DataBind();

        myda.Dispose();
        myds.Dispose();
        myconn.Close();
    }
}

如图,插入和展示就完成了:

现在增加查找功能: 末行配置多三个控件:

分别添加点击逻辑即可:

    protected void jqFind_Button_Click(object sender, EventArgs e)
    {
        SqlConnection myconn = common.myconn();
        myconn.Open();

        string cmdstr = "select *from Tproduct where Fname='" + Find_TextBox.Text.Trim() + "'";//单引号双引号括起来
        SqlDataAdapter myda = new SqlDataAdapter(cmdstr, myconn);

        DataSet myds = new DataSet();
        myda.Fill(myds);

        int rowNum = myds.Tables[0].Rows.Count;
        int columnNum = myds.Tables[0].Columns.Count;
        DataTable usingTable = myds.Tables[0];

        if (rowNum == 0)
        {
            usingTable = usingTable.Clone();//克隆
            usingTable.Rows.Add(usingTable.NewRow());//加新行
            GridView1.DataSource = usingTable;//赋能

            GridView1.Rows[0].Cells.Clear();//清空
            GridView1.Rows[0].Cells.Add(new TableCell());//加新格
            GridView1.Rows[0].Cells[0].Text = "无相关记录";//text
            GridView1.Rows[0].Cells[0].ColumnSpan = columnNum;
        }
        else
        {
            GridView1.DataSource = myds;
            GridView1.DataBind();
        }

        myds.Dispose();
        myda.Dispose();
        myconn.Close();
    }

    protected void mhFind_Button_Click(object sender, EventArgs e)
    {
        SqlConnection myconn = common.myconn();
        myconn.Open();
        
        string cmdstr = "select *from Tproduct where Fname like '%"+Find_TextBox.Text.Trim()+"%'";

        SqlDataAdapter myda = new SqlDataAdapter(cmdstr, myconn);

        DataSet myds = new DataSet();
        myda.Fill(myds);

        GridView1.DataSource = myds;
        GridView1.DataBind();

        myds.Dispose();
        myda.Dispose();
        myconn.Close();
    }

效果:

精确查找

模糊查找

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券