2012-06-17 143 views
2

我正在開發一個應用程序在C#中,我使用datagridview和gridview第一列包含複選框,我想chech複選框是真實的或不是,但它給了我'對象引用未設置爲對象的實例'。代碼如下檢查gridview列複選框

private void btnDelete_Click(object sender, EventArgs e) 
     { 
      StudentDAL s = new StudentDAL(); 

      try 
      { 
       for (int i = 0; i < this.dataGridView1.RowCount; i++) 
       { 

        if (!DBNull.Value.Equals(this.dataGridView1.Rows[i].Cells[0]) && (bool)this.dataGridView1.Rows[i].Cells[0].Value == true) 
        { 

         s.delete(Convert.ToInt32(this.dataGridView1.Rows[i].Cells[1].Value)); 
         i--; 

        } 

       } 
       this.dataGridView1.DataSource = s.getAll(); 

      } 
      catch (Exception nn) 
      { 


      } 


     } 

請幫幫我。

+0

你應該用'先拿到CheckBox控件FindControl()'方法,然後檢查它是否被檢查 –

回答

0

首先,你必須要找到你的CheckBox控件,那麼你可以檢查,檢查或者不喜歡這樣的:

Int32 i; 
    CheckBox k; 

    for (i = 0; i < GridView1.Rows.Count; i++) 
     { 
      k = ((CheckBox)(GridView1.Rows[i].Cells[0].FindControl("chk"))); 
      if (k.Checked == true) 
      { 
       //your code here 
      } 
      else 
      { 
       //your code here 
      } 
     } 
0

您正在嘗試引用尚未初始化的對象(我相信在此實例中爲Row [i])。

嘗試在for循環中放置一個斷點並逐步執行(F10)並檢查我在什麼位置引發異常。

+0

它第一次檢查條件時會拋出異常 – Billz

+0

您可以發佈堆棧跟蹤嗎? –

0

添加更多的驗證

foreach (DataGridViewRow rw in this.dataGridView1.Rows) 
{ 
    if (rw.Cells.Count > 2 && 
     rw.Cells[0].Value != DBNull.Value && String.IsNullOrWhiteSpace(rw.Cells[0].Value.ToString()) && 
     ((bool)rw.Cells[0].Value) && 
      rw.Cells[1].Value != DBNull.Value && String.IsNullOrWhiteSpace(rw.Cells[1].Value.ToString())) 
    { 
      s.delete(Convert.ToInt32(rw.Cells[1].Value)); 

    } 
}