[GridView]在 RowCommand事件中,自訂的Button 如何取出某一列(RowIndex) 的索引值#2 -- e.CommandSource

摘要:[GridView]在 RowCommand事件中,自訂的Button 如何取出某一列(RowIndex) 的索引值#2 -- e.CommandSource

GridView的 RowCommand事件
討論 GridViewCommandEventArgs.CommandSource 屬性

 

今天在論壇上看見網友的討論:

http://www.blueshop.com.tw/board/FUM20041006161839LRJ/BRD20140725110006GGM.html

自己也學到很多,趕緊做一個記錄。

 

Q : 在 GridView的樣板裡面,有一個 Label控制項

      我設定了一個按鈕(有CommandName),按下這個按鈕以後,如何 .FindControl() 抓到這個 Label ??

 

上一篇文章,是寫在GridView「選取」事件內  SelectedIndexChanged事件

      [習題] "選取" Gridview的某一列(RowIndex) & 那一列對應資料表的P.K.值

       http://www.dotblogs.com.tw/mis2000lab/2008/11/07/gridview_selectedindex_pk

 

這一次,是寫在 RowCommand事件內(若是ListView,則為ItemCommand事件)

並使用了 e.CommandSource

 

===============================================================================

第一,畫面上設定一個 GridView + SqlDataSource

          轉成 "樣板"之後,自己加入一個按鈕,並設定 CommandName = "Hello"

          這個作法很關鍵,不同的畫面設計,會讓您的程式寫法也有異動。

          下一篇文章會為您解說

 

第二,在 GridView的 RowCommand事件裡面撰寫程式。

我的作法,這篇文章已經有提過(方法一),就是我的作法。

[GridView]在 RowCommand事件中,自訂的Button 如何取出某一列(RowIndex) 的索引值。NamingContainer的入門用法

 

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)

    {

        if (e.CommandName == "Hello")

        {   //*** 錯誤版 ***************************************************

            //Button BTN = (Button)sender;   

            //*** 發生錯誤,因為這裡的e與sender不是Button而是代表「GridView」!! *******

            //GridViewRow myRow = (GridViewRow)BTN.NamingContainer;

            ////-- 從你按下 Button按鈕的時候,知道你按下的按鈕在GridView「哪一列」!

            //Label LB = (Label)GridView1.Rows[myRow.DataItemIndex].FindControl("Label1");

            //Response.Write(LB.Text);

 

            //--- 正確版 (1) --------------------------------------------------------------------------------

            Button BTN =(Button)e.CommandSource;    //先抓到這個按鈕(我們設定了CommandName)

            //資料來源 http://msdn.microsoft.com/zh-tw/library/system.web.ui.webcontrols.gridviewcommandeventargs.commandsource(v=vs.110).aspx

            GridViewRow myRow = (GridViewRow)BTN.NamingContainer;

            // 從你按下 Button按鈕的時候,NamingContainer知道你按下的按鈕在GridView「哪一列」!

            Label LB = (Label)GridView1.Rows[myRow.DataItemIndex].FindControl("Label1");

            //按下按鈕之後,這一列的列數(index)-- myRow.DataItemIndex

            Response.Write(LB.Text);

        }

    }

 

藍色小舖,網友  789789789的作法是:

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)

    {

        if (e.CommandName == "Hello")

        {  //--- 正確版 (2) --------------------------------------------------------------------------------

            Label LB = (Label)((Control)e.CommandSource).FindControl("Label1");

            Response.Write(LB.Text);

            //資料來源 http://www.blueshop.com.tw/board/FUM20041006161839LRJ/BRD20140725110006GGM.html

        }

    }

 

也感謝 Allen Kuo在這篇討論裡面提供的建議 -- e.CommandSource,

才能找出這個方法。

 

===============================================================================

如果您要寫在 ListView裡面,請看這篇文章

ListView 的 ItemCommand事件中,找到是 "第幾列"執行的?某一列的索引值? ListViewDataItem的 DisplayIndex屬性 / DataItemIndex屬性

www.dotblogs.com.tw/mis2000lab/2015/03/27/listview_listviewdataitem_displayindex

****** 這是我測試的範例,可運作 ******

protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)

{

      Button BTN = (Button)e.CommandSource;

      ListViewDataItem  LVDItem = (ListViewDataItem)BTN.NamingContainer;

      Response.Write("<h3>這一列的索引(Index)--" + LVDItem.DataItemIndex + "</h3>" );

      Response.Write("<h3>這一列的索引(Index)--" + LVDItem.DisplayIndex + "</h3>");

}

===============================================================================

我在微軟官方 msdn網站裡面,也找到類似的範例

您可以參考他的作法,類似我第一種的作法:

GridViewCommandEventArgs.CommandSource 屬性

http://msdn.microsoft.com/zh-tw/library/system.web.ui.webcontrols.gridviewcommandeventargs.commandsource(v=vs.110).aspx

 

<%@ Page language="C#" %> <!DOCTYPE html> <script runat="server">

  void CustomersGridView_RowCreated(Object sender, GridViewRowEventArgs e)  

{    // The GridViewCommandEventArgs class does not contain a    // property that indicates which row's command button was    // clicked. To identify which row was clicked, use the button's    // CommandArgument property by setting it to the row's index.    

if(e.Row.RowType == DataControlRowType.DataRow)    {      // Retrieve the LinkButton control from the first column.      

   LinkButton addButton = (LinkButton)e.Row.Cells[0].Controls[0];      // Set the LinkButton's CommandArgument property with the      // row's index.           

   addButton.CommandArgument = e.Row.RowIndex.ToString();      //我的註解:他在產生 GridView每一列的時候,偷偷加註每一列的索引號碼!放到按鈕裡面    

   }  

}   

 

void CustomersGridView_RowCommand(Object sender, GridViewCommandEventArgs e)  {    // 我的註解:這個範例很讚的地方!    // 在於他講解了 e.CommandName / e.CommandArgument / e.CommandSource三者!通通用上了    

// If multiple ButtonField columns are used, use the    // CommandName property to determine which button was clicked.    

if(e.CommandName=="Add")    {      // Convert the row index stored in the CommandArgument      // property to an Integer.      

int index = Convert.ToInt32(e.CommandArgument);      // Retrieve the row that contains the button clicked      // by the user from the Rows collection. Use the      // CommandSource property to access the GridView control.      

GridView customersGridView = (GridView)e.CommandSource;      

GridViewRow row = customersGridView.Rows[index];      // Create a new ListItem object for the customer in the row.      

ListItem item = new ListItem();      item.Text = Server.HtmlDecode(row.Cells[1].Text) + " " + Server.HtmlDecode(row.Cells[2].Text);      // If the author is not already in the ListBox, add the ListItem      // object to the Items collection of a ListBox control.      

if(!CustomersListBox.Items.Contains(item))      {        

   CustomersListBox.Items.Add(item);      }    

}  

}

 

  } </script> <html xmlns="http://www.w3.org/1999/xhtml" >  <head runat="server">    <title>GridViewCommandEventArgs Example</title> </head> <body>    <form id="form1" runat="server">      <h3>GridViewCommandEventArgs Example</h3>      <table width="100%">        <tr>          <td style="width:50%">            <asp:gridview id="CustomersGridView"              datasourceid="CustomersSource"              autogeneratecolumns="false"              onrowcommand="CustomersGridView_RowCommand"              onrowcreated="CustomersGridView_RowCreated"                runat="server">              <columns>                <asp:ButtonField buttontype="Link" CommandName="Add" text="Add"/>             重點提示:這裡並沒有轉成樣板!而是直接採用 GridView的「ButtonField」                <asp:boundfield datafield="CompanyName"                  headertext="Company Name"/>                <asp:boundfield datafield="City"                  headertext="City"/>              </columns>            </asp:gridview>          </td>          <td style="vertical-align:top; width:50%">             Customers: <br/>             <asp:listbox id="CustomersListBox"               runat="server"/>          </td>        </tr>      </table>      <!-- This example uses Microsoft SQL Server and connects  -->      <!-- to the Northwind sample database. Use an ASP.NET     -->      <!-- expression to retrieve the connection string value   -->      <!-- from the Web.config file.                            -->      <asp:sqldatasource id="CustomersSource"        selectcommand="Select [CustomerID], [CompanyName], [City] From [Customers]"        connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>"        runat="server"/>    </form>  </body> </html>

 

因為畫面設計的差異,會讓程式碼的寫法也不同,

如果您混合使用、不明白原因,就會犯下錯誤。

 

下一篇文章為您解析:

[GridView]在 RowCommand事件中,自訂的Button 如何取出某一列(RowIndex) 的索引值#3 -- ButtonField 與 樣板裡面的Button,導致 e.CommandSource寫法不同

www.dotblogs.com.tw/mis2000lab/2014/07/30/gridview_e-commandsource_rowcommand_error

 

 

 

我將思想傳授他人, 他人之所得,亦無損於我之所有;

猶如一人以我的燭火點燭,光亮與他同在,我卻不因此身處黑暗。----Thomas Jefferson

線上課程教學,遠距教學 (Web Form 約 51hr)  https://dotblogs.com.tw/mis2000lab/2016/02/01/aspnet_online_learning_distance_education_VS2015

線上課程教學,遠距教學 (ASP.NET MVC 約 135hr)  https://dotblogs.com.tw/mis2000lab/2018/08/14/ASPnet_MVC_Online_Learning_MIS2000Lab

 

寫信給我,不要私訊 --  mis2000lab (at) yahoo.com.tw  或  school (at) mis2000lab.net

 (1) 第一天 ASP.NET MVC5 完整影片(5.5小時 / .NET 4.x版)免費試聽。影片 https://youtu.be/9spaHik87-A 

 (2) 第一天 ASP.NET Core MVC 完整影片(3小時 / .NET Core 6.0~8.0)免費試聽。影片 https://youtu.be/TSmwpT-Bx4I 

[學員感言] mis2000lab課程評價 - ASP.NET MVC , WebForm  。 https://mis2000lab.medium.com/%E5%AD%B8%E5%93%A1%E6%84%9F%E8%A8%80-mis2000lab%E8%AA%B2%E7%A8%8B%E8%A9%95%E5%83%B9-asp-net-mvc-webform-77903ce9680b  


ASP.NET遠距教學、線上課程(Web Form + MVC)。 第一天課程, "完整" 試聽。 

.........   facebook社團   https://www.facebook.com/mis2000lab   ......................

.........  YouTube (ASP.NET) 線上教學影片  https://www.youtube.com/channel/UC6IPPf6tvsNG8zX3u1LddvA/

 

Blog文章 "附的範例" 無法下載,請看 https://dotblogs.com.tw/mis2000lab/2016/03/14/2008_2015_mis2000lab_sample_download

請看我們的「售後服務」範圍(嚴格認定)。

...................................................................................................................................................... 

ASP.NET MVC  => .NET Core MVC 線上教學  ...... 第一天課程 完整內容 "免費"讓您評估 / 試聽

[遠距教學、教學影片] ASP.NET (Web Form) 課程 上線了!MIS2000Lab.主講   事先錄好的影片,並非上課側錄!   觀看時,有如「一對一」面對面講課