【发布时间】:2019-04-23 10:28:45
【问题描述】:
我正在使用每行填充 7 个按钮字段和 2 个绑定字段的网格视图。 我正在尝试在每次单击时更改按钮字段的背景色,并使用 sp 进行一些数据库更新。 我试图在 rowcommand 上得到它,但对按钮对象有一个空引用。 我也试图找到一些对这个 subjetc 的引用,但只是在带有按钮的模板字段上找到了元素,我想使用按钮字段而不是模板。
这是我的 gridview 的行示例:
<asp:ButtonField DataTextField="datechg_1" HeaderText="Date chg 1" Text="Btn1" ButtonType="Button" CommandName="chgColor"></asp:ButtonField>
<asp:ButtonField DataTextField="datechg_2" HeaderText="Date chg 2" Text="Btn2" ButtonType="Button" CommandName="chgColor"></asp:ButtonField>
<asp:ButtonField DataTextField="datechg_3" HeaderText="Date chg 3" Text="Btn3" ButtonType="Button" CommandName="chgColor"></asp:ButtonField>
这是抛出空引用的行命令代码:
protected void grid_date_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName=="chgColor")
{
Button btn = e.CommandSource as Button; << null reference here -_-
var color = btn.Style.Value;
switch (color)
{
case "background-color:red;":
btn.Style["background-color"] = "rgb(0,200,83)";
break;
case "background-color:blue;":
btn.Style["background-color"] = "rgb(242,101,34)";
break;
case "background-color:green;":
btn.Style["background-color"] = "rgb(229,57,53)";
break;
}
}
}
我猜开关颜色一点都不好,但目前这不是问题。我想知道如何点击按钮。 谢谢你的帮助:)
【问题讨论】:
-
你可以使用 gridview 的 asp:TemplateField 并创建 ItemTemplate 然后在其中创建 asp:Button 并在其中提供 CommandName 而不是使用 asp:ButtonField
标签: c# asp.net gridview buttonfield