模版控件能讓用戶幾乎不用花費任何時間就創建出復雜的用戶界面. asp.net有很多控件都使用了模版技術(datagrid就是一個例子). 而這些控件都工作得很好, 通常, 模版可以被保存為ascx文件以增加復用性. 很有可能, 事前你是不知道你的控件是怎么布局的, 而且你需要動態的添加一些模版以應付不同的事件.
使用模版的另一個優勢,就是它們能動態的添加到你的控件里面去. 這樣的話, 你可以事先設計好模版, 然后通過簡單的幾行代碼就添加到你的控件中.
下面這篇文章就要告訴你如何如何一步步的添加一個動態的itemtemplate和edititemtemplate到datagrid中. 另外, 還會告訴你怎么獲取和更新用戶對edititemtemplate所做的改變. 例子將會是很簡單的. 然后, 我很快就會在tripleasp上面正式發布一個改進后的tableeditor版本. 這個版本將更好的說明如何使用動態模版.
itempalte的實現
為了能動態的添加itemtemplate和edititemtemplate, 我們需要創建2個類來實現itemplate的接口(interface). 第一個類是genericitem. 這個類的主要工作就是: 取數據源的列名, 創建一個文本控件(literal contral), 為這個文本控件賦值, 最后把這個文本控件加到父控件(在這里父控件就是datagrid了).
到目前為止還是很順利. 在繼續下面的討論之前, 我們來看看代碼和完成的步驟.
using system;
using system.web;
using system.data; using system.web.ui;
using system.web.ui.webcontrols;
namespace tripleasp.itemtemplates
{
/// <summary>
/// summary description for genericitem.
/// </summary>
public class genericitem : itemplate
{
private string column;
//private bool validate;
public genericitem(string column)
{
this.column = column;
}
public void instantiatein(control container)
{
literal l = new literal();
l.databinding += new eventhandler(this.binddata);
container.controls.add(l);
}
public void binddata(object sender, eventargs e)
{
literal l = (literal) sender;
datagriditem container = (datagriditem) l.namingcontainer;
l.text = ((datarowview) container.dataitem)[column].tostring();
}
}
}
正如你看到的, genericitem類實現了itemplate的接口(interface). 因為我們是實現接口, 所以必須包括instantiatein這個方法. 這個方法是用來定義所有子控件和模版所屬的控件對象的. 在這個方法里面, 我們創建了一個新的literal控件來保存datagrid的單元值. 接著, 我們添加了databinding事件處理函數. 這個事件處理函數實際上就是在datagrid綁定數據的時候, 把單元值放到literal控件的text屬性中. 最后, 把這個literal控件加入到控件的容器集合中. 很簡單吧?
動態edititemtemplate
動態edititemtemplate類validateedititem跟genericitem很類似, 但是有3個地方不同.
第一個不同的地方是, 我們添加的是textbox控件而不是literal控件. 這樣的話, 在編輯模式下, 用戶可以做任何修改.
第二個不同的地方, 你會發現我們會顯式地命名控件. 這會使我們能夠獲取更新事件中的任何數據變化.
最后一個不同, 你會看到一個跟textbox相聯系的requiredfieldvalidator控件. 這是可選的. 但是, 這的確讓你知道有些事是可以這樣做的.
下面就是validateedititem的代碼:
using system;
using system.data;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web;
namespace tripleasp.itemtemplates
{
/// <summary>
/// summary description for validateedititem.
/// </summary>
public class validateedititem : itemplate
{
private string column;
public validateedititem(string column)
{
this.column = column;
}
public void instantiatein(control container)
{
textbox tb = new textbox();
tb.databinding += new eventhandler(this.binddata);
container.controls.add(tb);
tb.id = column;
requiredfieldvalidator rfv = new requiredfieldvalidator();
rfv.text = "please answer";
rfv.controltovalidate = tb.id;
rfv.display = validatordisplay.dynamic;
rfv.id = "validate" + tb.id;
container.controls.add(rfv);
}
public void binddata(object sender, eventargs e)
{
textbox tb = (textbox) sender;
datagriditem container = (datagriditem)tb.namingcontainer;
tb.text = ((datarowview) container.dataitem)[column].tostring();
}
}
}
動態模版的實現
現在我們已經有兩個實現了itempalte接口的類了. 一切準備好了! 我們現在要做的就是把它們加入到我們的datagrid里面.
我們把binddata和dynamiccolumns兩個方法放在一起. binddata主要是創建sql查詢語句, 往datagrid添加列(動態列), 然后把數據表綁定到datagrid.
void binddata()
{
string sql = "select * from publishers where state is not null";
datagrid1.columns.add(dynamiccolumns("pub_id",false));
datagrid1.columns.add(dynamiccolumns("pub_name",true));
datagrid1.columns.add(dynamiccolumns("city",true));
datagrid1.columns.add(dynamiccolumns("state",true));
datagrid1.columns.add(dynamiccolumns("country",true));
datagrid1.datakeyfield = "pub_id";
datagrid1.datasource = getdatatable(sql);
datagrid1.databind();
}
dynamiccolumns有兩個參數: column(字符類型)和iseditable(布爾類型). column變量當然就是我們要加入templatecolumn的列名. iseditable變量是用作測試的, 如果我們希望這個列是允許編輯的話.
protected templatecolumn dynamiccolumns(string column, bool iseditable)
{
templatecolumn genericcolumn = new templatecolumn();
genericcolumn.headertext = column;
genericcolumn.itemtemplate = new genericitem(column);
if(iseditable)
{
genericcolumn.edititemtemplate = new validateedititem(column);
}
return genericcolumn;
}
正如你所看到的, 首先我們實例化一個templatecolumn(genericcolumn), 根據我們要添加的列的名字設置headertext屬性(當然,你可以設置為任何東西都可以). 接著, 我們通過添加新的genericitem的參考(reference), 把itemtemplate添加到genericcolumn, 并把名稱傳入. 最后, 我們必須檢查iseditable, 以便看看我們需不需要允許編輯這個列. 如果為真, 我們要往validateedititem添加新的參考, 而且把列名也傳過去.
datagrid事件
我們的編輯和取消事件是很標準的. 你有可能已經看過它們100遍了. 在我們的編輯事件里面, 我們簡單地取出被選中的行的編號, 然后重新綁定數據.
protected void edit_click(object sender, datagridcommandeventargs e)
{
datagrid1.edititemindex = e.item.itemindex;
binddata();
}
我們的取消事件是把當前所選行號設為-1. 這樣就等于告訴datagrid, 不在是編輯模式了. 然后, 我們重新綁定數據.
protected void cancel_click(object sender, datagridcommandeventargs e)
{
datagrid1.edititemindex = -1;
binddata();
}
更新事件會跟你以前看到的有一點點不同. 然而, 它卻會讓你想起你在asp的日子.
protected void update_click(object sender, datagridcommandeventargs e)
{
//gets the uniqueid that is attached to the front of each textbox
//dyamically added to our datagrid's edititemtempate
string uid = e.item.uniqueid + ":";
string pub_id = (string)datagrid1.datakeys[e.item.itemindex];
string pub_name = (request.form[uid + "pub_name"].tostring());
string city = (request.form[uid + "city"].tostring());
string state = (request.form[uid + "state"].tostring());
string country = (request.form[uid + "country"].tostring());
//simple method to update db
updaterecord(pub_id,pub_name,city,state,country);
datagrid1.edititemindex = -1;
binddata();
}
這樣的話, edititemtemplate就硬編碼到頁面中去了. 你可能已經看過一些取表單提交數據的例子, 其中的方法, 或者是通過控件位置取值, 或者是控件名稱取值. 但是, 如果你是在運行時創建控件, 那么, 在postback的時候, asp.net是無法取得這些值的. 為此, 我們只能通過request.form的方法來得到這些值.
在你開始在validateedititem類里面仔細尋找被小心命名的textbox的時候, 你必須記住, asp.net已經為控件的名字沖突做了預防措施. 一般來說, 這包括增加每個datagrid父控件的名稱, datagrid本身的名稱, 和一個代表每個textbox的序號的字符串放在textbox的id前面. 我們可以大量的使用這樣的方法. 但是這并不保證我們的代碼絕對的模塊化和可復用. 相反, 我們檢查datagridcommandeventargs.item.uniqueid 并在尾部加上":". 有了這個uniqueid, 我們就可以安全地取得textbox里面的編輯數據, 并更新到數據庫.
結論
動態添加模版到你的模版控件會在開始的時候增加一點點的工作量. 但是, 一旦你建立了一系列的優秀的模版類, 你會發現, 實現itemplate會非常的快速和容易. 它運行你建立強大的控件來滿足你數據操作的需要. 如果你需要更好的例子, 請看我即將發布在tripleasp的tableeditor控件.