using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
public partial class jQueryAutoComp_ACDataSrc : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//使用者目前輸入的文字預設以q傳入
string q = Request["q"] ?? "";
if (q.Length > 0)
{
DataTable t = getStockData();
DataView dv = new DataView(t);
//利用LIKE做查詢
dv.RowFilter = "Key LIKE '" + q.Replace("'", "''") + "%'";
dv.Sort = "Key, Symbol";
List<string> lst = new List<string>();
lst.Add("");
foreach (DataRowView drv in dv)
{
DataRow r = drv.Row;
//組裝出前端要用的欄位
lst.Add(string.Format("{0}|{1}|{2}", r["key"], r["symbol"], r["cname"]));
if (lst.Count >= 10) break;
}
//每筆資料間以換行分隔
Response.Write(string.Join("\n", lst.ToArray()));
}
}
private DataTable getStockData()
{
#region 股票代號
string rawData = @"
1435 中福 C.F.C.Y.CORP.
1437 勤益 GTM
...省略...
8249 菱光 CSI
9912 偉聯 AIC";
#endregion
//如果資料量未多到誇張,將DataTable Cached住
string CACHE_KEY = "StkTable";
if (Cache[CACHE_KEY] == null)
{
DataTable t = new DataTable();
t.Columns.Add("Key", typeof(string));
t.Columns.Add("Symbol", typeof(string));
t.Columns.Add("CName", typeof(string));
t.Columns.Add("EName", typeof(string));
//測試時由字串取得資料,實務上會去查DB
StringReader sr = new StringReader(rawData);
string line = null;
while ((line = sr.ReadLine()) != null)
{
string[] p = line.Split('\t');
if (p.Length != 3) continue;
//分別以Symbol, CName, EName作Key
//輸入中英文及代號都可以查
t.Rows.Add(p[0], p[0], p[1], p[2]);
t.Rows.Add(p[1], p[0], p[1], p[2]);
t.Rows.Add(p[2], p[0], p[1], p[2]);
}
//放入Cache,保存兩小時
Cache.Add(CACHE_KEY, t, null, DateTime.Now.AddHours(2),
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.Normal, null);
}
return Cache[CACHE_KEY] as DataTable;
}
}