很多時候我們需要在GridView的RowCommand之類的事件中需要擷取目前行的一些關聯性的資料值。但這些資料值又沒有直接展現在GridView的列中。這個時候該怎麼辦呢?
有同學喜歡用隐藏列的方式,把需要使用但不顯示的字段綁定到此列上,同時設定列寬為0或不顯示,使用時可以用正常的取某行某列的方式來擷取資料。
但是在Framework
2.0中,我們可以采用DataKeyNames的方式來擷取此類資料。
代碼示例:
(前台)

<asp:GridView ID="GridView1" runat="server" DataKeyNames="Grup" OnRowCommand="GridView1_RowCommand" AutoGenerateColumns="False">

<Columns>

<asp:TemplateField>

<ItemTemplate>

<asp:Label ID="Label1" runat="server" Text='<%#Eval("GrupName") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:ButtonField Text="按鈕" />

</Columns>

</asp:GridView>
Grup 為我們想使用但不需要顯示的列。(如果有多個字段,使用逗号分開)
(背景)

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack )
DataTable dt = new DataTable();
dt.Columns.Add("Grup");
dt.Columns.Add("GrupName");
dt.Rows.Add(new object[]
{ 0,"營業部" });
{ 1,"市場部" });
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
}
}


protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
// 擷取目前行索引
int index = Convert.ToInt32(e.CommandArgument);
// 取出目前行資料鍵值對象中的值
string strGrup = ((GridView)sender).DataKeys[index].Values["Grup"].ToString();
順便補充一句。
如果你使用模闆列中放置按鈕控件的方式,要想在按鈕事件中擷取這種字段值就更簡單了。
隻需要在按鈕的CommandArgument屬性設定為想綁定的字段,如:

<asp:TemplateField>

<ItemTemplate>

<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Button" CommandArgument=' <%#Eval("Grup") %>' />

</ItemTemplate>

</asp:TemplateField>
按鈕事件中如是寫:

protected void Button2_Click(object sender, EventArgs e)
{
string strGrup = ((Button)sender).CommandArgument.ToString();
}