2014-04-17 83 views
0

我想添加一個GridView,並且我已經添加了一個按鈕到最後一列。它沒有做任何事情,我已經做了一個新的標籤,看它是否返回任何數據,但它似乎只是在最後一行工作。 你看到我的代碼有什麼問題嗎?提前致謝!GridViewRow只選擇最後一行

HTML

   <asp:Button runat="server" Text="Submit" OnClick="ButtonClick8" /> 
       </ItemTemplate> 
      </asp:TemplateField> 

     </Columns> 
     <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" /> 
     <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" /> 
     <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" /> 
     <RowStyle BackColor="White" ForeColor="#330099" /> 
     <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" /> 
     <SortedAscendingCellStyle BackColor="#FEFCEB" /> 
     <SortedAscendingHeaderStyle BackColor="#AF0101" /> 
     <SortedDescendingCellStyle BackColor="#F6F0C0" /> 
     <SortedDescendingHeaderStyle BackColor="#7E0000" /> 
    </asp:GridView> 

C#

protected void ButtonClick8(object sender, System.EventArgs e) 
{ 
    Button button2 = (Button)sender; 

    GridViewRow row2 = (GridViewRow)button2.NamingContainer; 
    int i = 0; 
    int string1; 
    foreach (GridViewRow gvr in GridView2.Rows) 
    { 
     if (gvr == row2) 
     { 
      string1 = Convert.ToInt32(gvr.Cells[0].Text); 
      Label1.Text = string1.ToString(); 

     } 
     else 
     { 
      Label1.Text = "no"; 
     } 
    } 

再次感謝您!

回答

1

您的foreach循環正在執行,直到到達最後一列並覆蓋標籤文本。當gvr == row2時退出循環:

foreach (GridViewRow gvr in GridView2.Rows) 
{ 
    if (gvr == row2) 
    { 
     string1 = Convert.ToInt32(gvr.Cells[0].Text); 
     Label1.Text = string1.ToString(); 
     break; 

    } 
    else 
    { 
     Label1.Text = "no"; 
    } 
} 
+0

多數民衆贊成在很大。真的很感謝幫助! – user3437235