c# - 单击时更改网格视图中的按钮样式
问题描述
我正在使用每行填充 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;
}
}
}
我猜开关颜色一点都不好,但目前这不是问题。我想知道如何点击按钮。谢谢您的帮助 :)
解决方案
将 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);
}
推荐阅读
- c++ - C++ 入门 5 版:shared_ptr 从 uniqe_ptr 初始化?
- java - 卡在数独作业的回溯步骤上
- json - 寻找将通过 websocket 接收的 JSON 数据显示到 Xcode/Swift 动态表中的最有效方法
- catboost - CatBoost RandomizedSearch 停止并找出它的超参数
- python - 从 input_t(实际上是三个数字并充当特征)和 output_t 作为输出创建一个数据框
- javascript - JS文件无法访问laravel变量
- three.js - 如何在three.js上通过addEventListener动态更新set.position.x?
- geolocation - 查看和地理位置字段
- mysql - 为什么函数 count() 与 gorup by 出错?
- sql-server - EF Core 错误的连接语句