我有一个DataGridView,它有两个动态生成的ItemTemplate按钮列。我点击它们时触发的两个按钮都有代码隐藏,但是当点击btnInfo按钮时我还需要运行一个javascript函数
标记:
<asp:GridView ID="gridResutls" runat="server" OnRowCommand="gridResutls_RowCommand" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="strName" HeaderText="Name"/>
<asp:BoundField DataField="strBrand" HeaderText="Brand"/>
<asp:BoundField DataField="strServing" HeaderText="Serving"/>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="btnInfo" runat="server" CausesValidation="false" CommandName="MoreInfo"
Text="More Info" CommandArgument='<%# Eval("strID") %>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="btnAdd" runat="server" CausesValidation="false" CommandName="AddItem"
Text="Add To Log" CommandArgument='<%# Eval("strID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>'
我有一个名为populateLabel()
的javascript函数,我需要在点击btnInfo时触发。
有什么想法吗? (我知道有类似的问题已被问过,我在整个帖子中查看了一些东西,但似乎没有任何工作)
编辑:以下是ItemTemplate按钮的代码隐藏
protected void gridResutls_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
{
// Kick out if neither of the two dynamically created buttons have been clicked
if (e.CommandName != "MoreInfo" && e.CommandName != "AddItem")
{
return;
}
// If the "More Info" buton has been clicked
if (e.CommandName == "MoreInfo")
{
// Some code
}
// If the "Add To Log" button has been clicked
if (e.CommandName == "AddItem")
{
// Some code
}
}
答案 0 :(得分:4)
你可以这样做。
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
Button btnAdd = e.Row.FindControl("btnAdd") as Button;
btnAdd.Attributes.Add("OnClick", "populateLabel();");
}
}
标记:
<script type="text/javascript">
function populateLabel() {
alert('hi');
}
</script>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="DSModels" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="btnInfo" runat="server" CausesValidation="false" CommandName="MoreInfo"
Text="More Info" CommandArgument='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="btnAdd" runat="server" CausesValidation="false" CommandName="AddItem"
Text="Add To Log" CommandArgument='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
答案 1 :(得分:1)
使用OnClientClick
:
<asp:Button ID="btnInfo" runat="server" OnClientClick="populateLabel()" CausesValidation="false" CommandName="MoreInfo"
Text="More Info" CommandArgument='<%# Eval("strID") %>'/>