服务器简单搜索功能

时间:2016-12-04 18:05:17

标签: c# asp.net sql-server

感谢您抽出宝贵时间阅读我的帖子!这是非常赞赏。我是ASP.Net的新手,我正在尝试创建一个简单的页面,我可以搜索SQL Server数据库中的表。

这是asp.net代码:

<%@ Page Language="C#"  MasterPageFile="~/PantryAdmin.Master" AutoEventWireup="true" CodeFile="ProductSearch.aspx.cs" Inherits="RampantryF.ProductSearch" %>


  <asp:Content runat="server" ContentPlaceHolderID="ContentPlaceHolder1">

    <div>



        <asp:TextBox ID="SearchBox" runat="server"></asp:TextBox>



        <asp:Button ID="Button1" runat="server" Text="Search" OnClick="Button1_Click" />

    <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False">
    </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:fall16_g8ConnectionString %>" SelectCommand="SELECT * FROM [PRODUCT]"></asp:SqlDataSource>
</div>

        </asp:Content>   

我的代码背后:

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

namespace RampantryF
{
    public partial class ProductSearch : System.Web.UI.Page
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["fall16_g8ConnectionString"].ConnectionString);
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string find = "select * from PRODUCT where(PRODUCT_NAME like '%' + @PRODUCT_NAME + '%')";
            SqlCommand comm = new SqlCommand(find, con);
            comm.Parameters.Add("@PRODUCT_NAME", SqlDbType.NVarChar).Value = SearchBox.Text;

            con.Open();
            comm.ExecuteNonQuery();
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = comm;
            DataSet ds = new DataSet();
            da.Fill(ds, "PRODUCT_NAME");

            GridView2.DataSource = ds;
            GridView2.DataBind();

            con.Close();
        }
    }
}

页面加载正常,但是当您按下“搜索”键时按钮它只刷新页面而不是将数据加载到gridview中。我想知道发生了什么以及如何解决它。

如果需要任何其他信息,请与我们联系。我很乐意提供它。

谢谢!

1 个答案:

答案 0 :(得分:0)

对您的代码进行了少量更改,请检查指定的参数如何分配

 protected void Button1_Click(object sender, EventArgs e)
{
    string find = "select * from PRODUCT where PRODUCT_NAME like @PRODUCT_NAME";
    SqlCommand comm = new SqlCommand(find, con);
    comm.Parameters.Add("@PRODUCT_NAME", SqlDbType.NVarChar).Value = "%"+ SearchBox.Text + "%";
    SqlDataAdapter da = new SqlDataAdapter(comm);
    DataSet ds = new DataSet();
    da.Fill(ds, "PRODUCT_NAME");
    GridView2.DataSource = ds.Tables[0];
    GridView2.DataBind();

}

同样在aspx页面中将AutoGenerateColumns更改为true。

<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="true">
    </asp:GridView>