在进行GridView绑定的时候,有时候使用CommandField 进行绑定,但要根据不同的条件动态改变显示的文 字,则是比较麻烦的,当然,什么模板列则是非常简单的。下面就提供一种使用绑定列修改命令按钮显示文字的方法。
CommandField 有个ButtonType属性,有3个枚举值:Button,Image,Link,根据不同的设置,显示不同的类型。那么就可以在绑定事件里进行修改显示的文字。
ASPX 代码
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
// 计算数据,完全可以从数据看取得
System.Data.DataView CreateDataSourceByXianhuiMeng()
{
System.Data.DataTable dt = new System.Data.DataTable();
System.Data.DataRow dr;
dt.Columns.Add(new System.Data.DataColumn("id", typeof(System.Int32)));
dt.Columns.Add(new System.Data.DataColumn("学生姓名", typeof(System.String)));
dt.Columns.Add(new System.Data.DataColumn("语文", typeof(System.Decimal)));
dt.Columns.Add(new System.Data.DataColumn("数学", typeof(System.Decimal)));
dt.Columns.Add(new System.Data.DataColumn("英语", typeof(System.Decimal)));
dt.Columns.Add(new System.Data.DataColumn("计算机", typeof(System.Decimal)));
for (int i = 0; i < 8; i++)
{
System.Random rd = new System.Random(Environment.TickCount * i); ;
dr = dt.NewRow();
dr[0] = i * i;
dr[1] = "【孟子E章】" + i.ToString();
dr[2] = System.Math.Round(rd.NextDouble() * 100, 2);
dr[3] = System.Math.Round(rd.NextDouble() * 100, 2);
dr[4] = System.Math.Round(rd.NextDouble() * 100, 2);
dr[5] = System.Math.Round(rd.NextDouble() * 100, 2);
dt.Rows.Add(dr);
}
System.Data.DataView dv = new System.Data.DataView(dt);
return dv;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataSource = CreateDataSourceByXianhuiMeng();
GridView1.DataBind();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
System.Data.DataRowView dv = e.Row.DataItem as System.Data.DataRowView;
if (Decimal.Parse(dv["语文"].ToString()) > 60)
{
LinkButton b = e.Row.Cells[1].Controls[0] as LinkButton;
b.Text = "冻结";
}
}
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridView gv = sender as GridView;
Response.Write("要进行操作的主键的值:" + gv.DataKeys[e.RowIndex].Value);
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id"
OnRowDataBound="GridView1_RowDataBound" OnRowDeleting="GridView1_RowDeleting">
<Columns>
<asp:BoundField DataField="id" HeaderText="id" />
<asp:CommandField HeaderText="状态" ShowDeleteButton="True" DeleteText="state" />
<asp:BoundField DataField="语文" HeaderText="语文成绩" />
</Columns>
</asp:GridView>
</form>
</body>
</html>