Hidden field in ListView, for my Guid, or just hidden field.

Their are many times developer bind their data from database to the user interface and we wants to know what the user has chosen.

But in the meantime, the user will never wants to see the Guid. So what we need is a hidden field or a branch of hidden fields.

If you try to do this by a label with Visible=”false”. You won’t get what you want. Because ASP will just skip rendering not visible controls. They don’t even exist in your user interface.

We should use HiddenField and assign the Guid to its value. I do this in my ListView template and get the Guid back by FindControl().

開發網頁系統時,很常把資料庫的資料跟介面結合,然後我們想知道使用者選了甚麼項目,勾了那一行裡的checkbox. 但同時我們不想使用者在介面上看到Guid. 所以我們需要隱藏欄位.

如果你把Guid放在一個Label並設定Visible為false,那並不能成為一個隱藏欄位,ASP會在繪制UI時就不會繪Visible為false的控制項,它不存在你也取不出Guid.所以我們應該產生一個HiddenField控制項,把Guid存進去它的value. 我在我的ListView裡的每一行加一個HiddenField,再用FindControl()把Guid取回來.


ListView with dynamic template in action

In the previous article “Keep it MVC. Use templated controls without injecting Eval() in your aspx” I write about how to implement dynamic template. Now let’s look at how to use them.

There are a few things we should know before using template and ListView.

1. There are build-in action you can use. What I mean build-in is, you can assign some pre-defined CommandName to your control inside your ListView, such as a LinkButton, then if you assign CommandName=”Edit” to it, the event you should be handling when that button is being click is ListView.Onitemediting. Here is the list of build-in CommandName I know and the event handler which handle them.



1. ListView有一些內建的事件可以用,內建的意思是你只要在ListView裡的控制項設定適當的CommandName就能喚起對應該事件.例如一個LinkButton,如果你把它的CommandName設為Edit,當它被Click時,會喚起ListView的Onitemediting事件.下面是一部份常用的內建CommandName及其對應的事件.

CommandName Event Handler
Insert oniteminserting
Edit onitemediting
Update onitemupdating
Delete onitemdeleting
Cancel onitemcanceling

There should be more, but these are enough for us to discuss.

After we have the template and took care of LayoutTemplate. We have to assign the template to our ListView.



protected void Page_Init(object sender, EventArgs e)
            ltv_webpages.ItemTemplate = new WebpageListViewTemplate(ListViewTemplateType.ItemTemplate);
            ltv_webpages.AlternatingItemTemplate = new WebpageListViewTemplate(ListViewTemplateType.AlternatingItemTemplate);
            ltv_webpages.EditItemTemplate = new WebpageListViewTemplate(ListViewTemplateType.EditItemTemplate);
            ltv_webpages.InsertItemTemplate = new WebpageListViewTemplate(ListViewTemplateType.InsertItemTemplate);

We have to do this in Page_Init(). If you do this in Page_Load(), you will get a template not define error. If you want to know why this happen, it is because .NET will create and initialize all controls object before Page_Load() is reach. Take a look at any ASP page life cycle tutorial if you want to know more about this.

Then we have to bind data to the ListView. You can bind it in Page_Load(), but doing this, when you add a DataPager to your ListView, it won’t work properly. So, we should do the binding in Page_PreRender().

我們要在Page_Init()做這個動作,如果你在Page_Load()裡做這個動作,你會得到一個缺少模板定義的錯誤.如果想知道為甚麼會這樣,可以去看一下.NET的Page life cycle.在Page_Load()前就會建立好所有控制項.


protected void Page_PreRender(object sender, EventArgs e)
            ltv_webpages.DataSource = WebpageDA.GetAllPageInformation();

Then, the last thing, inserting, editing and deleting data in ListView.


1. Insert, set the ListView.InsertItemPosition to InsertItemPosition.FirstItem or InsertItemPosition.LastItem. This will make the InsertItemTemplate appears as the first or last item in the ListView. Then after you read the user input and done the inserting. assign InsertItemPosition.None to ListView.InsertItemPosition. Then the insertItemTemplate will be gone.

1. 新增,設定ListView.InsertItemPosition為InsertItemPosition.FirstItem或InsertItemPosition.LastItem其中一個. 這樣InsertItemTemplate就會出現在你設定的位置. 在完成加入動作後,把InsertItemPosition設為InsertItemPosition.None. InsertITemTemplate就會消失.

2. Editing, assign the index of which you wants to edit to ListView.EditIndex.

2. 修改, 把你想要修改的行數指定給ListView.EditIndex.

protected void ltv_webpages_ItemEditing(object sender, ListViewEditEventArgs e)
            ltv_webpages.EditIndex = e.NewEditIndex;

3. Canceling, you have to handle two canceling, edit canceling and insert canceling. by setting EditIndex to -1 or InsertItemPosition to None.

3. 取消, 你要處理兩種取消,修改取消和新增取消,把EditIndex設成-1,把InsertItemPosition設為None.

protected void ltv_webpages_ItemCanceling(object sender, ListViewCancelEventArgs e)
            if (e.CancelMode == ListViewCancelMode.CancelingEdit)
                ltv_webpages.EditIndex = -1;
            else if (e.CancelMode == ListViewCancelMode.CancelingInsert)
                ltv_webpages.InsertItemPosition = InsertItemPosition.None;

If you want some custom command, CommandName = “YourCommand”, the use a switch in onitemcommand event handler to handle it.

This pretty much wrap everything common up. I will post sample code when I could.

See you next time.

如果你想用自訂的指令, CommandName=”YourCommand”, 然後你可以在Onitemcommand裡用一個Switch去處理不同的Command.


compareValidator use with DateTime

I have been refactoring my colleague code recently. His code does the following, get user filter inputs and two dates for defining data within that two dates is retrieved.
I told him to use the AjaxToolKit calendarExtender and he did. He then does a lot checking in server-side to validate the user input dates. It is okay but with two points I think we can make some improvement.We should have client-side validation to improve user experience and clean up those code-behide checkings cause those if…return is making a big mess.

I rather use the compareValidator to do those dirty work for me and so I do. Here is two common techniques, check if the date is validate and check the begin date must be previous to the end date.

1. Check validate date : Type=”Date” and Operator=”DateTypeCheck”

<asp:CompareValidator ID="vld_startDate" runat="server" ErrorMessage="invalid date format" Type="Date"
                        Operator="DataTypeCheck" ControlToValidate="tb_startDate"></asp:CompareValidator>

2. Compare two date : Type=”Date”, Operator=”LessThanEqual”, i.e ControlToValidate LessThanEqual to ControlToCompare

<asp:CompareValidator ID="vld_compareDate" runat="server" ErrorMessage="begin date must be smaller than end date"
                        Type="Date" ControlToValidate="tb_startDate" ControlToCompare="tb_endDate" Operator="LessThanEqual"></asp:CompareValidator>

These techniques are simple but comes handy when you need them. Cheers.