1

So I am trying to add a title value to my DataGrid cell based on another cell within the same row.

I have an event triggered on ItemCreated which currently sets the cell to the HeaderText

using e.Item.Cells[i].Attributes.Add("title", DataGrid.Columns[i].HeaderText)

But now I have a new requirement that a certain column's title needs to be based on a different columns value.

But when I go to use e.Item.Cells[otherColumnIndex].Text it returns an empty string

Do I have to use a different property? How do I get the current value of a Cell, since i assumed the data is populated before this event is triggered. . Unless the data is filled in after the ItemCreated event?

4

1 回答 1

2

使用 ItemDataBound 事件而不是 ItemCreated 事件。

ItemCreated:行已创建,并且 itemtemplate 控件也已创建。

ItemDataBound:数据现在绑定到控件。

示例:标记

<asp:DataGrid id="grdTeset" OnItemDataBound="grdTeset_ItemDataBound" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundColumn DataField="Column1" />
        <asp:BoundColumn DataField="Column2" />
    </Columns>
</asp:DataGrid>

后面的示例代码:

public class Data 
{
    public string Column1 {get;set;}
    public string Column2 {get;set;}
}
public partial class _Default : System.Web.UI.Page
{
    public List<Data> data = new List<Data>();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            data.Add(new Data() { Column1 = "Row 1 Col 1", Column2 = "Row 1 Col 2" });
            data.Add(new Data() { Column1 = "Row 2 Col 1", Column2 = "Row 2 Col 2" });
            data.Add(new Data() { Column1 = "Row 3 Col 1", Column2 = "Row 3 Col 2" });

            grdTeset.DataSource = data;
            grdTeset.DataBind();
        }
    }

    protected void grdTeset_ItemDataBound(object sender, DataGridItemEventArgs e)
    {
        if (e.Item.ItemIndex != -1) //MAKE SURE THIS IS A DATA ROW AND NOT HEADER OR FOOTER
        {
            string value = e.Item.Cells[0].Text;
            Response.Write(value);
        }
    } 
}
于 2013-06-07T21:42:53.367 回答