比如数据库中有如下表Table1:
|
ID |
Name |
Type |
|
1 |
One |
A |
|
2 |
two |
B |
首先绑定到GridView1:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
try
{
SqlConnection myConnection = new SqlConnection(DataBaseDB.ConnectionString);
string cmdText = "select * from Table1 ";
SqlCommand myCommand = new SqlCommand(cmdText, myConnection);
myConnection.Open();
SqlDataReader recu = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
GridView1.DataSource = recu;
GridView1.DataBind();
recu.Close();
}
catch
{ }
}
}
运行可以显示如数据表的内容。若在绑定时Type字段的A显示为“优秀”,B为“良好”可以添加如下事件:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridViewRow item = e.Row;
DataControlRowType itemType = e.Row.RowType;
if (itemType == DataControlRowType.DataRow)
{
switch (item.Cells[2].Text)
{
case "A":
item.Cells[2].Text = "优秀";
break;
case "B":
item.Cells[2].Text = "良好";
break;
default:
break;
}
}
}
此时可以实现想要的效果了。