我正在使用一个gridview,在每行上填充7个按钮字段和2个边界字段。 我试图在每次单击时更改按钮字段的背景色,并使用sp进行一些数据库更新。 我试图在rowcommand上获取该信息,但是对按钮对象有一个空引用。 我还试图找到对此subjetc的一些引用,但只是在templatefields中发现了带有内部按钮的元素,我想使用buttonfield而不是模板。
这是我的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;
}
}
}
我猜开关颜色根本不好,但是目前这不是问题。我想知道如何单击按钮。 谢谢您的帮助:)
答案 0 :(得分:0)
将OnRowCommand事件添加到Gridview。
<asp:GridView OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:ButtonField />
</Columns>
</asp:GridView>
和班级
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
//Response.Write(e.CommandArgument);
}