1

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
  • Do you have a List of Courses or just one Course in Student type? Jan 25, 2011 at 17:44

2 Answers 2

3

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
  • it will not work because i have main object collection witin it i have another object that i want to access its property + Student withint Student i have Courses object and i want to access that course.name
    – Nick Kahn
    Jan 25, 2011 at 16:44
  • even if i define the key in my datakeynames will not work because as i have said that i have a custom object.. the correct way of doing is MyClass obj = (MyClass)(e.Row.DataItem); i will accept your answer.
    – Nick Kahn
    Jan 25, 2011 at 17:47
-1

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

1
  • Consider using a master-details to split this up. Jan 25, 2011 at 17:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.