How to implement a basic search button in your website?
Note: in this tutorial, this is a book search function with regards to a gridview
In your webform, insert these few lines where you want the search function to be.
In your webform, insert these few lines where you want the search function to be.
<asp:TextBox ID="txtSearch" runat="server" Width="200px" ></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" Width="70px"
onclick="btnSearch_Click"/>
Next, in your code behind file, implement this method
using System.Data;
using System.Data.SqlClient;
using ProjectName.App_Code;
protected void btnSearch_Click(object sender, EventArgs e)
{
DataTable dtBookData = new DataTable();
CBookManager BooksManager = new CBookManager();
string searchName = "";
searchName = txtSearch.Text;
dtBookData = BooksManager.searchBookByName(searchName);
grdData.DataSource = dtBookData;
grdData.DataBind();
}
Next, in your class file, App_Code - CBookManager, insert this part.
public DataTable searchBookByName(String inSearch)
{
SqlDataAdapter ad = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand();
SqlConnection connection = new SqlConnection();
DataSet ds = new DataSet();
String sqlText = "SELECT Book.BookRecordId, Book.BookName FROM Book";
sqlText += " WHERE BookName LIKE @inBookName";
string connString = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
connection.ConnectionString = connString;
cmd.Connection = connection;
cmd.CommandText = sqlText;
cmd.Parameters.Add("@inBookName", SqlDbType.VarChar, 100);
cmd.Parameters["@inBookName"].Value = "%" + inSearch + "%";
ad.SelectCommand = cmd;
connection.Open();
ad.Fill(ds, "BookData");
connection.Close();
return ds.Tables["BookData"];//Return the data table to the web form
}
After some editing, you should be able to search for the correct data. Good luck in implementing this search function. :)
No comments:
Post a Comment