在一个gridview中,第一列是TemplateField,放一个checkbox,后面五列是BoundField,直接绑订数据库。
我想控制改变最后一列的显示,如果从数据库拿到的数据是's',那么显示文字‘储存’,如果是‘P’那么显示‘批稿’。它后台直接就绑订了datasource,我现在应该如何控制?代码怎么写啊?
.aspx
<asp:GridView ID="gvDiff" runat="server" AutoGenerateColumns="False"> <Columns> <asp:TemplateField> <ItemTemplate> <asp:CheckBox runat="server" ID="cbSelectVersion"></asp:CheckBox> </ItemTemplate> <ItemStyle Width="5%" /> </asp:TemplateField> <asp:BoundField DataField="RevNo" HeaderText="<%$ Resources: RevNo %>" /> <asp:BoundField DataField="Remarks" HeaderText="<%$ Resources: Action %>" /> <asp:BoundField DataField="UpdatedDate" HeaderText="<%$ Resources: UpdateDate %>" /> <asp:BoundField DataField="UpdateName" HeaderText="<%$ Resources: UpdateBy %>" /> <asp:BoundField DataField="Status" HeaderText="<%$ Resources: ArticlePosition %>" /> </Columns> </asp:GridView> <asp:GridView ID="gvResult" runat="server" ShowHeaderWhenEmpty="True" Visible="true"> </asp:GridView>
aspx.cs
public override void DataBind() { if (DataSource != null) { articles = DataSource; gvDiff.DataSource = DataSource.ArticleHistories; gvDiff.DataBind(); } }
有个绑定项事件
能具体点吗?我没台明白你讲的
@rivahuang: RowDataBound
@jello chen:
protected void gvRowDatabound(object sender, GridViewRowEventArgs e) { for(int i=0;i<=gvDiff.Rows.Count;i++) { if (!string.IsNullOrWhiteSpace(gvDiff.Rows[0].Cells[5].ToString())) { switch (gvDiff.Rows[0].Cells[5].ToString()) { case "A": gvDiff.Rows[i].Cells[5].Text = ""; break; case "S": gvDiff.Rows[i].Cells[5].Text = ""; break; case "N": gvDiff.Rows[i].Cells[5].Text = ""; break; case "P": gvDiff.Rows[i].Cells[5].Text = ""; break; } } } }
你的意思是这样子写?
@rivahuang: 不需要遍历啊,通过GridViewRowEventArgs事件参数e可以获取该行的数据,然后根据数据来决定相应的变化
@jello chen: 可以简单的给我写一写吗?
@rivahuang:
aspx页面:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_OnRowDataBound"> <Columns> <asp:BoundField DataField="No" HeaderText="No"></asp:BoundField> <asp:BoundField DataField="Name" HeaderText="Name"></asp:BoundField> <asp:TemplateField> <ItemTemplate> <asp:Button ID="btn" runat="server"/> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView>
Codebehind:
public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { List<Student> students = new List<Student>(); for (int i = 0; i < 10; i++) { students.Add(new Student() { No = i + 1, Name = "zhangsan" + (i + 1) }); } GridView1.DataSource = students; GridView1.DataBind(); } protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e) { var student = e.Row.DataItem as Student; if (student != null) { var btn = e.Row.FindControl("btn") as Button; if (btn != null) { if (student.No % 2 == 0) { btn.Text = "偶行"; } else { btn.Text = "奇行"; } } } } } class Student { public int No { get; set; } public string Name { get; set; } }