(原創) 如何獲得GridView內LinkButton的RowIndex? (.NET) (ASP.NET)

Abstract
  在.NET 1.x的DataGrid,可以在ItemCommand event的e.Item.ItemIndex獲得目前的RowIndex,但在.NET 2.0的GridView,卻無法使用這種方式在RowCommand event獲得RowIndex。

Motivation
  為什麼需要在RowCommand event獲得RowIndex呢?通常一個Table的PK或FK並不會顯示在GridView上,而會設定在DataKeyNames property,然後再RowCommand event根據RowIndex讀出該row的PK或FK,所以第一步,必須先能在RowCommand獲得目前的RowIndex。

Introduction

.NET 1.x DataGrid
在.NET 1.x的DataGrid,若要使用LinkButton,一樣得放在TemplateColumn內,且ItemCommand event的e.Item.ItemIndex就可抓到RowIndex。

當在DataGrid點下FirstName後,會在下方的Label顯示LastName,LastName是此例的DataKey。


 1 ExpandedBlockStart.gif ContractedBlock.gif <% dot.gif @ Import Namespace="System.Data"  %>
 2 ExpandedBlockStart.gifContractedBlock.gif <% dot.gif @ Import Namespace="System.Data.SqlClient"  %>
 3 None.gif
 4 ExpandedBlockStart.gifContractedBlock.gif <% dot.gif @ Page Language="C#"  %>
 5 None.gif
 6 None.gif <! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
 7 None.gif
 8 ExpandedBlockStart.gifContractedBlock.gif < script  runat ="server" > dot.gif
 9ExpandedSubBlockStart.gifContractedSubBlock.gif/**//* 
10InBlock.gif(C) OOMusou 2007 http://oomusou.cnblogs.com
11InBlock.gif
12InBlock.gifFilename    : DataGrid_DataKeyField.aspx
13InBlock.gifCompiler    : Visual Studio 2005 / C# 2.0 / ASP.NET 2.0
14InBlock.gifDescription : Demo how to get RowIndex in DataGrid's LinkButton
15InBlock.gifRelease     : 06/26/2007 1.0
16ExpandedSubBlockEnd.gif*/

17ExpandedSubBlockStart.gifContractedSubBlock.gif  protected void Page_Load(object sender, EventArgs e) dot.gif{
18InBlock.gif    if (!IsPostBack) 
19InBlock.gif      DataGrid1_DataBind();
20ExpandedSubBlockEnd.gif  }

21InBlock.gif
22ExpandedSubBlockStart.gifContractedSubBlock.gif  protected void DataGrid1_DataBind() dot.gif{
23InBlock.gif    string strSQL = "SELECT TOP 10 " +
24InBlock.gif                           "fname," +
25InBlock.gif                           "lname " +
26InBlock.gif                    "FROM employee";
27InBlock.gif    SqlConnection con = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=pubs;Integrated Security=True");
28InBlock.gif    SqlDataAdapter da = new SqlDataAdapter(strSQL, con);
29InBlock.gif    DataSet ds = new DataSet();
30InBlock.gif
31ExpandedSubBlockStart.gifContractedSubBlock.gif    try dot.gif{
32InBlock.gif      da.Fill(ds);
33ExpandedSubBlockEnd.gif    }

34ExpandedSubBlockStart.gifContractedSubBlock.gif    catch (Exception err) dot.gif{
35InBlock.gif      Response.Write(err.ToString());
36InBlock.gif      return;
37ExpandedSubBlockEnd.gif    }

38ExpandedSubBlockStart.gifContractedSubBlock.gif    finally dot.gif{
39InBlock.gif      if ((con != null&& (con.State == ConnectionState.Open))
40InBlock.gif        con.Close();
41ExpandedSubBlockEnd.gif    }

42InBlock.gif
43InBlock.gif    DataGrid1.DataSource = ds;
44InBlock.gif    DataGrid1.DataKeyField = "lname";
45InBlock.gif    DataGrid1.AutoGenerateColumns = false;
46InBlock.gif    DataGrid1.DataBind();
47ExpandedSubBlockEnd.gif  }

48InBlock.gif
49ExpandedSubBlockStart.gifContractedSubBlock.gif  protected void DataGrid1_ItemCommand(object source, DataGridCommandEventArgs e) dot.gif{
50InBlock.gif    if (e.CommandName == "Select")
51InBlock.gif      Label1.Text = DataGrid1.DataKeys[e.Item.ItemIndex].ToString();
52ExpandedBlockEnd.gif  }

53None.gif
</ script >
54 None.gif
55 None.gif < html  xmlns ="http://www.w3.org/1999/xhtml" >
56 None.gif < head  runat ="server" >
57 None.gif   < title > Untitled Page </ title >
58 None.gif </ head >
59 None.gif < body >
60 None.gif   < form  id ="form1"  runat ="server" >
61 None.gif     < asp:DataGrid  ID ="DataGrid1"  runat ="server"  OnItemCommand ="DataGrid1_ItemCommand" >
62 None.gif       < Columns >
63 None.gif         < asp:TemplateColumn  HeaderText ="First Name" >
64 None.gif           < ItemTemplate >
65 None.gif             < asp:LinkButton  ID ="LinkButton1"  runat ="server"  CommandName ="Select"  Text ='<%#DataBinder.Eval(Container.DataItem,"fname")% > '>
66 None.gif             </ asp:LinkButton >
67 None.gif           </ ItemTemplate >
68 None.gif         </ asp:TemplateColumn >
69 None.gif       </ Columns >
70 None.gif     </ asp:DataGrid >
71 None.gif     < asp:Label  ID ="Label1"  runat ="server" ></ asp:Label >
72 None.gif   </ form >
73 None.gif </ body >
74 None.gif </ html >


51行

1 ExpandedBlockStart.gif ContractedBlock.gif protected   void  DataGrid1_ItemCommand( object  source, DataGridCommandEventArgs e)  dot.gif {
2InBlock.gif    if (e.CommandName == "Select")
3InBlock.gif      Label1.Text = DataGrid1.DataKeys[e.Item.ItemIndex].ToString();
4ExpandedBlockEnd.gif}

5 None.gif


只需在ItemCommand event的e.Item.ItemIndex就可以輕鬆的抓到RowIndex。

.NET 2.0 GridView
.NET 2.0就改用SqlDataSource和GridView了,LinkButtom一樣得放在TemplateField,但GridView沒有ItemCommand event,取而代之的是RowCommand event。

 1 ExpandedBlockStart.gif ContractedBlock.gif <% dot.gif @ Page Language="C#"  %>
 2 None.gif
 3 None.gif <! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
 4 None.gif
 5 ExpandedBlockStart.gifContractedBlock.gif < script  runat ="server" > dot.gif
 6ExpandedSubBlockStart.gifContractedSubBlock.gif /**//* 
 7InBlock.gif(C) OOMusou 2007 http://oomusou.cnblogs.com
 8InBlock.gif
 9InBlock.gifFilename    : GridView_RowCommand_RowIndex.aspx
10InBlock.gifCompiler    : Visual Studio 2005 / C# 2.0 / ASP.NET 2.0
11InBlock.gifDescription : Demo how to get RowIndex in GridView's LinkButton
12InBlock.gifRelease     : 06/26/2007 1.0
13ExpandedSubBlockEnd.gif*/

14ExpandedSubBlockStart.gifContractedSubBlock.gif  protected void Page_Load(object sender, EventArgs e) dot.gif{
15InBlock.gif    if (!IsPostBack)
16InBlock.gif      GridView1_DataBind();
17ExpandedSubBlockEnd.gif  }

18InBlock.gif
19ExpandedSubBlockStart.gifContractedSubBlock.gif  protected void GridView1_DataBind() dot.gif{
20InBlock.gif    SqlDataSource1.ConnectionString = @"Data Source=.\sqlexpress;Initial Catalog=pubs;Integrated Security=True";
21InBlock.gif    SqlDataSource1.SelectCommand = "SELECT TOP 10 " +
22InBlock.gif                                          "fname," +
23InBlock.gif                                          "lname " +
24InBlock.gif                                   "FROM employee";
25InBlock.gif    GridView1.DataSourceID = SqlDataSource1.ID;
26ExpandedSubBlockStart.gifContractedSubBlock.gif    GridView1.DataKeyNames = new string[] dot.gif"lname" };
27InBlock.gif    GridView1.AutoGenerateColumns = false;
28ExpandedSubBlockEnd.gif  }

29InBlock.gif
30ExpandedSubBlockStart.gifContractedSubBlock.gif  protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) dot.gif{
31ExpandedSubBlockStart.gifContractedSubBlock.gif    if (e.CommandName == "Select"dot.gif{
32InBlock.gif      int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
33InBlock.gif      Label1.Text = GridView1.DataKeys[rowIndex].Value.ToString();
34ExpandedSubBlockEnd.gif    }

35ExpandedBlockEnd.gif  }

36None.gif
</ script >
37 None.gif
38 None.gif < html  xmlns ="http://www.w3.org/1999/xhtml" >
39 None.gif < head  runat ="server" >
40 None.gif   < title > Untitled Page </ title >
41 None.gif </ head >
42 None.gif < body >
43 None.gif   < form  id ="form1"  runat ="server" >
44 None.gif     < div >
45 None.gif       < asp:GridView  ID ="GridView1"  runat ="server"  OnRowCommand ="GridView1_RowCommand" >
46 None.gif         < Columns >
47 None.gif           < asp:TemplateField  HeaderText ="First Name" >
48 None.gif             < ItemTemplate >
49 None.gif               < asp:LinkButton  ID ="LinkButton1"  runat ="server"  CommandName ="Select"  Text ='<%#Eval("fname")% > '> </ asp:LinkButton >
50 None.gif             </ ItemTemplate >
51 None.gif           </ asp:TemplateField >
52 None.gif         </ Columns >
53 None.gif       </ asp:GridView >
54 None.gif     </ div >
55 None.gif     < asp:Label  ID ="Label1"  runat ="server" ></ asp:Label >
56 None.gif     < asp:SqlDataSource  ID ="SqlDataSource1"  runat ="server" ></ asp:SqlDataSource >
57 None.gif   </ form >
58 None.gif </ body >
59 None.gif </ html >


最難理解的應該是32行

None.gif int  rowIndex  =  ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;


e.CommandSource傳的是按下去的LinkButton,不過由於傳回的是Object,就得自行轉成LinkButton,但由於我們想知道的是RowIndex,而LinkButton是包含在GridViewRow內,所以透過NamingContainer傳回目前的GridViewRow,但傳回的是Control,所以需在轉成GridViewRow後才能有RowIndex property。

Conclusion
GridView是DataGrid的繼承人,但不少寫法和DataGrid並不一樣,GridView很多地方比DataGrid更強更好用,但這個例子卻發現GridView比DataGrid麻煩些,或許我沒找到好最好的方法,若有人有更好的方式,歡迎指正,謝謝。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值