Skip to main content
 首页 » 编程设计

c#之Container.DataItemIndex 在 gridview 中不起作用

2024年02月20日13insus

出于某种原因,在我的代码容器中。DateItemIndex 没有在我的代码中返回任何值。

这是我的 asp.net:

   <asp:Label ID="Label1" runat="server" Text=""></asp:Label> 
 
<form id="form1" runat="server">  
         <asp:GridView ID="GridView1" runat="server" AllowPaging="True"  
             AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDataSource1"  
             EnableModelValidation="True" onrowcommand="GridView1_RowCommand" OnRowUpdating="GridView1_RowUpdating" > 
 
             <Columns> 
                 <asp:CommandField ShowEditButton="True" ControlStyle-CssClass="savefile"/> 
                 <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"  
                     ReadOnly="True" SortExpression="ID" /> 
                 <asp:BoundField DataField="event_name" HeaderText="event_name"  
                     SortExpression="event_name" /> 
 
                 <asp:TemplateField HeaderText="PDF"> 
 
           <ItemTemplate> 
 
               <asp:Button ID="Button1" CommandArgument='<%# Container.DataItemIndex %>' CommandName="DownloadFile" runat="server" Text="Button" /> 
 
            </ItemTemplate> 
 
           <EditItemTemplate> 
 
               <asp:FileUpload ID="FileUpload1" runat="server" /> // shown only in edit mode 
 
           </EditItemTemplate> 
 
          </asp:TemplateField> 
 
             </Columns> 
         </asp:GridView> 
</form> 

和我的 C# 代码:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) 
    { 
 
    if (e.CommandName == "DownloadFile") 
    { 
 
        Label1.Text = e.CommandArgument.ToString(); 
 
    } 
 
} 

为什么我没有从 CommandArgument='<%# Container.DataItemIndex %>' 中获取任何值

请您参考如下方法:

替换CommandArgument='<%# Container.DataItemIndex %>'与 CommandArgument='<%#DataBinder.Eval(Container, "DataItemIndex")%>' .