Programming Journal C#, Java, SQL and to a lesser extent HTML, CSS, XML, and regex. I made this so other programmers could benefit from my experience.

Wednesday, December 17, 2008

Using AutoComplete Ajax Control With Separate ID Field from Name Field

In the previous post, I detailed how to use the SQL stored procedure to select matches.

AutoComplete Extender offers a convenient way to select values froma TextBox. One problem is that multiple details can be displayed, but the whole text is selected by default. I wanted to allow multiple AutoCompletes, select the id without the other details and append the appropriate delimeter in between entries. First, I setup the WebService method. Note that the Stock object has Symbol and Name properties:

[WebMethod]
public string[] GetStocksInPrefix(string prefixText, int count)
{
int curCount = 0;
if (count == 0)
{
count = 10;
}
List<string> items = new List<string>();
JavaScriptSerializer jss = new JavaScriptSerializer();
string[] stocks = null;
string connectionString = getConnectionString("ConnectionString");
SqlDataReader rdr = null;
SqlConnection conn = new SqlConnection(connectionString);
System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand("sproc_aspnet_GetStocksByPrefix", conn);
try
{
command.CommandType = System.Data.CommandType.StoredProcedure;
conn.Open();
command.Parameters.AddWithValue("@Prefix", prefixText+"%");
rdr = command.ExecuteReader();
string tmp = string.Empty;
Stock _stock = null;
while (rdr.Read() && curCount<count )
{
_stock = new Stock(rdr["Symbol"].ToString(), rdr["Name"].ToString(), rdr["Exchange"].ToString());
tmp = rdr["Symbol"] + "\t" + rdr["Name"];
items.Add(AutoCompleteExtender.CreateAutoCompleteItem(tmp, jss.Serialize(_stock)));
curCount++;
}
command.Parameters.Clear();
}
catch (Exception ex)
{
}
finally
{
if (rdr != null) rdr.Close();
if(conn!=null) conn.Close();
}
return items.ToArray();
}


Then, I add the javascript event, 'OnSymbolSelected',to the OnClientItemSelected event in the AutoComplete Extender:

<asp:TextBox ID="txtSymbols" runat="server" Width="300px"></asp:TextBox>
<cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
TargetControlID="txtSymbols" ServiceMethod="GetStocksInPrefix"
ServicePath="~/WebServiceAutoCompleteSymbol.asmx" MinimumPrefixLength="2"
CompletionListHighlightedItemCssClass="watermark" CompletionSetCount="10"
DelimiterCharacters=", "
CompletionListElementID="Symbol"
CompletionListItemCssClass="watermarkMatch"
EnableCaching="true" CompletionInterval="1000" OnClientItemSelected="OnSymbolSelected"
>
</cc1:AutoCompleteExtender>


Finally, add the javascript function to the aspx page. This function reads the Stock object into results, takes the SelectedText and gets the original string before the new text was completed by replacing the completed text with an empty string. If it is an additional field (that does not contain ' ' or ',', then only the id (symbol in this case) is added. Othewise, the original id plus the ' ' delimeter and the new id is added:

<script type="text/javascript" language="javascript">
function OnSymbolSelected(source, eventArgs)
{
var results = eval('(' + eventArgs.get_value() + ')');
if (results.symbol != null) {
var symbols = document.getElementById('<%= txtSymbols.ClientID %>').value;
var original = symbols.replace((results.symbol+'\t'+results.name),'');
if (original.indexOf(' ')>0 || original.indexOf(',')>0)
document.getElementById('<%= txtSymbols.ClientID %>').value = original + (' '+ results.symbol);
else
document.getElementById('<%= txtSymbols.ClientID %>').value = results.symbol;
}
}
</script>


References: http://ziqbalbh.wordpress.com/2008/06/11/google-like-autocomplete-suggestions/
http://www.tizag.com/javascriptT/javascript-string-replace.php
http://techron.blogspot.com/2008/04/reading-textbox-or-other-control-values.html

79 comments:

Anonymous said...

Don't you love me

You can see my pics here.

[url=http://sexscreener.org/p/random/1992]My Profile[/url]

Anonymous said...

Technology truly has become one with our daily lives, and I think it is safe to say that we have passed the point of no return in our relationship with technology.


I don't mean this in a bad way, of course! Societal concerns aside... I just hope that as technology further advances, the possibility of transferring our memories onto a digital medium becomes a true reality. It's a fantasy that I dream about all the time.


(Posted on Nintendo DS running [url=http://kwstar88.livejournal.com/491.html]R4[/url] DS BlogServ)

Anonymous said...

Cool article you got here. It would be great to read a bit more about this matter. Thanks for sharing that material.

Anonymous said...

Hello


You will not believe what I just found! [url=http://www.foolioo.com]Foolioo.com[/url] makes [url=http://www.foolioo.com]free[/url] custom website for free. Yep! That's right, FREE!
Never thought it'd be so easy to get a free website and I really had to tell you guys.



So if you're looking for a free website, give these guys a try.



Cheers

Anonymous said...

Nice dispatch and this post helped me alot in my college assignement. Thanks you for your information.

Anonymous said...

Hello,

When ever I surf on web I never forget to visit this website[url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips].[/url]You have really contiributed very good info here techron.blogspot.com. Do you pay attention towards your health?. Let me present you with one fact here. Recent Research presents that nearly 80% of all U.S. grownups are either obese or overweight[url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips].[/url] So if you're one of these individuals, you're not alone. Infact many among us need to lose 10 to 20 lbs once in a while to get sexy and perfect six pack abs. Now the question is how you are planning to have quick weight loss? You can easily lose with with little effort. If you improve some of your daily diet habbits then, its like piece of cake to quickly lose weight.

About me: I am blogger of [url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips]Quick weight loss tips[/url]. I am also health expert who can help you lose weight quickly. If you do not want to go under painful training program than you may also try [url=http://www.weightrapidloss.com/acai-berry-for-quick-weight-loss]Acai Berry[/url] or [url=http://www.weightrapidloss.com/colon-cleanse-for-weight-loss]Colon Cleansing[/url] for quick weight loss.

Dean said...

greetings to all.
I would first like to thank the writers of this blog by sharing information, a few years ago I read a book called guanacaste costa rica in this book deal with questions like this one.

Anonymous said...

It was certainly interesting for me to read the post. Thank you for it. I like such themes and everything connected to this matter. I would like to read a bit more on that blog soon.

Kate Benedict

niz said...

Hello .. firstly I would like to send greetings to all readers. After this, I recognize the content so interesting about this article. For me personally I liked all the information. I would like to know of cases like this more often. In my personal experience I might mention a book called Generic Viagra in this book that I mentioned have very interesting topics, and also you have much to do with the main theme of this article.

Anonymous said...

Yes, really.

Anonymous said...

It is remarkable, a useful piece

oudinia said...

Just Awsome.

Thank you very much.

Anonymous said...

And how about adding some more pics? No offence, blog is really nice. Just as I’ve heard visitors acquire information much more efficient if they see some useful pictures.

Whitney Nixon
make cell phone jammer

Anonymous said...

Pretty cool blog you've got here. Thanx for it. I like such topics and everything that is connected to them. I would like to read more on that blog soon.


Julia Swenson
suisse escort

Anonymous said...

1

Anonymous said...

Специально для Вас друзья мы возвращаем наш отличный проект на котором можно скачать все с файлобменников бесплатно [url=http://kachaitut.ru/]Кино[/url] . Все для Вас друзья.
Уважаемые Админы приглашаем Вас обменяться ссылками.

С Уважением, Администрация КачайТУТ.

Anonymous said...

Отличная новость, что то здесь не так. А что именно. Нет все таки здесь [url=http://dadabum.ru/]Анекдоты[/url]
Блин Это что в натуре все здесь? Да ну нафиг ....

Anonymous said...

generic viagra viagra online doctor - mail order viagra usa

Anonymous said...

generic viagra purchase generic viagra mastercard - can buy viagra dublin

Anonymous said...

viagra online without prescription purchase viagra in the us - buy viagra online cheap us

Anonymous said...

buy soma online soma san diego foster the people - soma bras promotion code

Anonymous said...

buy soma cheap holidays to soma bay egypt - what is soma muscle relaxer

Anonymous said...

soma drug soma muscle relaxant abuse - buy soma no prescription online

Anonymous said...

soma pain soma ultram drug interactions - soma san diego box office hours

Anonymous said...

soma no prescription where to order somatropin - buy soma no prescription online

Anonymous said...

buy soma buy soma online overnight - soma bras gig harbor

Anonymous said...

buy soma online soma drug interactions - generic soma dosage

Anonymous said...

buy soma online smoking soma pills - buy soma fedex

Anonymous said...

Hi, zyban no prescription - zyban without prescription http://www.wellbutrinonlinesale.net/#zyban-without-prescription , [url=http://www.wellbutrinonlinesale.net/#zyban-bupropion ]zyban bupropion [/url]

Anonymous said...

Hi, zyban quit smoking - zyban smoking http://www.wellbutrinonlinesale.net/#zyban-smoking , [url=http://www.wellbutrinonlinesale.net/#zyban-stop-smoking ]zyban stop smoking [/url]

Anonymous said...

Hi, order zyban - zyban drug http://www.wellbutrinonlinesale.net/#zyban-drug , [url=http://www.wellbutrinonlinesale.net/#buy-zyban-online ]buy zyban online [/url]

Anonymous said...

Hi, zyban pills - zyban no prescription http://www.wellbutrinonlinesale.net/#zyban-no-prescription , [url=http://www.wellbutrinonlinesale.net/#zyban-without-prescription ]zyban without prescription [/url]

Anonymous said...

Hi, zyban cost - zyban pills http://www.wellbutrinonlinesale.net/#zyban-pills , [url=http://www.wellbutrinonlinesale.net/#zyban-no-prescription ]zyban no prescription [/url]

Anonymous said...

Extra Borojo Tablets cipro drug - buy ciprofloxacin no prescription http://www.cheapcipromed.net/#buy-ciprofloxacin-no-prescription , [url=http://www.cheapcipromed.net/#cheap-cipro-online ]cheap cipro online [/url]

Anonymous said...

Slippery Drug Dealer order ciprofloxacin online - order ciprofloxacin http://www.cheapcipromed.net/#order-ciprofloxacin , [url=http://www.cheapcipromed.net/#ciprofloxacin-online-pharmacy ]ciprofloxacin online pharmacy [/url]

Anonymous said...

Spinal Medicine For Pain propecia no prescription - finasteride 5mg http://www.propeciahowtosave.net/#finasteride-5mg , finasteride for sale

Anonymous said...

Denis Lehane Drug Dungarvan ciprofloxacin without rx - cipro 500mg http://www.cheapcipromed.net/#cipro-500mg , buy cipro no prescription

Anonymous said...

Drug Education Week Australia School cipro sale - ciprofloxacin without rx http://www.cheapcipromed.net/#ciprofloxacin-without-rx , cipro 500mg

Anonymous said...

buy tramadol cod tramadol xanax alcohol - tramadol withdrawal runny nose

Anonymous said...

Medications For Cardiomyopathy cost of cipro - buy ciprofloxacin online no prescription http://www.cheapcipromed.net/#buy-ciprofloxacin-online-no-prescription , ciprofloxacin online

Anonymous said...

buy cialis online cialis online reliable - best place buy cialis online

Anonymous said...

buy tramadol online tramadol online no prescription usa - buy tramadol online cheap

Anonymous said...

tmd buy sertraline - buy zoloft http://www.zoloftonlinesales.net/#buy-zoloft, [url=http://www.zoloftonlinesales.net/#buy-zoloft]generic zoloft [/url]

Anonymous said...

xanax online 2mg xanax urine - xanax dosage and pictures

Anonymous said...

xanax medication xanax headache - xanax and alcohol use

Anonymous said...

buy tramadol tramadol apap high - tramadol 100 mg withdrawal

Anonymous said...

buy tramadol tramadol with alcohol - tramadol buyers

Anonymous said...

Hello, buy soma without rx - soma 350 mg http://www.californiabarattorneysearch.net/#soma-350-mg , [url=http://www.californiabarattorneysearch.net/#buy-soma-online ]buy soma online [/url]

Anonymous said...

order xanax no prescription xanax side effects bad dreams - online eczane xanax

Anonymous said...

buy carisoprodol carisoprodol 350 mg with alcohol - carisoprodol soma alcohol

Anonymous said...

buy tramadol tramadol hcl 50 mg tab amn - tramadol 50 mg para que es

Anonymous said...

cheapest xanax buy xanax canada pharmacy - buy xanax online no prescription canada

Anonymous said...

buy tramadol online tramadol for dogs how often - can order tramadol online legally

Anonymous said...

buy carisoprodol carisoprodol orange juice - where to buy carisoprodol online

Anonymous said...

buy tramadol tramadol 50mg side effects in dogs - tramadol withdrawal chills

Anonymous said...

Всем привет если Вам нужно разнообразить свой фотошоп, найти что то новое и изумительное, Вам сюда [url=http://psdgif.ru/]Клипарт[/url]

Anonymous said...

buy carisoprodol carisoprodol soma watson brand - carisoprodol buy online no prescription

Anonymous said...

Всем привет если Вам нужно разнообразить свой фотошоп, найти что то новое и изумительное, Вам сюда [url=http://psdgif.ru/]Шрифты[/url]

Anonymous said...

buy cialis online taking 20mg cialis daily - cialis price malaysia

Anonymous said...

6, buy cheap klonopin - buy clonazepam no prescription http://www.klonopinsaleonline.com/#buy-cheap-klonopin, [url=http://www.klonopinsaleonline.com/#klonopin-for-sale]klonopin for sale[/url]

Anonymous said...

buy generic cialis cialis pro reviews - cialis online blog

Anonymous said...

buy cialis online buy cialis online for cheap - cialis online deutschland

Anonymous said...

cialis online cialis rash - cheap cialis in the us

Anonymous said...

buy cialis cheap get coupon cialis - order cialis daily use

Anonymous said...

buy tramadol tramadol vs vicodin - tramadol dosage weight

Anonymous said...

learn how to buy tramdadol order tramadol europe - buy generic tramadol online

Anonymous said...

http://landvoicelearning.com/#44827 tramadol 50 mg 319 - order tramadol cod

Anonymous said...

buy klonopin online klonopin dosage for restless leg syndrome - klonopin 0.125 mg

Anonymous said...

buy tramadol online buy cheapest tramadol online - tramadol tablets

Anonymous said...

clonazepam medication side effects long term klonopin use - buy klonopin overseas

Anonymous said...

buy klonopin online klonopin side effects insomnia - generic for klonopin

Anonymous said...

Салон Секреты Красоты предлагает большой выбор классических салонных услуг: парикмахерские услуги, маникюр, педикюр, косметология, перманентный макияж. Мы работаем более 10 лет и придерживаемся принципа соотношения цены и качества обслуживания. Для постоянных клиентов действуют акции и бонусная система. Заходите на наш сайт [url=http://s-krasoti.ru/] стрижка aldo coppola
[/url]

Anonymous said...

order carisoprodol online carisoprodol 350 mg controlled substance - dosage of carisoprodol

Anonymous said...

http://southcarolinaaccidentattorney.com/#90864 soma 250 mg carisoprodol tablets - long carisoprodol your system

Anonymous said...

carisoprodol 350 mg carisoprodol from usa - soma carisoprodol 500mg

Anonymous said...

Хотите Скачать филмы быстро и бесплатно, Вам сюда [url=http://expresskino.ru/]Хоббит: Нежданное путешествие[/url]

Anonymous said...

Производственная компания «М-СЕТ» специализируется на производстве сварных сеток в рулонах, имеющих широкое применение в различных строительных работах.
Производство сварной сетки выполняется на многоточечных сварных машинах, методом контактно-точечной сварки крестообразных соединений. Все пересечения и стыки прутьев тщательно сварены, благодаря чему конструкция отличается превосходным качеством и является одной из самых прочных.
На нашем сайте Вы можете посмотреть образцы нашей продукции и связаться с нами
[url=http://setka-vlg.ru/]сетка сварная штукатурная фасадная цена
[/url]

Anonymous said...

Yοu coulԁ definitеly ѕee yοur
eхpеrtіsе in the аrtiсle you
wгite. Τhe ωorlԁ hoρes
fοr еven more pаsѕiοnatе writеrs such as you who aгen't afraid to mention how they believe. Always go after your heart.

Here is my web blog frontier internet

Anonymous said...

Уже в этом году популярнаяигрушка среди многих поколений Counter-Strike празднует свой маленький «юбилей» - 14 лет. Между прочим, Контра является одним из самых известных шутеров, и пользуются ею множество человек ежедневно со всего света.
[url=http://cs-sborka.ru/]cs 1 6 wh opengl32 скачать[/url]

И если раньше вы не могли скачать игрушку в Сети в свободном доступе, то сегодня, например, на нашем ресурсе, вы сделаете это без труда. И что главное – вообще бесплатно.
[url=http://cs-sborka.ru/]скачать cs 1 6 rus[/url]

Между прочим, история ее разработки была очень интересной и весьма оригинальной. Так, в конце 20 века двое известных разработчиков приступили к разработкам. И мало кто знал в тот момент, что буквально через пару лет игра станет столь известной по всей Земле. Правда, у одного из создателей, имеющего прозвище «Гусятник», уже был аналогичный опыт – известная стрелялка «Quake 2». В марте того же года разработка получила свое название, а первая пробная версия вышла уже летом. Тогда все пользователи ринулись ее испытывать, и интерес к игрушке не истек до сих пор. А все потому, что пользователи, которые так ее любят, имеют все, что нам пообещали авторы.
[url=http://cs-sborka.ru/]скачать cs 1 6 оригинал бесплатно[/url]

Теперь вы сможете скачать игрушку на нашем ресурсе без труда, прохождения регистрации и без материальных затрат.
[url=http://cs-sborka.ru/]скачать cs 1 6 без смс[/url]