2016-07-26 89 views
0

我想使用自动增加的模板字段而不是DataKeyName作为更新/删除GridView的因素。我的推理是因为可以有多个具有相同ID的条目(数据库中没有pk)。使用TemplateField作为GridView的PK

的GridView代码:

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" ShowFooter = "True" 
    AllowSorting="True" AutoGenerateColumns="False" CellPadding="4" 
    DataSourceID="SqlDataSource1" > 

我的代码自动递增列:

<asp:TemplateField ShowHeader="False" Visible="False" HeaderText="PK"> 
      <ItemTemplate> 
       <span> 
        <%# Container.DataItemIndex +1 %> 
       </span> 
      </ItemTemplate> 
     </asp:TemplateField> 

回答

0

我建议使用窗口(在视图中),以模仿一个主键,并且绑定视图GridView而不是表格。

create table dbo.temp (TheData varchar(255)); 

go 

insert into dbo.temp values ('Alpha'), ('Bravo'), ('Charlie'), ('Delta'), ('Echo'), ('Foxtrox'); 

go 

create view dbo.tempView 

as 

select 
    Id = ROW_NUMBER() over (order by TheData), -- mimics primary key 
    TheData 
from 
    dbo.temp 

go 

select Id, TheData from dbo.tempView; -- use this as your data source 
相关问题