2017-09-08 63 views
1

我有一個gridview顯示來自sql表的大量行。我也有checkboxchkboxSelectAllgridview標題檢查gridview中的所有行。檢查Gridview的前5行

代碼chkboxSelectAlloncheckedchange

protected void chkboxSelectAll_CheckedChanged(object sender, EventArgs e) 
     { 
      CheckBox ChkBoxHeader = (CheckBox)Grid.HeaderRow.FindControl("chkboxSelectAll"); 
      foreach (GridViewRow row in Grid.Rows) 
      { 
       CheckBox ChkBoxRows = (CheckBox)row.FindControl("chkrow"); 
       if (ChkBoxHeader.Checked == true) 
       { 
        ChkBoxRows.Checked = true; 
       } 
       if (ChkBoxHeader.Checked == false) 
       { 
        ChkBoxRows.Checked = false; 
       } 
      } 
     } 

但是,我只想檢查檢查頭的複選框後的前5行的GridView的。

我搜索的所有答案都是數據表或數據集,但沒有人爲gridview本身。

有沒有辦法做到這一點。任何幫助將不勝感激..!!

+0

您的整數。例如'int i = 0;我++;如果(i> 5)...' –

+0

如果我正確理解您的問題,您可以選擇所有代碼並希望將其更改爲僅第5行。這是真的? – ConductedClever

+0

是@ConductedClever – Preet

回答

4

如果第二個評論的答案是真的,那麼這將是您的解決方案(例如):

protected void chkboxSelectAll_CheckedChanged(object sender, EventArgs e) 
    { 
     CheckBox ChkBoxHeader = (CheckBox)Grid.HeaderRow.FindControl("chkboxSelectAll"); 
     bool sign = ChkBoxHeader.Checked == true; 
     int counter = 0; 
     foreach (GridViewRow row in Grid.Rows) 
     { 
      CheckBox ChkBoxRows = (CheckBox)row.FindControl("chkrow"); 
      ChkBoxRows.Checked = sign; 
      counter++; 
      if (counter == 5) 
      { 
       break; 
      } 
     } 
    } 
+0

不客氣@Preet。 – ConductedClever

1

你可以使用LINQ來做到這一點:

foreach (GridViewRow row in Grid.Rows.Take(5)) 
{ 
    CheckBox ChkBoxRows = (CheckBox)row.FindControl("chkrow"); 
    if (ChkBoxHeader.Checked == true) 
    { 
     ChkBoxRows.Checked = true; 
    } 
    if (ChkBoxHeader.Checked == false) 
    { 
     ChkBoxRows.Checked = false; 
    } 
} 
+0

謝謝@senz,但我沒有使用LINQ – Preet