mir*_*zus 55 c# asp.net gridview
如何在buttonfield列按钮中访问并显示gridview项的行索引作为命令参数?
<gridview>
<Columns>
<asp:ButtonField ButtonType="Button"
CommandName="Edit" Text="Edit" Visible="True"
CommandArgument=" ? ? ? " />
.....
Run Code Online (Sandbox Code Playgroud)
Geo*_*rge 95
这是一个非常简单的方法:
<asp:ButtonField ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True"
CommandArgument='<%# Container.DataItemIndex %>' />
Run Code Online (Sandbox Code Playgroud)
Ric*_*ich 34
MSDN说:
ButtonField类使用适当的索引值自动填充CommandArgument属性.对于其他命令按钮,您必须手动设置命令按钮的CommandArgument属性.例如,当GridView控件未启用分页时,您可以将CommandArgument设置为<%#Container.DataItemIndex%>.
所以你不需要手动设置它.然后使用GridViewCommandEventArgs的行命令可以访问它; 例如
protected void Whatever_RowCommand( object sender, GridViewCommandEventArgs e )
{
int rowIndex = Convert.ToInt32( e.CommandArgument );
...
}
Run Code Online (Sandbox Code Playgroud)
小智 12
这是微软的建议 http://msdn.microsoft.com/en-us/library/bb907626.aspx#Y800
在gridview上添加一个命令按钮并将其转换为模板,然后在这种情况下给它一个命令名" AddToCart ",并添加CommandArgument "<%#((GridViewRow)Container).RowIndex%>"
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="AddButton" runat="server"
CommandName="AddToCart"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
Text="Add to Cart" />
</ItemTemplate>
</asp:TemplateField>
Run Code Online (Sandbox Code Playgroud)
然后在GridView的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.
}
}
Run Code Online (Sandbox Code Playgroud)
**我犯的一个错误是我想在我的模板按钮上添加操作,而不是直接在RowCommand事件上执行操作.
我认为这会奏效.
<gridview>
<Columns>
<asp:ButtonField ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" CommandArgument="<%# Container.DataItemIndex %>" />
</Columns>
</gridview>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
184963 次 |
| 最近记录: |