how to access templatefield from code behind

和自甴很熟 提交于 2020-01-03 04:22:09

问题


the reason why i am looking to update dynamic is because i am using objectdatasource and my objectdatasource have a collection of object and within that object i have another object that i wanted to access so for an example:

+Student
  ......
  ......
  ......
  -Courses
    .........
    .........
    Name

Update end

how do i bind templatefield from code-behind?

<asp:Gridview ID="gridview1" runat="Server">
<columns>
 <asp:TemplateField HeaderText="Name" SortExpression="Name">
                    <ItemTemplate>                       
                    </ItemTemplate> 
                </asp:TemplateField>

</columns>
</asp:Gridview>

回答1:


First of all define your key field in GridView control, just add net attribute to GridView markup: datakeynames="StudentID".

You can use both event handler for GridView: RowDataBound or RowCreated. Just add one of this event handler and find there control that is placed in your ItemTemplate. Like here, for instance:

void ProductsGridView_RowCreated(Object sender, GridViewRowEventArgs e)
  {

    if(e.Row.RowType == DataControlRowType.DataRow)
    {
      // Retrieve the LinkButton control from the first column.
      Label someLabel = (Label)e.Row.FindControl("someLabel");
      if (someLabel != null)
      {
          // Get Student index
          int StudentId = (int)GridView.DataKeys[e.Row.RowIndex].Values[0];
          // Set the Label Text
          // Define here all the courses regarding to current student id              
          someLabel.Text = // 
      }
    }

  }

This example was gotten from MSDN




回答2:


Here are some code samples from MSDN:

http://msdn.microsoft.com/en-us/library/aa479353.aspx

These are in VB but you should be able to locate C# also :-)

If you follow this link and scroll down you will find a code sample:

http://bytes.com/topic/asp-net/answers/624380-gridview-generated-programmatically



来源:https://stackoverflow.com/questions/4795903/how-to-access-templatefield-from-code-behind

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!