friends
please if you have time to solve my problem
i have many textbox in my form with one button and one datagridview
i use this code to make the search
What if i want to perform a search using values from 2 or more text boxes. what if I typed in "r" in the Name text box then also typed "NY" in the city text box. I want to see the gridview give me the results of that.
that what i try to find and i didn't find anything
the code is working if i search in one textbox only
warm regards
private void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
if (txtCIVILIDD.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from Tabl1 where CIVILIDD = '" + txtCIVILIDD.Text.Trim() + "'", con);
sda.Fill(dt);
con.Close();
}
else if (txtName_Arabic.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where Name_Arabic like '%" + txtName_Arabic.Text + "%'", con);
sda.Fill(dt);
con.Close();
}
else if (txtusername.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from Tabl1 where username = '" + txtusername.Text.Trim() + "'", con);
sda.Fill(dt);
con.Close();
}
else if (comboBox1.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where status = '" + comboBox1.Text.Trim() + "'", con);
sda.Fill(dt);
con.Close();
}
else if (comboBox2.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where confirmation = '" + comboBox2.Text.Trim() + "'", con);
sda.Fill(dt);
con.Close();
}
else if (CBgender.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where gender like '%" + CBgender.Text + "%'", con);
sda.Fill(dt);
con.Close();
}
else if (CBNATIONALITY.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where NATIONALITY like '" + CBNATIONALITY.Text + "%'", con);
sda.Fill(dt);
con.Close();
}
else if (comboBoxGovernorate.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where Governorate = '" + comboBoxGovernorate.Text.Trim() + "'", con);
sda.Fill(dt);
con.Close();
}
else if (comboBoxCity.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where City = '" + comboBoxCity.Text.Trim() + "'", con);
sda.Fill(dt);
con.Close();
}
dataGridView1.DataSource = dt;
i try to solve my problem with this code bout i find "SELECT * FROM tabl1 WHERE 1=1 ";
it return null to me
private void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
StringBuilder sqlcommand = "SELECT * FROM tabl1 WHERE 1=1 ";
if (!string.IsNullOrEmpty(CBgender.Text))
{
sqlcommand.Append(" and GENDER LIKE '%");
sqlcommand.Append(CBgender.Text);
sqlcommand.Append("%'");
}
// repeat for other textbox fields
dataGridView1.DataSource = dt;
}
my search form
Here are two possible approaches. The first uses #WelcomeOverflows's suggestion which is to use the RowFilter property of the DataTable. The advantage of doing so is that you only have to perform one database query and the filtering is handled client side. However, it isn't possible to protect RowFilter from SQL injection easily (but while you can still potentially subvert the filtering intention, the damage you can do on a disconnected data source is limited). Also if the dataset is enormous, it might not be desirable to pull back the entire dataset at once and keep it in memory.
// call upon startup to get all the data one time
private void GetData()
{
DataTable dataSource = new DataTable();
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["myDatabase"].ConnectionString))
{
connection.Open();
SqlCommand selectCommand = new SqlCommand("SELECT * FROM tabl1", connection);
SqlDataAdapter adapter = new SqlDataAdapter(selectCommand);
adapter.Fill(dataSource);
dataGridView1.DataSource = dataSource;
}
}
// create a filter for the given field in the database and our control
private string CreateFilter(string fieldName, Control userInputControl, bool exactMatch)
{
string searchValue = null;
if (userInputControl is TextBox) searchValue = ((TextBox)userInputControl).Text;
if (userInputControl is ComboBox) searchValue = ((ComboBox)userInputControl).Text;
if (String.IsNullOrWhiteSpace(searchValue)) return null;
if (exactMatch)
return String.Format("{0}='{1}'", fieldName, searchValue);
return String.Format("{0} LIKE '%{1}%'", fieldName, searchValue);
}
// set the filter on our data grid view
private void button1_Click(object sender, EventArgs e)
{
var filterConditions = new[] {
CreateFilter("Name_Arabic", txtName_Arabic, false),
CreateFilter("gender", CBgender, false),
CreateFilter("CIVILIDD", txtCIVILIDD, true),
CreateFilter("NATIONALITY", cbNationality, false)
// etc.
};
var dataSource = (DataTable)dataGridView1.DataSource;
if (!filterConditions.Any(a => a != null))
{
dataSource.DefaultView.RowFilter = null;
return;
}
dataSource.DefaultView.RowFilter = filterConditions
.Where(a => a != null)
.Aggregate((filter1, filter2) => String.Format("{0} AND {1}", filter1, filter2));
}
Second approach is to filter directly in the database query, using SQL parameters to avoid SQL injection.
private string CreateSqlFilter(string fieldName, Control userInputControl, SqlCommand command, bool exactMatch)
{
string searchValue = null;
if (userInputControl is TextBox) searchValue = ((TextBox)userInputControl).Text;
if (userInputControl is ComboBox) searchValue = ((ComboBox)userInputControl).Text;
if (String.IsNullOrWhiteSpace(searchValue)) return null;
if (exactMatch)
{
command.Parameters.Add(new SqlParameter("#" + fieldName, searchValue));
return fieldName + " = #" + fieldName;
}
else
{
command.Parameters.Add(new SqlParameter("#" + fieldName, "%" + searchValue + "%"));
return fieldName + " LIKE #" + fieldName;
}
}
private void button2_Click(object sender, EventArgs e)
{
SqlCommand selectCommand = new SqlCommand();
var filterConditions = new[] {
CreateSqlFilter("Name_Arabic", txtName_Arabic, selectCommand, false),
CreateSqlFilter("gender", CBgender, selectCommand, false),
CreateSqlFilter("CIVILIDD", txtCIVILIDD, selectCommand, true),
CreateSqlFilter("NATIONALITY", cbNationality, selectCommand, false)
// etc.
};
string filterCondition = filterConditions.Any(a => a != null) ? filterConditions.Where(a => a != null).Aggregate((filter1, filter2) => String.Format("{0} AND {1}", filter1, filter2)) : (string)null;
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["myDatabase"].ConnectionString))
{
selectCommand.Connection = connection;
selectCommand.CommandText = filterCondition == null ? "SELECT * FROM tabl1" : "SELECT * FROM tabl1 WHERE " + filterCondition;
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter(selectCommand);
DataTable dataSource = new DataTable();
adapter.Fill(dataSource);
dataGridView1.DataSource = dataSource;
}
}
Create StringBuilder object:
StringBuilder sqlcommand = new StringBuilder("SELECT * FROM tabl1 WHERE 1=1");
You can create a parametrized query which considers parameters having null values as neutral in search. For example:
SELECT * FROM Product WHERE
(Id = #Id OR Id IS NULL) AND
(Name LIKE '%' + #Name + '%' OR #Name IS NULL) AND
(Price = #Price OR #Price IS NULL)
This way, if you pass NULL for any of the parameters, that parameter will not be considered in search.
Also as a side note, it prevents SQL Injection, by using parameters.
Example
The following example assumes you have a table called Product, having a column named Id as INT, Name as NVARCHAR(100) and Price as INT.
Then to load data, create the following method:
public DataTable GetData(int? id, string name, int? price)
{
DataTable dt = new DataTable();
var commandText = "SELECT * FROM Products WHERE " +
"(Id = #Id OR #Id is NULL) AND " +
"(Name LIKE '%' + #Name + '%' OR #Name IS NULL) AND " +
"(Price = #Price OR #Price IS NULL)";
var connectionString = #"Data Source=.;Initial Catalog=SampleDb;Integrated Security=True";
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(commandText, connection))
{
command.Parameters.Add("#Id", SqlDbType.Int).Value =
(object)id ?? DBNull.Value;
command.Parameters.Add("#Name", SqlDbType.NVarChar, 100).Value =
(object)name ?? DBNull.Value;
command.Parameters.Add("#Price", SqlDbType.Int).Value =
(object)price ?? DBNull.Value;
using (var datAdapter = new SqlDataAdapter(command))
datAdapter.Fill(dt);
}
return dt;
}
To get values from TextBox controls and pass to GetData, you can use the following code:
var id = int.TryParse(idTextBox.Text, out var tempId) ? tempId : default(int?);
var name = string.IsNullOrEmpty(nameTextBox.Text)?null:nameTextBox.Text;
var price = int.TryParse(priceTextBox.Text, out var priceId) ? priceId : default(int?);
Then to get data:
var data = GetData(id, name, price);
Related
I am doing a little project and I got stuck at a certain point (I am new to C# WPF). What I want to do is I have some data tables called item, issue_note & items_in_Issue_Note. I want to get all the issue note details into a datagrid & after selecting a row and click view button, I want to display the items in that issue note. I can get the data using
dgISNDetails.ItemsSource = db.Issue_Note.ToList();
but when I am going to use
dgISNDetails.ItemsSource = db.Database.SqlQuery<Issue_Note>("select Issue_No,Created_Date,R_Name,R_Dep,R_Desig,Issued_Date,UpdatedAt from Issue_Note").ToList();
the code throws a NullReferenceException (I want to use the SQL query, because I want to search issue notes by no and date).
I will add my code for reference.
Thank you!
public PnlISNDetails_SK()
{
InitializeComponent();
dgISNDetails.ItemsSource = db.Database.SqlQuery<Issue_Note>("select Issue_No,Created_Date,R_Name,R_Dep,R_Desig,Issued_Date,UpdatedAt from Issue_Note").ToList();
dgISNDetails.ItemsSource = db.Issue_Note.ToList();
datagrid = dgISNDetails;
}
private void btnSearch_Click(object sender, RoutedEventArgs e)
{
dt = new DataTable();
addIssueNoteLogic = new AddIssueNoteLogic();
if(cmbSearchBy.Text== "ISSUE NOTE NO")
{
addIssueNoteLogic.ViewISNFromISNNo(txtSearchBox.Text).Fill(dt);
dgISNDetails.ItemsSource = dt.DefaultView;
datagrid = dgISNDetails;
}
else if (cmbSearchBy.Text == "CREATED DATE")
{
addIssueNoteLogic.ViewISNFromCreatedDate(Convert.ToDateTime(dpSearchDatePicker.Text)).Fill(dt);
dgISNDetails.ItemsSource = dt.DefaultView;
datagrid = dgISNDetails;
}
else if (cmbSearchBy.Text == "ISSUED DATE")
{
addIssueNoteLogic.ViewISNFromIssuedDate(Convert.ToDateTime(dpSearchDatePicker.Text)).Fill(dt);
dgISNDetails.ItemsSource = dt.DefaultView;
datagrid = dgISNDetails;
}
}
Class code for search issue notes:
public SqlDataAdapter ViewISNFromISNNo(string searchText)
{
con.Open();
cmd = new SqlCommand();
cmd.CommandText = "select * from Issue_Note where Issue_No like '%" + searchText + "%'";
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
con.Close();
return da;
}
public SqlDataAdapter ViewISNFromCreatedDate(DateTime searchText)
{
con.Open();
cmd = new SqlCommand();
cmd.CommandText = "select * from Issue_Note where created_date = '" + searchText + "'";
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
con.Close();
return da;
}
public SqlDataAdapter ViewISNFromIssuedDate(DateTime searchText)
{
con.Open();
cmd = new SqlCommand();
cmd.CommandText = "select * from Issue_Note where Issued_date = '" + searchText + "'";
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
con.Close();
return da;
}
public SqlDataAdapter ViewISNDetails(string isnNo)
{
con.Open();
cmd = new SqlCommand();
cmd.CommandText = "select Item.ItemCode,Item.itemName,Item.Unit,Items_In_Issue_Note.Issued_Qty,Issue_Note.Issue_No from ((Item inner join Items_In_Issue_Note on Item.ItemCode= " +
"Items_In_Issue_Note.ItemCode) inner join Issue_Note on Issue_Note.Issue_No = Items_In_Issue_Note.Issue_No)where Issue_Note.Issue_No = '"+isnNo+"'; ";
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
con.Close();
return da;
}
This is the code for displaying items in issue note:
public void LoadGrid()
{
dt = new DataTable();
string isnNo = (PnlISNDetails_SK.datagrid.SelectedItem as Issue_Note).Issue_No; //Exception is thrown in here
addIssueNoteLogic = new AddIssueNoteLogic();
addIssueNoteLogic.ViewISNDetails(isnNo).Fill(dt);
dgItemsInISN.ItemsSource = dt.DefaultView;
}
Debug and verify that the connection to the database in your datacontext is not null or closed. specifically this part
db.Database
I have two tables in the database one is UserAuth and the other is CarAdd, but I need to show UserName from the UserAuth table in my CarAdd dataGridView1 section.
This method shows all data from my CarAdd table:
void Bindata()
{
SqlCommand cmd = new SqlCommand("select * from CarAdd", con);
SqlDataAdapter sd = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sd.Fill(dt);
dataGridView1.ItemsSource = dt.DefaultView;
}
But, now I need to show the username from the UserAuth table in the dataGridView1 section.
I have tried this code:
void BindataUserName()
{
SqlCommand cmd = new SqlCommand("select * from UsreAuth where UserName='UserName'", con);
SqlDataAdapter sd = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sd.Fill(dt);
// dataGridView1.ItemsSource = dt.DefaultView;
}
Here is my save click button, actually I need to save and show username on dataGridView1 after click this button:
private void save_Click(object sender, RoutedEventArgs e)
{
if (carid.Text != "" && cartype.Text != "" && model.Text != "" && intime.Text!="" && outtime.Text!="" && slotgroup.Text!="")
{
try
{
con.Open();
string newcon = "insert into CarAdd (carid, cartype, carmodel, duration, payment, slot_book, insertdate) values ('" + carid.Text + "','" + cartype.Text + "','" + model.Text + "', '" +txtduration.Text+ "','" +txtpayment.Text+ "','"+ slotgroup.Text +"' ,getdate())";
SqlCommand cmd = new SqlCommand(newcon, con);
cmd.ExecuteNonQuery();
MessageBox.Show("Successfully inserted");
Bindata();
// TimeShow();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
else
{
MessageBox.Show("Invalid credentials");
}
}
Note: I have created a WPF Windows application for this project
Thank you!
Since UserName is an attribute in the UserAuth table, the SQL query must be modified accordingly to fetch it.
SELECT UserName
FROM UserAuth
So for the Bindatausername() method, the SqlCommand should be changed to the following:
void BindataUserName()
{
SqlCommand cmd = new SqlCommand("select UserName from UserAuth where UserName='UserName'", con);
Under this I am trying to save the cart items chosen by the user into the database, for that I have initially selected the chosen items through Request.Query method now after that I have called those values and formed an SaveCartDetail function in which I have performed insert command into the database,the asp.net shows no error but there is no change in my table the name of my table is cart.
if (!IsPostBack)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("sno");
dt.Columns.Add("itemname");
dt.Columns.Add("quantity");
dt.Columns.Add("price");
dt.Columns.Add("totalprice");
dt.Columns.Add("image");
if (Request.QueryString["itemname"] != null)
{
if (Session["Buyitems"] == null)
{
dr = dt.NewRow();
SqlConnection scon = new SqlConnection(ConfigurationManager.ConnectionStrings["online food orderingConnectionString"].ConnectionString);
scon.Open();
String myquery = "select * from food_items where item_name=#items_name";
SqlCommand cmd = new SqlCommand(myquery, scon);
cmd.Parameters.AddWithValue("items_name", Request.QueryString["itemname"].ToString());
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
dr["sno"] = 1;
if (ds.Tables[0].Rows.Count > 0)
{
dr["itemname"] = ds.Tables[0].Rows[0]["item_name"].ToString();
dr["image"] = ds.Tables[0].Rows[0]["image"].ToString();
dr["price"] = ds.Tables[0].Rows[0]["price"].ToString();
int price = Convert.ToInt16(ds.Tables[0].Rows[0]["price"].ToString());
int quantity = Convert.ToInt16(Request.QueryString["quantity"].ToString());
int totalprice = price * quantity;
dr["quantity"] = Request.QueryString["quantity"];
dr["totalprice"] = totalprice;
SaveCartDetail(ds.Tables[0].Rows[0]["item_name"].ToString(), Request.QueryString["quantity"], ds.Tables[0].Rows[0]["price"].ToString(), totalprice.ToString());
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
Session["buyitems"] = dt;
GridView1.FooterRow.Cells[4].Text = "Total Amount";
GridView1.FooterRow.Cells[5].Text = grandtotal().ToString();
}
}
}
}
private void SaveCartDetail(String itemname, String quantity, String price, String totalprice)
{
String query = "insert into cart(item_name, quantity, price, totalprice, username) values ('" + itemname + "','" + quantity + "','" + price + "','" + totalprice + "','" + Session["username"].ToString() + "')";
SqlConnection scon1 = new SqlConnection(ConfigurationManager.ConnectionStrings["online food orderingConnectionString"].ConnectionString);
scon1.Open();
SqlCommand cmd1 = new SqlCommand(query, scon1);
cmd1.ExecuteNonQuery();
scon1.Close();
Response.Write("Items saved in cart");
}
I have written code to filter data from database(filtering is done by two dropdownlists and between 2 dates). I am getting an error
There is already an open DataReader associated with this Command which must be closed first.
this is my front end
public partial class data : System.Web.UI.Page
{
SqlConnection con;
string constring = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnshow_Click(object sender, EventArgs e)
{
if ((ddldept.SelectedValue == "all") && (ddldesig.SelectedValue!="all") )
{
con = new SqlConnection(constring);
con.Open();
string desig = ddldesig.SelectedValue;
DateTime mydate;
mydate = Convert.ToDateTime(tbfrom.Text);
string from = Convert.ToString(mydate);
mydate = Convert.ToDateTime(tbto.Text);
string to = Convert.ToString(mydate);
SqlCommand cmddeptall = new SqlCommand("select * from registration where Department IN('Computer Science Engineering','Mechanical Engineering','Electrical And Electronics','Electronics And Communication','Civil Engineering','Science And Humanity') AND PostAppliedFor='"+desig+"' AND (RegisteredDate BETWEEN '"+from+"' AND '"+to+"')",con);
cmddeptall.ExecuteReader();
SqlDataAdapter da = new SqlDataAdapter(cmddeptall);
DataSet ds = new DataSet();
da.Fill(ds, "registration");
GridView1.DataSource = ds.Tables["registration"];
GridView1.DataBind();
con.Close();
}
else if ((ddldept.SelectedValue == "all") && (ddldesig.SelectedValue == "all"))
{
SqlConnection con;
string constring = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
con = new SqlConnection(constring);
try
{
con.Open();
DateTime mydate;
mydate = Convert.ToDateTime(tbfrom.Text);
string from = Convert.ToString(mydate);
mydate = Convert.ToDateTime(tbto.Text);
string to = Convert.ToString(mydate);
string query = "select * from registration where Department IN('Computer Science Engineering','Mechanical Engineering','Electrical And Electronics','Electronics And Communication','Civil Engineering','Science And Humanity') AND PostAppliedFor IN('Principal','Professor','Associate Professor','Assistant Professor','Placement Officer','SoftSkills Trainer','Administrative Officer','Office Superintendent','Lab Technician') AND (RegisteredDate BETWEEN '" + from + "' AND '" + to + "')";
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteReader();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "registration");
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
}
}
else if ((ddldept.SelectedValue != "all") && (ddldesig.SelectedValue != "all"))
{
con = new SqlConnection(constring);
con.Open();
string desig = ddldesig.SelectedValue;
string dept = ddldept.SelectedValue;
DateTime mydate;
mydate = Convert.ToDateTime(tbfrom.Text);
string from = Convert.ToString(mydate);
mydate = Convert.ToDateTime(tbto.Text);
string to = Convert.ToString(mydate);
SqlCommand cmddeptall = new SqlCommand("select * from registration where Department='"+dept+"' AND PostAppliedFor='"+desig+"' AND (RegisteredDate BETWEEN '" + from + "' AND '" + to + "')", con);
cmddeptall.ExecuteReader();
SqlDataAdapter da = new SqlDataAdapter(cmddeptall);
DataSet ds = new DataSet();
da.Fill(ds, "registration");
GridView1.DataSource = ds.Tables["registration"];
GridView1.DataBind();
con.Close();
}
con.Close
}
Problem is that you are not disposing any objects properly. You should make database calls as mentioned below:
var ds = new DataSet();
if ((ddldept.SelectedValue == "all") && (ddldesig.SelectedValue != "all"))
{
using (var con = new SqlConnection(constring))
{
con.Open();
string desig = ddldesig.SelectedValue;
DateTime mydate;
mydate = Convert.ToDateTime(tbfrom.Text);
string from = Convert.ToString(mydate);
mydate = Convert.ToDateTime(tbto.Text);
string to = Convert.ToString(mydate);
using (var cmddeptall = new SqlCommand("select * from registration where Department IN('Computer Science Engineering','Mechanical Engineering','Electrical And Electronics','Electronics And Communication','Civil Engineering','Science And Humanity') AND PostAppliedFor='" + desig + "' AND (RegisteredDate BETWEEN '" + from + "' AND '" + to + "')", con))
{
using (var da = new SqlDataAdapter(cmddeptall))
{
da.Fill(ds, "registration");
}
}
}
}
else if ((ddldept.SelectedValue == "all") && (ddldesig.SelectedValue == "all"))
{
// Code Here
}
else if ((ddldept.SelectedValue != "all") && (ddldesig.SelectedValue != "all"))
{
// Code Here
}
Note: Moreover, I would suggest you to create separate function to call database and retrieve dataset based on query you have made. There is no need of writing same code again and again.
You don't need to execute the reader when you use the command in the SqlDataAdapter.Constructor, that's done implicitly at da.Fill. So remove the first line:
cmddeptall.ExecuteReader();
SqlDataAdapter da = new SqlDataAdapter(cmddeptall);
The search text box is not returning a valid person datatable on the screen, anyone have any idea why?
Database class:
static public DataTable SearchButton(string search)
{
using (var conn = new SqlConnection(DatabaseConnectionString))
{
var dt = new DataTable();
const string searchQuery = "exec SearchTerm";
using (var cmd = new SqlCommand(searchQuery, conn))
{
conn.Open();
cmd.Parameters.Add("#Search_Term", SqlDbType.VarChar, search.Length).Value = "%" + search + "%";
dt.Load(cmd.ExecuteReader());
return dt;
}
}
}
PeopleList.aspx.cs:
protected void SearchButton_Click(object sender, EventArgs e)
{
if (SearchTextbox.Text == null || SearchTextbox.Text == "")
{
PeopleListLabel.Text = "Please enter a search term!";
}
else
{
Phonelist.DataSource = Database.SearchButton(SearchTextbox.Text);
Phonelist.DataBind();
}
}
SQL Stored Procedure:
print 'SearchTerm'
if exists (select * from sys.objects where object_id = object_id(N'[SeachTerm]') AND type in (N'P', N'PC'))
drop procedure SearchTerm
go
create procedure SearchTerm
#Search_Term varchar(64) = null
as
begin
set nocount on;
SELECT first_name, last_name, email_address, gender, home_address, home_city, home_state, home_zip_code, telephone_number
FROM person
WHERE first_name LIKE #Search_Term OR last_name LIKE #Search_Term
end
You need to enclose the search parameter within single quotes.
Replace This:
cmd.Parameters.Add("#Search_Term", SqlDbType.VarChar, search.Length).Value
= "%" + search + "%";
With This:
cmd.Parameters.Add("#Search_Term", SqlDbType.VarChar, search.Length).Value
= "'%" + search + "%'";
you are missing commandType.
static public DataTable SearchButton(string search)
{
using (var conn = new SqlConnection(DatabaseConnectionString))
{
var dt = new DataTable();
const string searchQuery = "exec SearchTerm";
using (var cmd = new SqlCommand(searchQuery, conn))
{
conn.Open();
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("#Search_Term", SqlDbType.VarChar, search.Length).Value = "'%" + search + "%'";
dt.Load(cmd.ExecuteReader());
return dt;
}
}
}