2

各行にボタンがあるグリッドビューがあります:

ここに画像の説明を入力

ボタンはテンプレートフィールドにあります:

<asp:GridView ID="storyGridView" runat="server" AllowSorting="True" AutoGenerateColumns="False" 
      BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3"    
      CellSpacing="2" DataKeyNames="PK_NonScrumStory" DataSourceID="SqlDataSource1">
...
        <asp:TemplateField HeaderText="Actions">
            <ItemTemplate>
                <asp:Button ID="viewHoursButton" runat="server" Text="View Hours" OnClick="viewHoursButton_OnClick" />
                <asp:Button ID="addHoursButton" runat="server" Text="Add Hours" OnClick="addHoursButton_OnClick" />
                <asp:Button ID="editButton" runat="server" Text="Edit" OnClick="editButton_OnClick" />
                <asp:Button ID="deleteButton" runat="server" Text="Delete" OnClick="deleteButton_OnClick" />
            </ItemTemplate>
        </asp:TemplateField>

クリック時にデータキー名を取得するにはどうすればよいですか?

protected void viewHoursButton_OnClick(object sender, EventArgs e)
{
    //get PK_NonScrumStory for clicked row
}
4

3 に答える 3

9

私はそれを考え出した:

protected void viewHoursButton_OnClick(object sender, EventArgs e)
{
    Button btn = sender as Button;
    GridViewRow row = btn.NamingContainer as GridViewRow;
    string pk = storyGridView.DataKeys[row.RowIndex].Values[0].ToString();
    System.Diagnostics.Debug.WriteLine(pk);
}
于 2013-11-06T22:19:00.923 に答える
5

たとえば、カスタムButtonsCommandNameに対してとをバインドできます。CommandArgument

<asp:Button ID="deleteButton" 
 runat="server" 
 Text="Delete" 
 CommandName="DeleteItem" 
 CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
 OnClick="deleteButton_OnClick" />

次に、イベント storyGridView1_RowCommand を実装し、すべてのコマンドを処理する必要があります。

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
  if (e.CommandName == "DeleteItem")
  {
    // Retrieve the row index stored in the 
    // CommandArgument property.
    int index = Convert.ToInt32(e.CommandArgument);

    // Retrieve the row that contains the button 
    // from the Rows collection.
     GridViewRow row = GridView1.Rows[index];

    //Retrieve the key of the row and delete the item

  }
  else if(e.CommandName == "EditItem")
  {
    //edit the item
  }
  //Other commands
}
于 2013-11-06T22:24:05.490 に答える
3

間違ったイベントを使用しています。使用する

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand.aspx

GridView.RowCommand - セルではなくグリッドのイベントです。セルに CommandName string = を指定すると、OnClick イベントの代わりに、CommandName="ViewHours" が表示されます。

次に、myGridView_RowCommand イベント ハンドラーで、次のいずれかを取得します。

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridviewcommandeventargs.aspx

そして、e.CommandName に大きな switch ステートメントを挿入します。醜いですが、うまくいきます。

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

行インデックスを取得します。myGridView.DataKeys[index] で使用して、DataKeys を取得できます。

...

ええ、私は知っています。

于 2013-11-06T22:17:38.630 に答える