在GridView的RowCommand中,自定Button如何抓到被選的RowIndex --e.CommanfArgument & e.CommandSource

  • 5210
  • 0
  • 2015-09-19

摘要:GridView的RowCommand如何抓到被選的RowIndex

1. GridView自訂按鈕(Gridview身體裡面並設定CommandName),按下後要抓到「當下被選RowIndex」,進而抓到Row裡面的控制項RowCommand

        方法一 : e.CommandArgument

1.GridView +sqlDataSource小精靈

2.GridView身體裡新增一個按鈕欄位並設定CommandName

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

3.RowCommand

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)

    {

        if (e.CommandName == "GridRows") {

            //抓到RowCommand選取時的Row的所引編號

            int pk_key =Convert.ToInt32(e.CommandArgument);

            //抓到RowCommand選取時的控制項

            GridViewRow gr = (GridViewRow)GridView1.Rows[pk_key];

            Label lb1 = (Label)GridView1.Rows[gr.DataItemIndex].FindControl("Label1");

           

            Response.Write("GridView Row Index : " + pk_key.ToString()+"<br/>");

            Response.Write(lb1.Text);

        }

    } 

方法二 : e.CommandSource

1.GridView +sqlDataSource小精靈

2.GridView身體裡新增一個按鈕欄位轉成樣板,並設定CommandName

<asp:TemplateField ShowHeader="False">

                <ItemTemplate>

                    <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="false"

                        CommandName="Button" Text="按鈕"></asp:LinkButton>

                </ItemTemplate>

            </asp:TemplateField>

3.RowCommand

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)

    {

        if (e.CommandName == "Button") {

            //Button欄位要轉成樣板System.Web.UI.WebControls.LinkButton

            //Button欄位若沒有轉成樣板System.Web.UI.WebControls.GridView

       //Response.Write(e.CommandSource.ToString());

    

      

             LinkButton bt = (LinkButton)e.CommandSource;

             // LinkButton bt = (LinkButton)sender --錯誤這會抓到GridView

            GridViewRow gdrow = (GridViewRow)bt.NamingContainer;

            //由控制項抓到Row

 

            Label lb1 = (Label)GridView1.Rows[gdrow.DataItemIndex].FindControl("Label1");

            Response.Write("RowIndex : " + gdrow.DataItemIndex.ToString());

            Response.Write(lb1.Text);

        }

    }

  若是欄位轉成樣板,執行就會是對的

     LinkButton bt = (LinkButton)e.CommandSource;

若是沒有轉成樣板

      LinkButton bt = (LinkButton)e.CommandSource;就會錯誤

e.CommandSource只會抓到GridView而已

 

內容為Mis2000Lab學筆記 參考 :

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

 

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

 

 

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