2011-08-23 118 views
0

在我的表之一,我有以下三个字段:ID,标题,内容GridView控件绑定问题

如果我数据绑定表中数据为GridView我想有一个链接,使用displaycontent格式的标题。 ASPX?ID = '身份证'。

我的问题是,如果我没有在gridview中显示id字段,我不绑定id字段。如何在datarowbind事件中获得id值?

回答

1

我认为你可以这样做:

NavigationUrl='displaycontent.aspx?id=<%#Eval("Id")%>' 

而且你也不需要将Id列

我没有测试,但我敢肯定,这就是理念结合。

0

有几种方法可以做到这一点。您实际上不需要为此订阅RowDataBound事件。

你需要一个TemplateField列,其中包含足够您的需求(HyperLinkLinkButton,或其他)

一个用户控件让我们假设你的TemplateColumn中看起来是这样的:

<asp:TemplateField> 
    <ItemTemplate> 
     <asp:HyperLink runat="server" ID="hlContent" Text="Details" /> 
    </ItemTemplate> 
</asp:TemplateField> 

您可以让数据绑定就像伊卡洛斯所说的那样。 意味着,超链接看起来像这样(未经):

<asp:HyperLink runat="server" ID="hlContent" Text="Details" /> 

另一种选择是使用的RowDataBound事件,因为你要求它在你的问题:

protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e) 
    { 
    if(e.Row.RowType == DataControlRowType.DataRow) // neccessary to differentiate between content, header and footer 
    { 
     HyperLink hlContent = e.Row.FindControl("hlContent") as HyperLink; 
     YourObject dataItem = e.Row.DataItem as YourObject; // Depending on what datatype your e.Row.DataItem is. Take a look at it which the QuickWatch 
     hlContent.NavigateUrl = String.Format("displaycontent.aspx?id={0}", dataitem.id); 
    } 
    } 

编辑:在发布了关于如何使用RowDataBound事件的几个答案后,我决定写一篇阐述它的文章:http://www.tomot.de/en-us/article/7/asp.net/gridview-overview-of-different-ways-to-bind-data-to-columns

2

Juse使模板字段和locali所有绑定到控件的事件的定制。出于某种原因,大多数人在RowDataBound事件上这样做,我不建议这样做。没有理由必须使用DataBinding控件来搜索控件,并且它还允许将定制化本地化并易于更换,而不必影响其他任何东西。试想一下,如果您的网格中有20个控件需要DataBinding某种类型的自定义设置。你的RowDataBound事件将是一团糟,必须知道网格中的所有内容,这可能很容易出错。

例子:

<asp:TemplateField> 
    <ItemTemplate> 
     <asp:HyperLink runat="server" ID="lnkYourLink" 
      OnDataBinding="lnkYourLink_DataBinding" /> 
    </ItemTemplate> 
</asp:TemplateField> 

在codebind:

protected void lnkYourLink_DataBinding(object sender, System.EventArgs e) 
{ 
    HyperLink lnk = (HyperLink)(sender); 
    lnk.Text = Eval("Title").ToString(); 
    lnk.NavigateUrl = string.Format("displaycontent.aspx?id={0}", 
     Eval("ID").ToString()) 
}  

我喜欢这种方法,以及以内嵌代码,因为它不与任何逻辑混乱您的标记以及。如果第二天你需要它是一个LinkButton你可以很容易地换掉它,而不需要触及与HyperLink无关的任何其他代码。