AutoCompleteExtender on TextBox returns the page HTML - c#

I am trying to implement a search textbox with the Ajax Control Toolkit AutoCompleteExtender. The result should be a list of names matching the entered text however what gets displayed is the page source HTML, character by character, creating an extremely long list of single letters.
I have found and tried several samples but cannot get this to work. I am certain the database connection is valid and the SQL query when executed directly in MSSMS, returns the expected result. The AjaxControlToolkit is installed and works on other pages in the solution.
This issue was asked before ("Ajax Control Toolkit AutoCompleteExtender displays html source character by character of the current page as autocomplete suggestion list"). However for reasons of simplicity and maintainability I do not want to implement a WebService as this poster did.
acex.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>AutoCompleteExtender - Last Names</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<asp:TextBox ID="txbxLastName" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
TargetControlID="txbxLastName"
MinimumPrefixLength="2"
EnableCaching="true"
CompletionSetCount="1"
CompletionInterval="1000"
ServiceMethod="GetLastNames">
</asp:AutoCompleteExtender>
</div>
</form>
</body>
</html>
acex.aspx.cs
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace MCA
{
public partial class acex : System.Web.UI.Page
{
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetLastNames(string prefixText)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString());
SqlCommand cmd = new SqlCommand("SELECT [Last_Name] FROM [Entity_Person] WHERE [Last_Name] LIKE #Name+'%'", conn);
cmd.Parameters.AddWithValue("#Name", prefixText);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
conn.Open();
da.Fill(dt);
List<string> LastNames = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
LastNames.Add(dt.Rows[i][0].ToString());
}
return LastNames;
}
}
}

Related

How link/bind textbox, dropdown list and SQL database together on C#?

Basically what the task is that you search someone's name in the textbox, click search, the users with that name will populate the dropdown list.
SQL Server: this is the query I am try to add to the search button on my page:
SELECT Users.Forename + ' ' + Users.Surname AS [Name], Users.ID
From Users
Order by [Name]
Aspx side:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Page1.aspx.cs" Inherits="SearchRecords.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<p> Search User </p>
<p> Filter Users: <asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
<asp:Button ID="SearchButton1" runat="server" Text="Search" OnClick="BtnSearch_Click" />
<br />
<br />
Select a user:
<asp:DropDownList ID="DDLSelectUser1" runat="server"> </asp:DropDownList>
<asp:Label ID="lblUserCount" runat="server" Text=""></asp:Label>
<br />
<div class="DataGrid">
<asp:GridView ID="DataGrid1" runat="server" ShowHeaderWhenEmpty="false" EmptyDataText="No data found!">
</asp:GridView>
</div>
</p>
<p> Link to page 1 </p>
</div>
</form>
</body>
</html>
C# side: I've got this already (this is me attempting to fetch data from the Database and bind the list of names to the dropdown list):
private void LoadIntoDropdown()
{
using (SqlConnection connection = new SqlConnection("Data Source=DEV-WEB;Initial Catalog=Isabelle;Integrated Security=True"))
{
connection.Open();
string sqlQuery = "SELECT Users.Forename + ' ' + Users.Surname AS [Name], Users.ID From Users WHERE Forename like '%'+#Forename+'%'";
using (SqlCommand cmd = new SqlCommand(sqlQuery, connection))
{
cmd.Parameters.AddWithValue("Forename", TextBox1.Text);
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
adapter.Fill(dt);
DDLSelectUser1.DataTextField = "[Name]";
DDLSelectUser1.DataValueField = "Users.ID";
DDLSelectUser1.DataSource = dt;
DDLSelectUser1.DataBind();
}
}
connection.Close();
}
}
It's never working, this is what I get:
"DataBinding: 'System.Data.DataRowView' does not contain a property with the name '[Name]'."
And I don't understand why? I combined two columns from the database, the Forename and Surname columns, together and called it [Name], so it does exist.
I can't seem to find online the right answer to my question as they all are 'select from the dropdown list to fill the textbox' I want the other way around, if it's possible!
The alias [Name] in your query becomes just Name once the database returns the resultset to the client (in this case, your program). So, when you reference that column in your code, you should do it as Name instead of [Name]
DDLSelectUser1.DataTextField = "Name";
Square bracket names and aliases are used in SQL Server queries both to specify that you want the name/alias to be exactly as written (including "invalid" characters for names like spaces e.g. [First Name]) and to differentiate such names/aliases from keywords (althought using keywords as field names is not recommended).
You can find more information in this SO question and in this Microsoft Docs' question

Drag and Drop ListBox Rows with jQuery in ASP.Net

I'm trying to implement a C# drag and drop with a listbox.
I've come across some snippets of code on the internet but none seem to be working with my needs.
I want you to show me an example code of how to move rows in ListBox.
My code below.
Thanks!
.cs
public partial class DragDrop : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string constr = ConfigurationManager.ConnectionStrings["cn"].ConnectionString;
string query = "SELECT * FROM City LIMIT 10;";
using (MySqlConnection con = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand(query))
{
using (MySqlDataAdapter sda = new MySqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
ListBox1.DataSource = ds.Tables[0];
ListBox1.DataTextField = "Name";
ListBox1.DataValueField = "Name";
ListBox1.DataBind();
}
}
}
}
}
}
.aspx
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.22/jquery-ui.js"></script>
<link rel="Stylesheet" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/themes/redmond/jquery-ui.css" />
<script type="text/javascript">
$(function () {
$(".drag_drop_grid").sortable({
items: 'tr:not(tr:first-child)',
cursor: 'crosshair',
connectWith: '.drag_drop_grid',
axis: 'y',
dropOnEmpty: true,
receive: function (e, ui) {
$(this).find("tbody").append(ui.item);
}
});
$("[id*=ListBox2] tr:not(tr:first-child)").remove();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="ListBox1" runat="server"
SelectionMode="Multiple"
Height="100"
Width="100"
Font-Names="Verdana"
EnableViewState="true"></asp:ListBox>
<asp:ListBox ID="ListBox2" runat="server"
Height="100"
Width="100"
Font-Names="Verdana"></asp:ListBox>
</div>
</form>
</body>
</html>
Hope this can help you.
Best regards
http://rajudasa.blogspot.com/2011/11/drag-and-drop-list-items-with-multi.html
Here you will find information about selecting items by drag-n-drop on webpage and how i created drag-n-droppable items in listBoxes using JQuery-UI Sortable.
On JQuery-UI Sortable Demo page, List items been represented by <li>, I tried with <li> and <td> as items, both of them not satisfied my requirement. Instead of using <li> as items, I used <div> tags. One of the required feature is, multi-select drag drop using ctrl + mouse drag.
The sample demo page contains 2 Listboxes (source, destination). Source box is filled with items from JSON data(static or coming from Asp.Net). On button click, the selected/dropped items in destination box
are stored in a hidden-field as JSON string and you can retreive them at serverside. (or in JS version, just filling in a textarea).
You can check the demo here
Download the Zip file here

the button is not doing its supposed function

I'm having a project to create a website that connects my database to perform different functionalities. When I create the web form and connects it with the database, and when i click the button it's supposed that all the products will appear but it doesn't happen.
This is the SQL procedure:
CREATE PROC reviewOrders
AS
BEGIN
SELECT *
FROM Orders
END
And this is the c# code
protected void reviewOrders(object sender, EventArgs e)
{
string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ToString();
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("reviewOrders", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
and the HTML code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="ReviewOrders.aspx.cs"
Inherits="GUCommerce.ReviewOrders" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="viewOrders" runat="server" OnClick ="reviewOrders" Height="45px"
Text="view orders" Width="148px" />
</div>
<p style="height: 121px">
</p>
<asp:Panel ID="x" Visible ="false" runat="server" Height="338px">
<asp:Table ID="orders" CellPadding ="4" runat="server" Height="67px" Width="316px">
</asp:Table>
</asp:Panel>
</form>
</body>
</html>
Can one please tell me what is missing?
Thanks is advance!
I would recommend using ASP Gridview instead of ASP Table. Gridviews (<asp:GridView>) are used to present data in tables. They actually get rendered as html tables. Here is how to build one using your code:
<asp:Panel ID="x" Visible="false" runat="server" Height="338px">
<%--<asp:Table ID="orders" CellPadding="4" runat="server" Height="67px" Width="316px"></asp:Table>--%>
<asp:GridView ID="gvOrders" CellPadding="4" runat="server" Height="67px" Width="316px"></asp:GridView>
</asp:Panel>
Now, in the code-behind there are a couple changes. A DataTable can be used to store the results of your query and then you can bind a DataTable to a GridView. To do this, you need a SqlDataAdapter which is shown below.
protected void reviewOrders(object sender, EventArgs e)
{
// data table variable outside of sql block
// you could also move the sql code to another method that returns a datatable
DataTable dt = null;
string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ToString();
using (SqlConnection conn = new SqlConnection(connStr))
{
SqlCommand cmd = new SqlCommand("reviewOrders", conn);
cmd.CommandType = CommandType.StoredProcedure;
using (cmd)
{
conn.Open();
// Use SQL Data Adapter instead of Execute Non Query
using (SqlDataAdapter _Adapter = new SqlDataAdapter(cmd))
{
// Fill DataTable with results of query
dt = new DataTable();
_Adapter.Fill(dt);
}
}
}
//
gvOrders.DataSource = dt;
gvOrders.DataBind();
}
Note: I use using(SqlConnection) and using(cmd) to handle closing the connection and command for me. Give this a shot.

The name 'UName' does not exist in the current context

When trying to register to my database I am receiving the "The name 'UName' does not exist in the current context" error.
Register.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Register.aspx.cs" Inherits="Register" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Registration Page</title>
</head>
<body>
<p>This is the registration page</p>
Home | Register
<form id="form1" runat="server">
<div>
<p>Enter First Name :</p>
<p>
<asp:TextBox ID="UName" runat="server" Width="271px"></asp:TextBox>
</p>
<p>
<asp:Button ID="registerButton" runat="server" Text="REGISTER" OnClick="registerEventMethod" />
</p>
</div>
</form>
</body>
</html>
Register.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Register : System.Web.UI.Page
{
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
String queryStr;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void registerEventMethod(object sender, EventArgs e)
{
registerUser();
}
private void registerUser()
{
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
queryStr = "";
queryStr = "INSERT INTO jamieobr_obecarrentals.users (Forename)" +
"VALUES('" + UName.Text + "')";
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
cmd.ExecuteReader();
conn.Close();
}
}
why am I getting this error? I have tried several solutions and all failed.
So I solved my own issue, the first initial issue was that I tried copying the .aspx file into a new solution, however this did not copy along the .aspx.designer.cs file therefore causing the problem.
However after trying to re write a fresh version manually which had a designer file with it I forgot to include the .cs file into the namespace of my solution therefore then generating a new problem.
However after including the .cs file into the namespace, hey presto, it worked!

Insert Data into SQL table using Javascript and ASP.NET

Im using Microsoft Visual Studio 2012 as platform and i have created Web Forms Project
i have created data base file "SimpleDB.mdf" inside his "Table" folder i added new table called "Table" which has two columns - id and Name(string).What im trying is to insert string data into Name column of this table while calling server side function from javascript function.
This is the aspx.cs code
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.Web.Services;
namespace ProjectWWW
{
public partial class WebForm1 : System.Web.UI.Page
{
[WebMethod]
public static string InsertData(string ID){
string source = "Data Source=(LocalDB)\v11.0;Integrated Security=True;Connect Timeout=30";
SqlConnection con = new SqlConnection(source);
{
SqlCommand cmd = new SqlCommand("Insert into Table(Name) values('" + ID + "')", con);
{
con.Open();
cmd.ExecuteNonQuery();
return "True";
}
}
}
}
and this is the aspx code
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="ProjectWWW.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script>
function CallMethod() {
PageMethods.InsertData("hello", CallSuccess, CallError);
}
function CallSuccess(res) {
alert(res);
}
function CallError() {
alert('Error');
}
</script>
</head>
<body>
<header>
</header>
<div class="table" id="div1" > </div>
<form id="Form1" runat="server">
<asp:Button id="b1" Text="Submit" runat="server" onclientclick="CallMethod();return false;"/>
<asp:ScriptManager enablepagemethods="true" id="ScriptManager1" runat="server"></asp:ScriptManager>
</form>
</body>
</html>
So basically im expecting when the button submit is clicked the Table Column "Name" will be filled with "Hello" but nothing happens and the column stays empty(NULL)
Table is reserved word in T-SQL so i would suggest you to use [] square brackets to enclose the Table.
Try This:
SqlCommand cmd = new SqlCommand("Insert into [Table](Name)
values('" + ID + "')", con);
Suggestion: Your query is open to sql injection attacks.I would suggest you to use Parameterised Queries to avoid them.
Try This:
using(SqlConnection con = new SqlConnection(source))
{
using(SqlCommand cmd = new SqlCommand("Insert into [Table](Name)
values(#Name)", con))
{
con.Open();
cmd.Parameters.AddWithValue("#Name",ID);
cmd.ExecuteNonQuery();
return "True";
}
}

Categories

Resources