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

52 comments:

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.

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

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://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...

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

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...

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 medication xanax headache - xanax and alcohol use

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...

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...

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...

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