2014年3月26日 星期三

[轉貼] ASP.NET 神奇FindControl方法

出處:http://weisnote.blogspot.tw/2012/03/aspnet-findcontrol.html

說到ASP.NET最常用的方法,FindControl一定有被提名
平常在用沒什麼就這樣就OK

TextBox tb = this.Page.FindControl("TextBox1") as TextBox;


之後想幹嘛就幹嘛
但是如果有套用主版頁面的話這方法就失靈囉,總是見到怒毆大神,然後就怒毆電腦
正解如下

TextBox tb = this.Master.FindControl("ContentPlaceHolder1").FindControl("TextBox1") as TextBox;


先用 this.Master 選到主版,在慢慢向下一層層找
對,這方法很邪門不像 WinFrom 的 Control.ControlCollection.Find 方法,有第二個參數
對於有套主版或者像是 GridView ItemTemplate 裡面的都無法找到
假如有2個都叫TextBox1的鬼東西
一般得這麼做才能對他操作
如果還有用巢狀主版的話,好不好玩?
佐藤ポヨ表示:自己寫個 擴充方法 吧
在類別庫建立個靜態類別寫擴充方法
擴充方法細則參閱MSDN
把類別加入參考後,Control 就能用 doFindControl 跟 doFindControls 擴充方法
使用方式
好啦,地獄兩百層的控制項也能Find了

2014年3月6日 星期四

[轉貼] 利用存儲過程實現模糊查詢

出處:http://www.oschina.net/code/snippet_222150_32766

1. [代碼]建表腳本     

01USE [TestDB]
02GO
03 
04/****** Object:  Table [dbo].[tblCustomer]    Script Date: 01/18/2014 22:01:53 ******/
05SET ANSI_NULLS ON
06GO
07 
08SET QUOTED_IDENTIFIER ON
09GO
10 
11CREATE TABLE [dbo].[tblCustomer](
12    [id] [int] IDENTITY(1,1) NOT NULL,
13    [name] [nvarchar](100) NULL,
14    [dat] [date] NULL
15) ON [PRIMARY]
16 
17GO

2. [文件] SearchCustomer.sql ~ 182B     下載(1)     

1CREATE PROCEDURE SearchCustomer
2    -- Add the parameters for the stored procedure here
3    @name nvarchar(100)
4 
5AS
6    SELECT FROM dbo.tblCustomer WHERE name LIKE '%'+@name+'%'
7GO

3. [代碼]模糊搜索代碼     跳至 [1] [2] [3] [全屏預覽]

01using (SqlConnection cn = newSqlConnection("Server=localhost;Database=TestDB;Trusted_Connection=True;"))
02{
03    cn.Open();
04    string str = "關鍵字";
05    //str = null;
06    SqlCommand cmd = new SqlCommand("SearchCustomer", cn);
07    cmd.CommandType = CommandType.StoredProcedure;
08    DataTable dt = new DataTable();
09    SqlDataAdapter da = new SqlDataAdapter(cmd);
10    da.SelectCommand.Parameters.Add("@name", SqlDbType.NVarChar).Value = str;
11    da.Fill(dt);
12    Debug.Assert(dt.Rows.Count > 0);
13    GridView1.DataSource=dt;
14    GridView1.Bind();
15    cn.Close();
16}