2011年5月2日 星期一

.NET 2.0 GridView RowCommand

我們常常需要再GridView裡面加入Controls,例如LinkButton, ImageButton之類的,
,只要設定CommandName屬性,便可使區分各種不同的Control所引發的事件

加入Button的方法可能有:

1. 使用TemplateField
 <asp:TemplateField HeaderText="規劃案號" SortExpression="planno" ItemStyle-Width="20%">

<ItemTemplate>

<asp:LinkButton runat="server" Text='<%# Eval("planno") %>' CommandName="Select"
CommandArgument='<%# Eval("planno") %>'></asp:LinkButton>

</ItemTemplate>

</asp:TemplateField>

2. 使用ButtonField
<asp:ButtonField HeaderText="規劃案號" ButtonType="Link" DataTextField="planno"
SortExpression="planno"

CommandName="Select" ItemStyle-Width="20%" />

問題:

.NET 1.x的DataGrid: 可以使用ItemCommand event handler的e.Item.ItemIndex這樣的語法來獲得目前的RowIndex
.NET 2.0的GridView: 其RowCommand event handler並沒有相對應於ItemIndex這樣的屬性

解決方法:

1. 使用第一種方法(assuming ImageButton Control is used)

int rowIndex = ((GridViewRow)((ImageButton)e.CommandSource).NamingContainer).RowIndex;

或是(assuming LinkButton is used)

int rowindex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex

便可取得所需的row index了

2. 使用第二種方式

則e.CommandArgument便可取得RowIndex了,不過缺點是這個方法就沒辦法另外加CommandArgument

另外一個解決方式:

在RowCreated event handler中將屬於每一行的RowIndex給指定到CommandArgument中,便可以在之後的RowCommand event handler裡面使用e.CommandArgument來直接取得RowIndex了,這樣做的缺點是,如果你有其他的參數想要指定給CommandArgument的話,就沒辦法了

參考網頁:
http://www.cnblogs.com/oomusou/archive/2007/06/26/796094.html
http://msdn2.microsoft.com/zh-tw/library/system.web.ui.webcontrols.gridview.rowcreated(VS.80).aspx

沒有留言:

張貼留言