简体   繁体   中英

Query System - How to search and display data?

I need help on how to make the search function works based on the checkbox being ticked and display the results in the result page. Basically, I have the database ready, the connection between the database and the web service has been made and the form is ready as well.

Below is my SearchPage.aspx.cs (the main page)

    public partial class SearchPage : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {


    }

    protected void searchbtn_Click(object sender, EventArgs e)
    {
        string searchbox = inputtxt.Text;            

        if (searchbox.Length == 0)
        {
            errormsglbl.ForeColor = Color.Red;
            errormsglbl.Text = "Please fill in the search box below";
        }

        else
        {

            string query = "SELECT * from item_list ";

            //fix this ?input = inputtxt.txt, title = title.......
            //if all are untick change all to true
            if (titlelbl.Checked)
                query += "WHERE Title like '%" + inputtxt.Text + "%'";
            else if (authorlbl.Checked)
                query += "WHERE Author = '%" + inputtxt.Text + "%'";
            else if (publisherlbl.Checked)
                query += "WHERE Publisher = '%" + inputtxt.Text + "%'";

            string connectionString =
                "Provider=Microsoft.Jet.OLEDB.4.0;" +
                "Data Source='C:\\Users\\Mister\\Documents\\Visual Studio
2012\\Project\\LibraryQuerySystem\\QuerySystem\\App_data\\items.mdb';";

            string queryString = "INSERT INTO item_list VALUES ('" + Title + "', '" +
Author + "', '" + Publisher + "')";

            using (OleDbConnection connection = new OleDbConnection(connectionString)) 
            {
                connection.Open();
                OleDbConnection commandText = queryString;
                //OleDbCommand command = new OleDbCommand(queryString, connection);
                OleDbDataReader reader = commandText.ExecuteReader();

                while (reader.Read())
                {
                    result+="Title = "+ reader["Title"].ToString()+"  ";
                    result+="Author= "+ reader["Author"].ToString()+"  ";
                    result+="Publisher= "+ reader["Publisher"].ToString()+"  ";
                    result+"<br/>";//dd new line
                }
                reader.Close();
                connection.Close();

                //set Session here
                Session["Results"]=ResultPage;
                //now redirect
                Response.Redirect("~/ResultPage.aspx");
            }

        }

    }

    protected void addbtn_Click(object sender, EventArgs e)
    {
        Response.Redirect("/AddPage.aspx");
    }

    protected void authorlbl_CheckedChanged(object sender, EventArgs e)
    {

    }

    protected void publisherlbl_CheckedChanged(object sender, EventArgs e)
    {

    }

    protected void inputtxt_TextChanged(object sender, EventArgs e)
    {

    }
}

this is my ResultPage.aspx.cs

public partial class ResultPage : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {

        results.InnerHtml = Session["Results"].ToString();

    }

    protected void backbtn_Click(object sender, EventArgs e)
    {
        Response.Redirect("/SearchPage.aspx");
    }

}

and my DatabaseService.asmx.cs

/// <summary>
/// Summary description for Databases
/// </summary>
[WebService(Namespace = "http://tempuri.org/", Name="Library Database",
Description="This is Database of the Library")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment
the following line. 
// [System.Web.Script.Services.ScriptService]
public class Databases : System.Web.Services.WebService
{        
    [WebMethod]
    public string CheckConnection()
    {
            string result = "";
            string connectionString =
                "Provider=Microsoft.Jet.OLEDB.4.0;" +
                "Data Source='C:\\Users\\Mister\\Documents\\Visual Studio
2012\\Projects\\LibraryQuerySystem\\QuerySystem\\App_data\\items.mdb';";

        using (OleDbConnection connection = new OleDbConnection(connectionString))
        {
            try
            {
                connection.Open();
                result = "Connection Success";
            }
            catch (Exception e)
            {
                result = "Error in Connection";
            }
        }
        return result;
    }

    [WebMethod]
    public string addBook(String title, String author, String publisher)
    {
        string result = "";

        string connectionString =
            "Provider=Microsoft.Jet.OLEDB.4.0;" +
            "Data Source='C:\\Users\\Mister\\Documents\\Visual Studio 2012\\Project
\\LibraryQuerySystem\\QuerySystem\\App_data\\items.mdb';";

        string queryString = "INSERT INTO item_list VALUES ('" + title + "', '" +
author + "', '" + publisher + "')";

        using (OleDbConnection connection = new OleDbConnection(connectionString))
        {
            connection.Open();
            OleDbCommand command = connection.CreateCommand();
            command.CommandText = queryString;
            // OleDbCommand command = new OleDbCommand(queryString, connection);

            command.ExecuteNonQuery();

            connection.Close();

            result += "Item added";
        }
        return result;
    }




    [WebMethod]
    public string[] searchBook(string input, Boolean title, Boolean author, Boolean
publisher)
    {

        string connectionString =
            "Provider=Microsoft.Jet.OLEDB.4.0;" +
            "Data Source='C:\\Users\\Mister\\Documents\\Visual Studio 2012\\Project
\\LibraryQuerySystem\\QuerySystem\\App_data\\items.mdb';";

        string queryString = "SELECT * FROM item_list WHERE Title = '" + input + "' OR
Author = '" + input + "' OR Publisher = '" + input + "'";

        string lists = "";

        string[] book = new string[3];

        using (OleDbConnection connection = new OleDbConnection(connectionString))
        {
            connection.Open();
            OleDbCommand command = connection.CreateCommand();
            command.CommandText = queryString;

            OleDbDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
            }

            if (title == true)
            {
                queryString = "SELECT * FROM item_list WHERE Title like '%" + input +
"%'";

                OleDbCommand comd2 = new OleDbCommand(queryString, connection);
                comd2.CommandText = queryString;
                OleDbDataReader read2 = comd2.ExecuteReader();

                while (read2.Read())
                {
                    lists += "<p> title = " + read2[0].ToString() + "<br> author = " +
read2[1].ToString() + "<br> publisher = " + read2[2].ToString() + "</p>";
                }
            }

            if (author == true)
            {
                queryString = "SELECT * FROM item_list WHERE Author LIKE '%" + input +
"%'";

                OleDbCommand comd3 = new OleDbCommand(queryString, connection);
                comd3.CommandText = queryString;
                OleDbDataReader read3 = comd3.ExecuteReader();

                while (read3.Read())
                {
                    lists += "<p> title = " + read3[0].ToString() + "<br> author = " +
read3[1].ToString() + "<br> publisher = " + read3[2].ToString() + "</p>";
                }
            }

            if (publisher == true)
            {
                queryString = "SELECT * FROM item_list WHERE Publisher LIKE '%" + input +
"%'";

                OleDbCommand comd4 = new OleDbCommand(queryString, connection);
                comd4.CommandText = queryString;
                OleDbDataReader read4 = comd4.ExecuteReader();

                while (read4.Read())
                {
                    lists += "<p> title = " + read4[0].ToString() + "<br> author = " +
read4[1].ToString() + "<br> publisher = " + read4[2].ToString() + "</p>";
                }
            }

            reader.Close();
            connection.Close();
        }
        return book;
    }
}

The problem I have is in the Search Page, which is in these lines:

2.The name 'Author' does not exist in the current context 3.The name 'Publisher' does not exist in the current context

            string queryString = "INSERT INTO item_list VALUES ('" + Title + "', '" +
Author + "', '" + Publisher + "')";

4.Cannot implicitly convert type 'string' to 'System.Data.OleDbConnection' 5.'System.Data.OleDbConnection' does not contain a definition for "ExecuteReader' and no extension method 'ExecuteReader' accepting first argument of type 'System.Data.OleDb.OleDbConnection' could be found

            using (OleDbConnection connection = new OleDbConnection(connectionString)) 
            {
                connection.Open();
                OleDbConnection commandText = queryString;
                //OleDbCommand command = new OleDbCommand(queryString, connection);
                OleDbDataReader reader = commandText.ExecuteReader();

6.The name 'result' does not exist in the current context 9.Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement

while (reader.Read())
                {
                    result+="Title = " reader["Title"].ToString()+"  ";
                    result+="Author= " reader["Author"].ToString()+"  ";
                    result+="Publisher= " reader["Publisher"].ToString()+"  ";
                    result+"<br/>";//dd new line
                }

Please help me find the solution.

From my understanding:

1.you have an Input TextBox to read the input String basically it is an search string.
2.you have 3 CheckBox Controls.
They are :

a.Author
b.Publisher
c.Title

3.based on the user selection the query has to be fired with given input string.

Example : if user wants to search Title he has to enter some title on input TextBox and select/Check the Title CheckBox to find the Books with given Title .
same for Publisher and Author

Try This Code: (Sample Code)

Design Code:

<asp:CheckBox ID="chkTitle" runat="server" Text="Title"/>
    <asp:CheckBox ID="chkAuthor" runat="server" Text="Author" />
    <asp:CheckBox ID="chkPublisher" runat="server" Text="Publisher" />
      <asp:TextBox ID="txtInput" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click1" />

Code Behind:

    protected void Button1_Click1(object sender, EventArgs e)
        {

            String query = "SELECT * FROM item_list ";

            if(chkTitle.Checked)
            query+="WHERE Title like '%" + txtInput.Text + "%'";
            else if(chkAuthor.Checked)
            query+="WHERE Author = '%" + txtInput.Text + "%'";
            else if(chkPublisher.Checked)
            query+="WHERE Publisher = '%" + txtInput.Text + "%'";

            //now execute command with  query variable to perform search 
string connectionString =
            "Provider=Microsoft.Jet.OLEDB.4.0;" +
            "Data Source='C:\\Users\\Mister\\Documents\\Visual Studio 2012\\Project
\\LibraryQuerySystem\\QuerySystem\\App_data\\items.mdb';";

        string queryString = "INSERT INTO item_list VALUES ('" + title + "', '" +
author + "', '" + publisher + "')";

        using (OleDbConnection connection = new OleDbConnection(connectionString))
        {
            connection.Open();
            OleDbCommand command = connection.CreateCommand();
            command.CommandText = queryString;
            // OleDbCommand command = new OleDbCommand(queryString, connection);
            OleDbDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
              result+="Title = "+ reader["Title"].ToString()+"  ";
              result+="Author= "+ reader["Author"].ToString()+"  ";
              result+="Publisher= "+ reader["Publisher"].ToString()+"  ";
              result+"<br/>";//dd new line
            }
            connection.Close();

           //set Session here
           Session["Results"]=result;
           //now redirect
           Response.Redirect("~/SearchPage.aspx");
        }

        }

Now SearchPage.aspx page should contain following code:

Design code of SearchPage.aspx

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div id="results" runat="server">

    </div>
    </form>
</body>
</html>

Code Behind of SearchPage page

Page_Load should add the results to the div element

public partial class SearchPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        results.InnerHtml = Session["Results"].ToString();
    }
}

Solution 3: you need concatenation operator + for combining string

Try This:

while (reader.Read())
                {
                    result+="Title = "+ reader["Title"].ToString()+"  ";
                    result+="Author= "+ reader["Author"].ToString()+"  ";
                    result+="Publisher= "+ reader["Publisher"].ToString()+"  ";
                    result+"<br/>";//dd new line
                }

Note: as this is a sample Code I hope that you can change your code as per your reuirement, if you need something else please let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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