【问题标题】:how to access templatefield from code behind如何从后面的代码访问模板字段
【发布时间】:2011-01-25 16:12:12
【问题描述】:

我希望更新动态的原因是因为我正在使用 objectdatasource 并且我的 objectdatasource 有一个对象集合,并且在该对象中我有另一个我想访问的对象,例如:

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

更新结束

如何从代码隐藏中绑定模板字段?

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

</columns>
</asp:Gridview>

【问题讨论】:

  • 您有课程列表还是只有一个学生类型的课程?

标签: asp.net gridview


【解决方案1】:

首先在 GridView 控件中定义您的关键字段,只需将 net 属性添加到 GridView 标记:datakeynames="StudentID"

您可以同时使用 GridView 的事件处理程序:RowDataBound 或 RowCreated。只需添加一个此事件处理程序并找到放置在您的 ItemTemplate 中的控件。比如这里:

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 = // 
      }
    }

  }

这个例子来自MSDN

【讨论】:

  • 它不起作用,因为我有主对象集合,我有另一个对象,我想访问它的属性+ Student withint Student i have Courses object,我想访问那个course.name
  • 即使我在 datakeynames 中定义了密钥也不起作用,因为正如我所说,我有一个自定义对象。正确的做法是 MyClass obj = (MyClass)(e.Row.DataItem); 我会接受你的回答。跨度>
【解决方案2】:

以下是一些来自 MSDN 的代码示例:

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

这些在 VB 中,但您也应该能够找到 C# :-)

如果您点击此链接并向下滚动,您会找到一个代码示例:

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

【讨论】:

  • 考虑使用 master-details 来拆分它。
猜你喜欢
  • 2012-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-19
相关资源
最近更新 更多