Q> 我想将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>
答案 0 :(得分:2)
如果您希望文本显示为“删除”或“读取”,则只需将DataTextField
属性设置为使用结果的MID
属性,而不是设置{{ 1}}属性如此:
CommandName
就处理按钮的<asp:ButtonField ButtonType="Button" CommandName='<%#Eval("MMID")%>' HeaderText="Delete"
Text="Delete" />
事件而言,您可以在GridView上处理OnClick
事件:
OnRowCommand
现在添加代码:
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView_RowCommand" AutoGenerateColumns="False"
<强>更新强>
以上代码不起作用。 ButtonField和乳头对男人一样有用。而是使用ItemTemplateField:
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
}
}
然后GridView_RowCommand变为:
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btn" runat="server" CommandName="Delete" CommandArgument='<%#Eval("MID") %>'
Text="Delete" />
</ItemTemplate>
</asp:TemplateField>