programing

ASP.NET 그리드행 색인을 명령으로 보기인수

skycolor 2023. 8. 25. 23:26
반응형

ASP.NET 그리드행 색인을 명령으로 보기인수

그리드 보기 항목의 행 인덱스를 버튼 필드 열 버튼에서 명령 인수로 액세스하여 표시하려면 어떻게 해야 합니까?

<gridview>
<Columns>
   <asp:ButtonField  ButtonType="Button" 
        CommandName="Edit" Text="Edit" Visible="True" 
        CommandArgument=" ? ? ? " />
.....

매우 간단한 방법은 다음과 같습니다.

<asp:ButtonField ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" 
                 CommandArgument='<%# Container.DataItemIndex %>' />

MSDN은 다음과 같이 말합니다.

ButtonField 클래스는 CommandArgument 속성에 적절한 인덱스 값을 자동으로 채웁니다.다른 명령 단추의 경우 명령 단추의 CommandArgument 속성을 수동으로 설정해야 합니다.예를 들어 CommandArgument를 <%# 컨테이너로 설정할 수 있습니다.데이터 항목그리드 보기 컨트롤에 페이징이 활성화되지 않은 경우 인덱스 %>.

따라서 수동으로 설정할 필요가 없습니다.GridViewCommandEventArgs가 있는 행 명령을 사용하면 액세스할 수 있습니다.

protected void Whatever_RowCommand( object sender, GridViewCommandEventArgs e )
{
    int rowIndex = Convert.ToInt32( e.CommandArgument );
    ...
}

다음은 이 http://msdn.microsoft.com/en-us/library/bb907626.aspx#Y800 에 대한 Microsoft 제안입니다.

그리드 보기에서 명령 단추를 추가하고 템플릿으로 변환한 다음 "AddToCart"의 경우 명령 이름을 지정하고 명령 인수 "<%#((GridViewRow) 컨테이너)"를 추가합니다.행 색인 %>"

<asp:TemplateField>
  <ItemTemplate>
    <asp:Button ID="AddButton" runat="server" 
      CommandName="AddToCart" 
      CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
      Text="Add to Cart" />
  </ItemTemplate> 
</asp:TemplateField>

그런 다음 그리드 보기의 RowCommand 이벤트에 대해 "AddToCart" 명령이 트리거된 시점을 식별하고 원하는 대로 수행합니다.

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
  if (e.CommandName == "AddToCart")
  {
    // 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];

    // Add code here to add the item to the shopping cart.
  }
}

**한 가지 실수는 RowCommand 이벤트에서 직접 작업을 수행하는 대신 템플릿 버튼에 작업을 추가하려고 했다는 것입니다.

이게 될 것 같아요.

<gridview>
<Columns>

            <asp:ButtonField  ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" CommandArgument="<%# Container.DataItemIndex %>" />
        </Columns>
</gridview>
void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    Button b = (Button)e.CommandSource;
    b.CommandArgument = ((GridViewRow)sender).RowIndex.ToString();
}

일반적으로 그리드 보기와 함께 RowDatabound 이벤트를 사용하여 이 데이터를 바인딩합니다.

protected void FormatGridView(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
   if (e.Row.RowType == DataControlRowType.DataRow) 
   {
      ((Button)e.Row.Cells(0).FindControl("btnSpecial")).CommandArgument = e.Row.RowIndex.ToString();
   }
}
<asp:TemplateField HeaderText="" ItemStyle-Width="20%" HeaderStyle-HorizontalAlign="Center">
                    <ItemTemplate>
                        <asp:LinkButton runat="server" ID="lnkAdd" Text="Add" CommandName="Add" CommandArgument='<%# Eval("EmpID"))%>' />
                    </ItemTemplate>
                </asp:TemplateField>

이것은 강력하게 입력된 데이터가 있는 asp.net 프레임워크의 전통적인 방식이자 최신 버전이며 "EMPID"와 같은 문자열로 사용할 필요가 없습니다.

<asp:LinkButton ID="LnkBtn" runat="server" Text="Text" RowIndex='<%# Container.DisplayIndex %>' CommandArgument='<%# Eval("??") %>' OnClick="LnkBtn_Click" />

이벤트 핸들러 내부:

Protected Sub LnkBtn_Click(ByVal sender As Object, ByVal e As EventArgs)
  dim rowIndex as integer = sender.Attributes("RowIndex")
  'Here you can use also the command argument for any other value.
End Sub

페이징을 사용하여 약간의 계산이 필요합니다.

int index = Convert.ToInt32(e.CommandArgument) % GridView1.PageSize;

언급URL : https://stackoverflow.com/questions/389403/asp-net-gridview-rowindex-as-commandargument

반응형