简体   繁体   English

使用 Search 显示 GridView 中的记录

[英]Using Search to display records in GridView

I'm trying to search for records in my VSC database through the SQL connection string and display records based on the user's input.我正在尝试通过 SQL 连接字符串在我的 VSC 数据库中搜索记录,并根据用户的输入显示记录。 I seem to be hitting a wall with the tutorials I've found on how to get things running.我找到的关于如何让事情运行的教程似乎碰壁了。 At the moment this code is throwing an exception with sda.Fill(dt);目前,这段代码使用sda.Fill(dt); . . Could anyone point out where I'm going wrong?谁能指出我哪里出错了?

 protected void GoButton_Click(object sender, EventArgs e) { SqlCommand command; SqlConnection conn; String selectTable; conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); conn.Open(); selectTable = "SELECT * from Activity where ActivityName LIKE '%'+@ActivityName+'%'"; command = new SqlCommand(selectTable, conn); command.Parameters.AddWithValue("ActivityName", SearchBox); DataTable dt = new DataTable(); SqlDataAdapter sda = new SqlDataAdapter(command); sda.Fill(dt); GridView1.DataSource = dt; GridView1.DataBind(); command.Dispose(); conn.Close();

You missed .Text on SearchBox that's why it won't come and i revamped your code use code always like this您错过了SearchBox上的.Text这就是它不会出现的原因,我修改了您的代码使用代码总是这样

protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection();
        SqlCommand cmd = new SqlCommand();
        try
        {
            var constring = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            DataTable dt = new DataTable();

            using (con = new SqlConnection(constring))
            {
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }

                using (cmd = new SqlCommand("SELECT * from Activity where ActivityName LIKE '%'+@ActivityName+'%'", con))
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.AddWithValue("ActivityName", SearchBox.Text);
                    using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                    {
                        sda.Fill(dt);

                        GridView1.DataSource = dt;
                        GridView1.DataBind();
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            cmd.Dispose();
            con.Close();
        }
    }

Ok, the approach to adding filter (1 or many) can be attacked like this:好的,添加过滤器(1个或多个)的方法可以像这样受到攻击:

markup:标记:

        <h4>Filters</h4>
        <div style="float:left">
            <asp:Label ID="Label1" runat="server" Text="Search Hotel"></asp:Label>
            <br />
             <asp:TextBox ID="txtHotel" runat="server"></asp:TextBox>
        </div>

        <div style="float:left;margin-left:20px">
            <asp:Label ID="Label2" runat="server" Text="Search City"></asp:Label>
            <br />
            <asp:TextBox ID="txtCity" runat="server"></asp:TextBox>
        </div>

        <div style="float:left;margin-left:20px">
            <asp:Label ID="Label3" runat="server" Text="Must Have Description"></asp:Label>
            <br />
            <asp:CheckBox ID="chkDescripiton" runat="server"  />
        </div>

        <div style="float:left;margin-left:20px">
            <asp:Label ID="Label4" runat="server" Text="Show only Active Hotels"></asp:Label>
            <br />
            <asp:CheckBox ID="chkActiveOnly" runat="server"  />
        </div>

        <div style="float:left;margin-left:20px">
            <asp:Button ID="cmdSearch" runat="server" Text="Search" CssClass="btn" OnClick="cmdSearch_Click"/>
        </div>

        <div style="float:left;margin-left:20px">
            <asp:Button ID="cmdClear" runat="server" Text="Clear Fitler" CssClass="btn" OnClick="cmdClear_Click"/>
        </div>



        <div style="clear:both">
                <%-- this starts new line for grid --%>
        </div>

        <asp:GridView ID="GridView1" runat="server" 
            AutoGenerateColumns="False" DataKeyNames="ID" 
            CssClass="table" Width="60%" ShowHeaderWhenEmpty="true">
            <Columns>
                <asp:BoundField DataField="FirstName" HeaderText="FirstName" />
                <asp:BoundField DataField="LastName" HeaderText="LastName"  />
                <asp:BoundField DataField="HotelName" HeaderText="HotelName" />
                <asp:BoundField DataField="City" HeaderText="City" />
                <asp:BoundField DataField="Province" HeaderText="Province" />
                <asp:BoundField DataField="Description" HeaderText="Description"  />
            </Columns>
        </asp:GridView>
    </div>

Now code to load grid is this:现在加载网格的代码是这样的:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack == false)
        {
            SqlCommand cmdSQL = new
                SqlCommand("SELECT * FROM tblHotels WHERE ID = 0");

            LoadGrid(cmdSQL);
        }
    }

    public void LoadGrid(SqlCommand cmdSQL)
    {
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
        {
            using (cmdSQL)
            {
                cmdSQL.Connection = conn;
                DataTable rstData = new DataTable();
                conn.Open();
                rstData.Load(cmdSQL.ExecuteReader());
                GridView1.DataSource = rstData;
                GridView1.DataBind();
            }
        }
    }

And now we have this:现在我们有了这个:

在此处输入图像描述

Now, you might just have ONE filter - one text box.现在,您可能只有一个过滤器 - 一个文本框。 But here is the code and approach for several filters like I have in above.但这里是我上面的几个过滤器的代码和方法。

So, follow this template and design pattern:因此,请遵循此模板和设计模式:

    protected void cmdSearch_Click(object sender, EventArgs e)
    {
        string strSQL = "SELECT * FROM tblHotels ";
        string strORDER = " ORDER BY HotelName";
        string strFilter = "";

        SqlCommand cmdSQL = new SqlCommand();

        if (txtHotel.Text != "")
        {
            strFilter = "(HotelName like @HotelName + '%')";
            cmdSQL.Parameters.Add("@HotelName", SqlDbType.NVarChar).Value = txtHotel.Text;
        }

        if (txtCity.Text != "")
        {
            if (strFilter != "") strFilter += " AND ";
            strFilter += "(City Like @City + '%'";
            cmdSQL.Parameters.Add("@City", SqlDbType.NVarChar).Value = txtCity.Text;
        }

        if (chkActiveOnly.Checked)
        {
            if (strFilter != "") strFilter += " AND ";
            strFilter += "(Active = 1)";
        }
        if (chkDescripiton.Checked)
        {
            if (strFilter != "") strFilter += " AND ";
            strFilter += "(Description is not null)";
        }

        if (strFilter != "") strSQL += " WHERE " + strFilter;

        strSQL += strORDER;
        cmdSQL.CommandText = strSQL;
        LoadGrid(cmdSQL);

    }

So, we can have with above 1, 2 or 9 filter options.因此,我们可以拥有以上 1、2 或 9 个过滤器选项。

And our clear filter button code还有我们清晰的过滤按钮代码

    protected void cmdClear_Click(object sender, EventArgs e)
    {
        txtCity.Text = "";
        txtHotel.Text = "";
        chkActiveOnly.Checked = false;
        chkDescripiton.Checked = false;
        SqlCommand cmdSQL = new 
            SqlCommand("SELECT * FROM tblHotels ORDER BY HotelName");
        LoadGrid(cmdSQL);
    }

So, I can for example type in K to find all hotels that start with K.因此,例如,我可以输入 K 来查找所有以 K 开头的酒店。

and we get this:我们得到了这个:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM