AutoComplete functionality not firing - c#

I have a project that is using ASP.NET 4.5 and C#. I have a textbox server control that is tied to a asp AutoCompleteExtender. The problem is that it seems to either not be connection to the database to there is a bug somewhere in my code. For this I am not using a web service just a simple aspx and aspx.cs code behind. I haven't been able to debug to pinpoint the actual problem yet because I am getting the
uncaught exception thrown by method called through reflection
and am in the process of figuring out what is causing that problem.
Here is my textbox control:
<div class="col-md-10">
<asp:TextBox ID="txtContactsSearch" runat="server"></asp:TextBox>
<cc1:AutoCompleteExtender ServiceMethod="SearchCustomers"
MinimumPrefixLength="2"
CompletionInterval="100" EnableCaching="false" CompletionSetCount="10"
TargetControlID="txtContactsSearch"
ID="AutoCompleteExtender1" runat="server" FirstRowSelected="false">
</cc1:AutoCompleteExtender>
<asp:RequiredFieldValidator runat="server" ControlToValidate="StudentID" CssClass="text-danger" Display="Dynamic" ErrorMessage="The student ID field is required." />
</div>
And I have the AJAX directive on the declared on the aspx page aswell:
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
And this is the code behind that implements the functionality for the AutoComplete:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class SearchStudent : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> SearchStudents(string prefixText, int count)
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Fname from Student_Registration_Form where " +
"Fname like #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
cmd.Connection = conn;
conn.Open();
List<string> students = new List<string>();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
students.Add(sdr["Fname"].ToString());
}
}
conn.Close();
return students;
}
}
}
}

The issue which caught my attention is: You are calling wrong method in your Autocomplete extender
<cc1:AutoCompleteExtender ServiceMethod="SearchCustomers"
public static List<string> SearchStudents(string prefixText, int count)
{
Here you can see you have passed SearchCustomers as ServiceMehtod but in your page you are using SearchStudents.
Recently I have tried twitter's TypeAhead autocomplete plugin which is easy and fast as compare to Autocomplete Extender. Have a look you might like :
Textbox autocomplete using twitter typeahead in asp .net

[I think you have used this link for your reference .But it worked for me.][1]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
namespace AutoComplete
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetCompletionList(string prefixText, int count)
{
using (SqlConnection conn = new SqlConnection())
{
try
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["Default"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select LoginName from Users where " +
"LoginName like #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
cmd.Connection = conn;
conn.Open();
List<string> students = new List<string>();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
students.Add(sdr["LoginName"].ToString());
}
}
conn.Close();
return students;
}
}
catch (Exception ex)
{
return null;
}
}
}
}
}
ASPX Code:
<table style="margin-top: 40px; color: White">
<tr>
<td>
Search County
</td>
<td>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender ServiceMethod="GetCompletionList" MinimumPrefixLength="1"
CompletionInterval="10" EnableCaching="false" CompletionSetCount="1" TargetControlID="TextBox1"
ID="AutoCompleteExtender1" runat="server" FirstRowSelected="false">
</asp:AutoCompleteExtender>
</td>
</tr>
</table>
Web.Config
<connectionStrings>
<add name="Default" providerName="System.Data.SqlClient" connectionString="Data Source=SERVERNAME;database=DBNAME;uid=sa;pwd=123;connection reset=false;connection lifetime=1000000;enlist=true;min pool size=1;max pool size=1000000"/>
</connectionStrings>
And Don't Forgot to create table and insert some records in SQL Server

Related

Populating a listbox with search results from a SQL query in ASP.NET and C#

The idea behind the program is for a user to enter a title they would like to search for and then click on the search button. The program should then display the search results in a listbox. The current code populates the listbox with all the available titles when the from loads but when you search for a title the listbox stays the same. How can I avoid the population of the listbox when the form loads and how do I only display the search result when the user clicks the search button?
Here is the C# code I have written:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace Project2
{
public partial class ProductSelection : System.Web.UI.Page
{
public SqlConnection conn1;
public DataSet ds;
public SqlDataAdapter adap;
string DVDToRent;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string constr = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Hanno\Desktop\CMPG\CMPG212\Project 2\Project2\Project2\App_Data\Stock.mdf;Integrated Security=True";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT ID, Title FROM StockTable WHERE Title LIKE '%" + Session["DVDToRent"] + "%' AND CopiesAvailable = 'True'"))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
lstCustomers.DataSource = cmd.ExecuteReader();
lstCustomers.DataTextField = "Title";
lstCustomers.DataValueField = "ID";
lstCustomers.DataBind();
con.Close();
}
}
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
DVDToRent = tbSearch.Text;
Session["DvDToRent"] = tbSearch.Text;
}
}
}
and the ASP.NET markup for the listbox:
<div class="formSearch" runat="server">
<div class ="form-group">
<h2 class="auto-style2">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</h2>
</div>
<div class="form-group">
<asp:Label ID="Label2" runat="server" Text="Search for a DVD:"></asp:Label>
<br />
<asp:TextBox ID="tbSearch" runat="server"></asp:TextBox>
</div>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" />
<div class="form-group">
<asp:Label ID="Label3" runat="server" Text="Search Results:"></asp:Label>
<br />
<asp:ListBox ID="lstCustomers" runat="server" AutoPostBack="True" Width="400px"></asp:ListBox>
</div>
</div>

My web form is not saving to database successfully

My form doesn't save the text in the Texbox to the database. I've probably something wrong in my .cs CodeFile, but I can't work it out.
It could well be my connection string.
My web form:
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
Enter selection text:
</td>
<td>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
<td colspan="2" align="center">
<asp:Button ID="Button1" runat="server" Text="Submit" />
</td>
</tr>
</table>
</div>
</form>
Here is my code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(#"Data Source=db65225900.db.1and1.com; Initial Catalog=db211255182; User ID=dbo652259000; Password=Password");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into homepageSelection values('"+TextBox1.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
}
}
My MsSQL is setup like the following:
1 column: selectionText nvarchar(3000)
Missing button click event definition in aspx
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click1" />
---------------^
SqlConnection is for SQL Server. You need MySqlConnection - This is not part of the .NET Framework. So it is a better approach if you will also have to use the MySqlCommand object rather than the SqlCommand object.
This is MySql and not SQL. So you need to get connected to MySql. For this you need to download and installed the MySQL Connector/NET from the MySQL official website.
Then probably you can look at Connect C# to MySQL to see how to get connected with MySQL Database and run the different Insert, Update, Select, Delete commands using C#
Last but not the least you have to include OnClick="Button1_Click1" with your asp:Button
You need to set the colum name in insert statement
cmd.CommandText = "insert into homepageSelection (ColumnName) values('"+TextBox1.Text+"')";
also you missed click event
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click1" />

autocmplete in asp.net with ajax

I am trying to autocomplete textbox, and i downloaded source code from any website,
Here is aspx page code
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Ajax AutoCompleteExtender without Webservice</title>
</head>
<body>
<form id="form1" runat="server">
<ajax:ToolkitScriptManager ID="ScriptManager1" runat="server"/>
<div>
<asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
<ajax:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
TargetControlID="txtCountry"
MinimumPrefixLength="1" EnableCaching="true" CompletionSetCount="1"
CompletionInterval="1000" ServiceMethod="GetCountries" >
</ajax:AutoCompleteExtender>
</div>
</form>
and here is codebehind file.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetCountries(string prefixText)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand("select varStateName from tblStateMaster where varStateName like #Name'%'", con);
cmd.Parameters.AddWithValue("#Name", prefixText);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
List<string> CountryNames = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
CountryNames.Add(dt.Rows[i][1].ToString());
}
return CountryNames;
}
}
It could not generate proper output and i am not able to debug this service, so how can i debug such service, and please tell me where is exact problem and which points should be remember for service and autocomplete,
And one more thing can i do it with dropdownlist?
I suspect the issue is in your query and more specifically in the %, try to include it in your parameter instead:
prefixText = string.Concat(prefixText, "%");
SqlCommand cmd = new SqlCommand("select varStateName from tblStateMaster where varStateName like #Name", con);
EDIT
Ok, so digging around, according to official examples from Microsoft, your method signature should look like this (notice the additional parameters):
public static string[] GetCountries(string prefixText)
{
// your stuff
}

Ajax AutcompletExtender not returning any results

I have a text box, a script manager and an auto-complete extender on an aspx page. I'm trying to simply have an auto complete into the text box and am currently getting nothing. What am I missing? When I try to debug the code the break point never gets beyond the first curly brace in the GetComplete method. I'm on VS2010
markup:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="AjaxAutocomplete._Default" %>
<%# Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender ID="TextBox1_AutoCompleteExtender" runat="server"
DelimiterCharacters="" Enabled="True" ServiceMethod="GetComplete" MinimumPrefixLength="3" TargetControlID="TextBox1">
</asp:AutoCompleteExtender>
</asp:Content>
code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace AjaxAutocomplete
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Script.Services.ScriptMethod]
[System.Web.Services.WebMethod]
public static List<string> GetComplete(string Prefixtetxt)
{
List<string> returnList = new List<string>();
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter p = new SqlParameter("#drug_name", Prefixtetxt);
//cmd.Parameters.AddWithValue("#drug_name", p);
cmd.Parameters.Add("#drug_name", SqlDbType.VarChar);
using (SqlDataReader reader = cmd.ExecuteReader())
{
returnList.Add(Convert.ToString(reader["drug_name"]));
}
}
}
return returnList;
}
}
}
sproc from Sql Server
create proc spFindAllDrugs
#drug_name varchar(100)
as
begin
select distinct drug_name
from rx
where drug_name like '%' + #drug_name + '%'
end
It looks like you are not associating the SqlCommand with the connection or telling the command the name of your stored procedure. Try modifying your code as shown.
using (SqlCommand cmd = new SqlCommand("spFindAllDrugs"))
{
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;

ASP Button onClick to send data from text box to database

I'm new to ASP.
I am trying to insert data from an asp:textbox into a SQL Server database.
I have created a class in the APP_CODE folder which handles the database connection and insert methods.
When button1 is clicked I want it to take the data from the asp:textbox and use the questionnaireSQL.cs file in APP_CODE to update the database.
How can I go about this?
questionnaireSQL.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;
namespace Devworks
{
public class OscarSQL
{
private string _productConnectionString;
private SqlConnection _productConn;
public OscarSQL()
{
_productConn = new SqlConnection();
_productConnectionString += "data source=mssql.dev-works.co.uk; Initial Catalog=devworks_oscar;User ID=myusername;Password=mypassword";
_productConn.ConnectionString = _productConnectionString;
}
// Insert New Questionnaire:
public int InsertQuestionnaire(string QuestName, int CustomerID, int NumberOfQuest)
{
int retVal = 0;
SqlCommand myCommand = new SqlCommand("NewQuestionnaire", _productConn);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add(new SqlParameter("#QUESTNAME", SqlDbType.NVarChar));
myCommand.Parameters.Add(new SqlParameter("#CUSTID", SqlDbType.Int));
myCommand.Parameters.Add(new SqlParameter("#NUMQUEST", SqlDbType.Int));
myCommand.Parameters.Add("#QUEST_ID", SqlDbType.Int, 0, "QUEST_ID");
myCommand.Parameters["#QUEST_ID"].Direction = ParameterDirection.Output;
myCommand.Parameters[0].Value = QuestName;
myCommand.Parameters[1].Value = CustomerID;
myCommand.Parameters[2].Value = NumberOfQuest;
_productConn.Open();
myCommand.ExecuteNonQuery();
retVal = (int)myCommand.Parameters["#QUEST_ID"].Value;
_productConn.Close();
return retVal;
}
// SQL DATAREADER, DATATABLE & NON QUERY UPDATE:
private void insert(SqlCommand myCommand)
{
_productConn.Open();
myCommand.ExecuteNonQuery();
_productConn.Close();
}
private SqlDataReader getData(SqlCommand myCommand)
{
_productConn.Open();
SqlDataReader myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
return myDataReader;
}
private DataTable createDataTable(SqlDataReader data)
{
DataTable retVal = new DataTable();
retVal.Load(data);
return retVal;
}
}
}
newquestionnaire.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/Main.Master" AutoEventWireup="true" CodeBehind="new_questionnaire.aspx.cs" Inherits="new_questionnaire" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="container">
<div class="main">
<h2 class="new">Add Your Questionnaire</h2>
<h3>Give your questionnaire a name.</h3>
<asp:TextBox ID="QuestName" runat="server"></asp:TextBox>
<h3>CustomerID</h3>
<asp:TextBox ID="CustomerID" runat="server"></asp:TextBox>
<h3>Number Of Questions</h3>
<asp:TextBox ID="NumberOfQuest" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Create" />
</div> <!-- end main -->
</div> <!-- end container -->
</asp:Content>
newquestionnaire.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Devworks;
public partial class new_questionnaire : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
}
}
Thanks in advance
You've posted all this code but exactly what can't you do?
One has to wonder if you wrote the DAL (Data access layer - your db code) and the Web UI, how is it that you cannot write the click event of a button ironically called Button1 ??
You take the value of your textbox and on the click of a button insert it into a database.
When you have a large task seperate it into smaller ones and do each piece until you've finished the puzzle.
According to your code
OscarSQL c = new OscarSQL(); //btw: not sure why you are not using a static class for this
int result = c.InsertQuestionnaire(textBox.Text ...); //add all parameters here
If (result > 0)
//good id
else
//display error message
Place all of this code behind the button1_click event of your code.

Categories