2013-08-22 3 views
1

Я создал главную страницу (мою страницу шаблона), и я поместил на нее сетку. Теперь я создам несколько страниц (aspx), которые будут использовать эту главную страницу. Вместо того, чтобы выполнять все настройки для этих страниц aspx, все, что мне нужно сделать, это настроить источник данных. Когда aspx загружает, он подключает источник данных к gridview (на главной странице), и он загружается. Теперь я хотел бы манипулировать данными внутри gridview, но мой счетчик datakeys возвращает 0. Я могу получить доступ к значениям, например, через gv.Rows(dr.RowIndex).Cells(5). Но я хочу сделать это с помощью ключей данных. Мой код ниже, любая помощь приветствуется. Благодарю.Datakeys count returns 0

Public Sub ConnectDataSource() 
    Dim mpContentPlaceHolder As ContentPlaceHolder 
    Dim gv As GridView 
    mpContentPlaceHolder = CType(Master.FindControl("GridViewPlaceHolder"), ContentPlaceHolder) 
    If Not mpContentPlaceHolder Is Nothing Then 
     gv = CType(mpContentPlaceHolder.FindControl("GridView1"), GridView) 
     If Not gv Is Nothing Then 
      Dim es As EntityDataSource = EntityDataSource1 
      gv.DataSource = es 
      gv.DataBind() 
      Debug.WriteLine("datakey count " + gv.DataKeys().Count.ToString()) 
      ' gv.HeaderRow.Cells(2).Text = "sdfds" // to change header text for each column. 
     End If 
    End If 
End Sub 

Private Sub PaymentRules_Load(sender As Object, e As EventArgs) Handles Me.Load 
    Dim toolbarPlaceHolder As ContentPlaceHolder 
    Dim btn As ImageButton 
    toolbarPlaceHolder = CType(Master.FindControl("ToolBarPlaceHolder"), ContentPlaceHolder) 
    If Not toolbarPlaceHolder Is Nothing Then 
     btn = DirectCast(toolbarPlaceHolder.FindControl("ImageButton2"), ImageButton) 
     If Not btn Is Nothing Then 
      AddHandler btn.Click, AddressOf ImageButton2_Click 
     End If 
    End If 
    If (Not Page.IsPostBack) Then 
     ConnectDataSource() 
    End If 
End Sub 
Protected Sub ImageButton2_Click(sender As Object, e As EventArgs) 
    Debug.WriteLine("ImageButton2_Click") 
    Dim maList As New List(Of Integer) 
    Dim mContentPlaceHolder As ContentPlaceHolder 
    Dim gv As GridView 
    mContentPlaceHolder = CType(Master.FindControl("GridViewPlaceHolder"), ContentPlaceHolder) 
    If Not mContentPlaceHolder Is Nothing Then 
     gv = CType(mContentPlaceHolder.FindControl("GridView1"), GridView) 
     If Not gv Is Nothing Then 
      For Each dr As GridViewRow In gv.Rows 
       If ((TryCast(dr.FindControl("CheckBox1"), CheckBox)).Checked = True) Then 
        'Debug.WriteLine(dr.RowIndex.ToString()) 
        'Dim id As Integer = gv.DataKeys(dr.RowIndex).Value 
        'maList.Add(id) 
        Debug.WriteLine("row index " + gv.Rows(dr.RowIndex).Cells(5).Text) 
        Debug.WriteLine("datakey count " + gv.DataKeys().Count.ToString()) 
       End If 
      Next 
     End If 
    End If 
End Sub 

EDITED - Мастер кодовая страница


<%@ Master Language="VB" AutoEventWireup="false" CodeBehind="JSPSite.master.vb" Inherits="SSPayroll.JSPSite" %> 

<!DOCTYPE html> 

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head id="Head1" runat="server"> 
    <title></title> 
    <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" /> 
    <link href="../Styles/Style1.css" rel="stylesheet" type="text/css" /> 
    <asp:ContentPlaceHolder ID="HeadContent" runat="server"> 
    </asp:ContentPlaceHolder> 
</head> 
<body> 
    <form id="Form1" runat="server"> 
    <div class="page"> 
     <div class="header"> 
      <div class="title"> 

      <h1> 
       <asp:Image ID="Image1" runat="server" ImageUrl="~/images/GSCV1.01 - Copy.png" 
        Height="73px" style="margin-top: 20px" Width="428px" /> 
      </h1> 
      </div> 

      <div class="loginDisplay"> 
       <asp:LoginView ID="HeadLoginView" runat="server" EnableViewState="false"> 
        <LoggedInTemplate> 
         <asp:Label ID="Label2" runat="server" Text="User: " Font-Names="Cambria"></asp:Label><span class="bold"> 
          <asp:LoginName ID="HeadLoginName" runat="server" Font-Names="Cambria" /> 
         </span> [ 
         <asp:LoginStatus ID="HeadLoginStatus" runat="server" LogoutAction="Redirect" 
          LogoutPageUrl="~/" Font-Names="Cambria" Font-Size="Small" ForeColor="#D9D5D5" Font-Bold="True" LogoutText="Sign Out" /> 
         ] 
              <div> 

       </div> 
        </LoggedInTemplate> 
        <RoleGroups> 
         <asp:RoleGroup> 
         </asp:RoleGroup> 
        </RoleGroups> 
       </asp:LoginView> 
       <asp:Label ID="Label1" runat="server" Text="Date/Time" Font-Names="Cambria" 
         Font-Size="Small" ForeColor="#333333"></asp:Label>    
      </div> 

      <div class="clear hideSkiplink"> 
       <asp:Menu ID="NavigationMenu" runat="server" CssClass="menu" EnableViewState="False" 
        IncludeStyleBlock="False" Orientation="Horizontal" BackColor="#FFFBD6" 
        DynamicHorizontalOffset="2" Font-Names="Verdana" Font-Size="0.8em" 
        ForeColor="#990000" StaticSubMenuIndent="10px" Enabled="True"> 
        <DynamicHoverStyle BackColor="#990000" ForeColor="White" /> 
        <DynamicMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" /> 
        <DynamicMenuStyle BackColor="#FFFBD6" /> 
        <DynamicSelectedStyle BackColor="#FFCC66" /> 
        <Items> 
              <asp:MenuItem Text="Menu1" Value="Tools"> 
               <asp:MenuItem NavigateUrl="~/JSPayroll/Payment_Rules/PaymentRules.aspx" Text="Payment Rules" Value="Payment Rules"></asp:MenuItem> 
         </asp:MenuItem> 

        </Items> 
        <StaticHoverStyle BackColor="#990000" ForeColor="White" /> 
        <StaticMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" /> 
        <StaticSelectedStyle BackColor="#FFCC66" /> 
       </asp:Menu> 
      </div> 
     </div> 
     <asp:ContentPlaceHolder ID="ToolBarPlaceHolder" runat="server" > 
      <asp:Panel ID="Panel1" runat="server" HorizontalAlign="Center"> 
       <div> 
       <hr /> 
       <asp:ImageButton ID="ImageButton1" runat="server" Height="48px" ImageUrl="~/IconsPack/Home.png" Width="48px" ToolTip="Home" CssClass="morph" /> 
       <asp:ImageButton ID="ImageButton2" runat="server" Height="48px" ImageUrl="~/IconsPack/Add.png" ToolTip="Add Record" CssClass="morph" Width="48px"/> 
       <asp:ImageButton ID="ImageButton3" runat="server" Height="48px" ImageUrl="~/IconsPack/Edit E.png" ToolTip="Edit Record" CssClass="morph" Width="48px" /> 
       <asp:ImageButton ID="ImageButton4" runat="server" Height="48px" ImageUrl="~/IconsPack/ViewDetails.png" ToolTip="View Record Details" CssClass="morph" Width="48px" /> 
       <asp:ImageButton ID="ImageButton5" runat="server" Height="48px" ImageUrl="~/IconsPack/Delete.png" ToolTip="Delete Record" CssClass="morph" Width="48px" /> 
       <asp:ImageButton ID="ImageButton6" runat="server" Height="48px" ImageUrl="~/IconsPack/Approved.png" ToolTip="Approve Record" CssClass="morph" Width="48px"/> 
       <asp:ImageButton ID="ImageButton7" runat="server" Height="48px" ImageUrl="~/IconsPack/Denied.png" ToolTip="Unapprove Record" CssClass="morph" Width="48px"/> 
       <asp:ImageButton ID="ImageButton8" runat="server" Height="48px" ImageUrl="~/IconsPack/Update.png" ToolTip="Refresh Table" CssClass="morph" Width="48px"/> 
       <hr /> 
      </div> 
     </asp:Panel> 
     </asp:ContentPlaceHolder> 

     <%--<asp:ContentPlaceHolder ID="GridViewPlaceHolder" runat="server">--%> 
      <div class="EU_TableScroll" id="showData" style="display: block"> 
       <asp:GridView ID="GridView1" runat="server" CssClass="EU_DataTable" EmptyDataText="No Data Available."> 
        <Columns> 
         <asp:TemplateField> 
          <ItemTemplate> 
           <asp:CheckBox ID="CheckBox1" runat="server" /> 
          </ItemTemplate> 
         </asp:TemplateField> 
        </Columns> 

       </asp:GridView> 
      </div> 
     <%--</asp:ContentPlaceHolder>--%> 
     <div class="main"> 
        <asp:ContentPlaceHolder ID="MainContent" runat="server"> 
        </asp:ContentPlaceHolder> 
     </div> 
     <div class="clear">   
     </div> 
    </div> 
    <div class="footer"> 
    </div> 
    </form> 
</body> 
</html> 

ответ

0

Помещенные ImageButtons и GridView и EntityDataSource из ContentPlaceHolde.
Вы не используете FindControl, а CheckBox.
В GridView1 set DataKeyNames Недвижимость вашему ключу.

+0

Вы можете расширить этот вопрос .. почему я должен это делать? –

+0

Я взял его и все еще вернул 0! –

+0

share aspx code –

0

Установили ли вы свойство DataKeyNames на стороне Gridview .aspx. Проверьте ниже пример кода от msdn. Если вы установите свойство DataKeyNames, то только я думаю, что вы можете получить доступ к свойству DataKeys в коде позади.

<asp:gridview id="CustomersGridView" 
     datasourceid="CustomersSource" 
     autogeneratecolumns="true" 
     emptydatatext="No data available." 
     autogenerateselectbutton="true"  
     datakeynames="CustomerID" 
     onselectedindexchanged="CustomersGridView_SelectedIndexChanged" 
     runat="server"> 

     </asp:gridview> 
+0

Спасибо .. это то, чего не хватало. –

+0

в любом случае я могу установить это в коде, а не прямо на gridview? –

+0

попробуй, я скажу. – Mitul