Why is this code not working? - asp.net

I am trying to add a search bar with an auto complete in asp.net using a web method and here is what i tried :
<asp:TextBox runat="server" ID="sBox"></asp:TextBox>
<asp:AutoCompleteExtender runat="server" ID="aC" TargetControlID="sBox"
MinimumPrefixLength="2" Enabled="true" EnableCaching="true"
CompletionInterval="0000" CompletionSetCount="20"
ServiceMethod="AutoComplete" ServicePath="~/Controls/SearchComplete.asmx"
></asp:AutoCompleteExtender>
and the web-method:
[WebMethod]
public string[] AutoComplete(string prefixText) //auto completing the searchbar
{
List<string> listString = new List<string>();
using (SqlConnection conn = new SqlConnection(#"ConnectionString"))
{
SqlCommand cmd = new SqlCommand("SELECT id,name FROM search WHERE name LIKE #name", conn);
cmd.Parameters.AddWithValue("#name", "%" + prefixText + "%");
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
listString.Add(AutoCompleteExtender.CreateAutoCompleteItem(dr["name"].ToString(), dr["id"].ToString()));
}
}
}
string[] str = listString.ToArray();
return str;
}
it's not giving errors it just isn't auto completing , thanks
using asp.net 4.0

Two things to check for:
1) check to see if there's data going TO the server
2) put a break point on the "return" statement to checked what's being returned from the query

Set a break point in AutoComplete() and debug it. You may be throwing an error server side which prevents the client side AutoCompleteExtender from seeing the web method return value.

Related

Ajaxtoolkit - Autocomplete dont do anything when i click

I have tried everything and nothing works, i have no clue now. I used an example, that used to work ones but dont anymore. I used this example
https://www.aspsnippets.com/Articles/AJAX-AutoCompleteExtender-Example-in-ASPNet.aspx
And download the ajaxtoolkit from here
https://www.devexpress.com/products/ajax-control-toolkit/
I have scriptmanager in the top of the page and it looks like this.
This is my code
Masterpage.master
<asp:TextBox ID="txtContactsSearch" aria-describedby="basic-addon2" class="form-control-header" placeholder="Søg her ..." runat="server"></asp:TextBox> <cc1:AutoCompleteExtender ServiceMethod="SearchCustomers" MinimumPrefixLength="2" ServicePath="MasterPage.master" CompletionInterval="100" EnableCaching="false" CompletionSetCount="10" TargetControlID="txtContactsSearch" ID="AutoCompleteExtender1" runat="server" FirstRowSelected = "false"></cc1:AutoCompleteExtender>
My codebehind
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> SearchCustomers(string prefixText, int count)
{
using (MySqlConnection conn = new MySqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["Connectionstring"].ConnectionString;
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.CommandText = "select Produktnavn from Produkter where " +
"Produktnavn like #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
cmd.Connection = conn;
conn.Open();
List<string> customers = new List<string>();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(sdr["Produktnavn"].ToString());
}
}
conn.Close();
return customers;
}
}
}

Stored procedure doesnt return any value

I got simple problem but I got no idea about where is problem :/ So in my GridView I am using ObjectDataSource with custom paging like in this tutorial http://www.codedigest.com/Articles/ASPNET/180_Custom_GridView_Paging_with_ObjectDataSource_Control_with_ASPNet_20.aspx
Here is my aspx markup:
<asp:ObjectDataSource ID="ObjectDataSource2"
runat="server"
onselecting="ObjectDataSource2_Selecting"
EnablePaging="true"
SelectCountMethod="GetItemsCount"
SelectMethod="BindItems"
StartRowIndexParameterName="startRowIndex"
MaximumRowsParameterName="maximumRows"
TypeName="eSova.Utilities.RecordUtilities"
>
And method which calling:
public static DataTable BindItems(int category,int search,int startRowIndex,int maximumRows)
{
DataTable table = new DataTable();
using (SqlConnection connection = new SqlConnection())
{
ConnectionUtilities.OpenConnection(connection);
SqlTransaction transaction = connection.BeginTransaction();
try
{
SqlCommand command = new SqlCommand("GetItems",connection,transaction);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#RowIndex", SqlDbType.Int, 4).Value = startRowIndex;
command.Parameters.Add("#MaxRows", SqlDbType.Int, 4).Value = maximumRows;
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(table);
transaction.Commit();
}
catch
{
transaction.Rollback();
}
}
return table;
}
My stored procedure works just fine and return in all items from table.
But when I analyze the code, I got breakpoint on return and table variable is without records. I don't know where is problem.
UPDATE:
create proc [dbo].[GetItems](#RowIndex int,#MaxRows int)
as
declare #StartRows int
declare #EndRow int
set #StartRows=(#RowIndex+1)
set #EndRow=(#StartRows+#MaxRows)
select *
from ( select id, name, filepath, descript, itemlanguage,
filetypeid, ROW_NUMBER() over (ORDER by id)as row FROM Items)as NumberesItems
where row between #StartRows and #EndRow
Your connectionstring is empty.

Need help reading multiple values back from sql server database in asp code

here is my codebehind for grabbing data from database:
public static string getTestimonial()
{
string username = "xxxxx";
SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["xxxxxxx"].ConnectionString);
Conn.Open();
string sql = "select testimonial,submitname from (SELECT TOP 1 * FROM dbo.testimonials where username='" + username + "' ORDER BY newid()) as answer;";
SqlCommand cmd = new SqlCommand(sql, Conn);
string test=cmd.ExecuteScalar().ToString();
Conn.Close();
return test;
}
yet when I try to display the data on my aspx page all I get is the first value:
<div class="span3">
<%= getTestimonial() %>
</div>
can you please help me with a method of getting both the testimonial and the submitname from the query into variables?
Thanks!
Thanks! Solved! using:
public static string getTestimonial()
{
string username = "xxxxxx";
SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["xxxxxxx"].ConnectionString);
Conn.Open();
string sql = "select testimonial,submitname from (SELECT TOP 1 * FROM dbo.testimonials where username='" + username + "' ORDER BY newid()) as answer;";
SqlCommand cmd = new SqlCommand(sql, Conn);
var test = new StringBuilder();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
test.Append(reader.GetString(0));
test.Append(" and ");
test.Append(reader.GetString(1));
}
}
Conn.Close();
return test.ToString();
}
ExecuteScalar() will always return first column of the first row - a single value. You may want to rethink your approach, meanwhile the simplest way is to make your query return combined value:
string sql = "select testimonial + ' and ' + submitname from ....
As an aside, you probably should rewrite that function to not use inline SQL, as you are making your site vulnerable to SQL injection attacks potentially in writing it this way. (presumably, userid is not set as a constant XXXXX in the actual function and is instead passed in somehow).

Search GridView

I have a guestbook at the moment displaying "comment", "comment_time", "user". I want to add a search box below and then search the gridview by "user" and then bind the data to a new grid view below. I am under strict instructions to have all data interactions passed via a web service.
I have a Web Method at the moment to get all the comments:
[WebMethod]
public DataSet SearchDatabase(string query)
{
DataSet ds = new DataSet();
string database = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|/dvd_forum.accdb;Persist Security Info=True";
string queryStr = "SELECT * FROM Comments WHERE User LIKE '%query%'";
OleDbConnection myConn = new OleDbConnection(database);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(queryStr, myConn);
myConn.Open();
myDataAdapter.Fill(ds, "Comments");
myConn.Close();
return ds;
}
Here's the front code:
<asp:Label ID="Label3" runat="server" Text="Search"></asp:Label><asp:TextBox ID="TextBoxSearch"
runat="server"></asp:TextBox><asp:Button ID="ButtonSearch"
runat="server" Text="Search" onclick="ButtonSearch_Click" />
<asp:GridView ID="GridView2" runat="server">
The code behind:
protected void ButtonSearch_Click(object sender, EventArgs e)
{
string query = TextBoxSearch.Text;
localhost.Service1 myws = new localhost.Service1();
ds = myws.SearchDatabase(query);
GridView2.DataSource = ds;
GridView2.DataBind();
}
It just doesn't do anything at all, page refreshes with no new GridView or any other action.
On another side note:
I have another input on the same page with a required field validator that doesn't let me search unless I fill the input with some text. How can I resolve this?
Thanks.
string queryStr = "SELECT * FROM Comments WHERE User LIKE '%"+query+"%'";

Getting results from a stored procedure to populate a GridView

I have a windows aspx form that I have a TextBox, Button and a GridView. The TextBox is stored as a variable #subschedule and passed to a stored procedure. What I'd like to do is to populate the results of that procedure into my GridView. Can anyone suggest a way to do this?
Thank you
Two popular options:
1.. Code Behind:
string subSchedule = txtSubSchedule.Text.Trim();
//you'll create a new class with a method to get a list of customers
//from your database as others answers have demonstrated
IEnumerable<Customer> custs = MyDataLayer.GetCustomers(subSchedule);
myGrid.DataSource = custs;
myGrid.DataBind();
2.. Use a SqlDataSource. This is a quick and dirty way to bind your ASP.NET server control to a stored procedure. It's got its easy implementation pros, and some other cons :
<asp:GridView id="myGrid"
runat="server"
AutoGenerateColumns="true"
DataSourceID="ds1" />
<asp:SqlDataSource
id="ds1"
runat="server"
ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"
SelectCommandType="StoredProcedure"
SelectCommand="GetSchedule">
<SelectParameters>
<asp:ControlParameter name="SubSchedule"
ControlID="txtSubSchedule" Propertyname="Text"/>
</SelectParameters>
</asp:SqlDataSource>
Add a reference to System.Data.SqlClient
Then create a method for your calling your stored procedure... Maybe wrap it up in a class for database calls.
public static class DataBase
{
public static DataTable myProcedureName(String subSchedule)
{
var dt = new DataTable();
using (var cnx = new SqlConnection("myConnectionString"))
using (var cmd = new SqlCommand {
Connection = cnx,
CommandText = "myProcedureName",
CommandType = CommandType.StoredProcedure,
Parameters = {
new SqlParameter("#subSchedule", subSchedule)
}
})
{
try
{
cnx.Open();
dt.Load(cmd.ExecuteReader());
return dt;
}
catch (Exception ex)
{
throw new Exception("Error executing MyProcedureName.", ex);
}
}
}
}
Then call it...
gvMyGrid.DataSource = DataBase.myProcedureName(txtSubSchedule.Text);
gvMyGrid.DataBind();
You'll need to use the DataSource property:
DataTable dt = new DataTable();
// Open the connection
using (SqlConnection cnn = new SqlConnection(
"Data Source=.\sqlexpress;Initial Catalog=AcmeRentals;Integrated Security=True"))
{
cnn.Open();
// Define the command
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = cnn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = storedProcedureName;
// Define the data adapter and fill the dataset
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
// This is the key code; you can set the DataSource to "collection"
gridView.DataSource = dt.DefaultView;
gridView.DataBind();
Source: http://msmvps.com/blogs/deborahk/archive/2009/07/07/dal-retrieve-a-datatable-using-a-stored-procedure.aspx
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "SPPUBLISHER";
adapter = new SqlDataAdapter(command);
adapter.Fill(ds);
connection.Close();
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
Full Source..gridview from procedure

Resources