以编程方式将非数据绑定列添加到gridview

时间:2009-10-30 20:34:35

标签: c# asp.net

我想在page_load()

上向gridview添加一列

它是我想要添加的标签。我的数据源中有ID ..但我不想显示Id,我必须在对象模型中查找ID并将其替换为名称。

所以,我需要一个这样的标签:

<asp:Label ID="1234" runat="server" OnDataBinding="BindName" />

这是我在ascx文件中做的事情..在TemplateField中。

我想在编程后面的代码中做同样的事情。

有什么想法吗?

3 个答案:

答案 0 :(得分:3)

您需要创建一个实现该ITemplate接口的类。

public class TemplateImplementation : ITemplate
{
    public void InstantiateIn(Control container)
    {
        Label label = new Label();
        label.DataBinding += Label_DataBinding;
        container.Controls.Add(label);
    }
    void Label_DataBinding(object sender, EventArgs e)
    {
        Label label = (Label)sender;
        object dataItem = DataBinder.GetDataItem(label.NamingContainer);
        string sName = /* Lookup your name using the dataitem here here */;
        label.Text = sName;
    }
}

然后创建一个TemplateColumn并将ItemTemplate设置为此类的实例。

TemplateColumn lblColumn = new TemplateColumn();
lblColumn.ItemTemplate = as;
grdMyGrid.Columns.Add(lblColumn);

答案 1 :(得分:0)

GridView有一个名为RowDataBound的事件。用那个。在此列的标记中包含TemplateColumn。在RowDataBound事件中,执行类似这样的操作(粗略示例):

      Private Sub GridView1_OnRowDataBound(ByVal sender as Object, ByVal e as EventArgs)
           If e.Row.RowType = DataControlRowType.DataRow Then
              'in this example the column in question is the 3rd column
              'unless you are doing some javascript or some css on the label, I would 
              'recommend using a literal and not label.  This is presuming there is no               
              'label or literal control in the ItemTemplate property of the TemplateColumn
              Dim lt as New Literal
              lt.Text = NameController.GetName(e.Row.DataItem("NameID")) 'your business logic layer goes here
              e.Row.Cells(2).Controls.Add(lt)
           End If
        End Sub

In addition, here is a link that may help you further:

答案 2 :(得分:0)

ASPX来源

 <asp:GridView ID="sampleGridView" Runat="server" DataSourceID="sampleDataSource">
    <Columns>
     <asp:TemplateField HeaderText="Territories">
        <ItemTemplate>
     <asp:Label ID="1234" runat="server"/>
        </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField HeaderText="FirstName" DataField="FirstName" 
           SortExpression="FirstName"></asp:BoundField>
        <asp:BoundField HeaderText="LastName" DataField="LastName" 
           SortExpression="LastName"></asp:BoundField>
</Columns>

C#代码

void sampleGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType == DataControlRowType.DataRow)
  {
    Label bl = (Label)e.Row.FindControl("1234");
    bl.Text= ((DataRowView) e.Row.DataItem)["ID"].ToString();
  }
}