首页 > 解决方案 > 单击时更改网格视图中的按钮样式

问题描述

我正在使用每行填充 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;
                }
            }
        }

我猜开关颜色一点都不好,但目前这不是问题。我想知道如何点击按钮。谢谢您的帮助 :)

标签: c#asp.netgridviewbuttonfield

解决方案


将 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);        
 }

推荐阅读