1

Q>我想将 GridView 按钮的文本显示为硬编码,并在按钮单击时触发一个事件。如何做到这一点?

直到现在我已经能够走到这一步

GridView 示例

但我想将按钮文本显示为读取删除,而不是读取/删除列中的值。我用过的代码

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
DataKeyNames="MID" DataSourceID="inbox" EnableModelValidation="True" 
onselectedindexchanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:ButtonField ButtonType="Button" DataTextField="MID" HeaderText="Read" 
  Text="Read" />
<asp:BoundField DataField="MID" HeaderText="MID" InsertVisible="False" 
  ReadOnly="True" SortExpression="MID" />
<asp:BoundField DataField="sender" HeaderText="sender" 
  SortExpression="sender" />
<asp:BoundField DataField="subject" HeaderText="subject" 
  SortExpression="subject" />
<asp:BoundField DataField="on" HeaderText="on" SortExpression="on" />
<asp:ButtonField ButtonType="Button" DataTextField="MID" HeaderText="Delete" 
  Text="Delete" />
</Columns>
</asp:GridView>

<asp:SqlDataSource ID="inbox" runat="server" 
ConnectionString="<%$ ConnectionStrings:connectionString %>" 
SelectCommand="SELECT [MID], [sender], [subject], [on] FROM [mail]">
</asp:SqlDataSource>
4

1 回答 1

3

如果您希望文本显示为“删除”或“读取”,那么只需不要将DataTextField属性设置为使用MID结果的属性,而是将CommandName属性设置为:

<asp:ButtonField ButtonType="Button" CommandName='<%#Eval("MMID")%>' HeaderText="Delete" 
  Text="Delete" />

至于处理OnClick按钮的事件,您可以这样处理OnRowCommandGridView 上的事件:

<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView_RowCommand" AutoGenerateColumns="False" 

现在在后面添加代码:

protected void GridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{

  string MMID = e.CommandName;
  if( (e.CommandSource as ButtonField).Text=="Delete")
  {
             //oh, I should delete this MMID
  }
}    

更新

上面的代码不起作用。ButtonField 就像乳头对男人一样有用。而是像这样使用 ItemTemplateField:

 <asp:TemplateField>
     <ItemTemplate>
         <asp:Button ID="btn" runat="server" CommandName="Delete" CommandArgument='<%#Eval("MID") %>'
                    Text="Delete" />
     </ItemTemplate>
 </asp:TemplateField>

然后 GridView_RowCommand 变成这样:

protected void GridView_RowCommand(Object sender, GridViewCommandEventArgs e)
    {
        string mid = e.CommandArgument.ToString();
        // If multiple buttons are used in a GridView control, use the
        // CommandName property to determine which button was clicked.
        if (e.CommandName == "Delete")
        {

        }
    }    
于 2012-09-05T14:56:28.057 回答