2011-11-29 71 views
0

我想在DataGridView獲得「改變currentcell」事件,但每次我嘗試加載形式(這是另一種形式的孩子),我得到的datagridview_currentcell事件異常:爲什麼我在引用DataGridView CurrentRow時遇到異常?

SystemNullReferenceException:未將對象設置爲對象的實例。

我想這是因爲我沒有選擇任何行。當然,我可以使用catchtry繞過,但我想要一個更優雅的方式,並知道我做錯了什麼。

這裏是我的代碼:

Form2.CS

namespace AsefotSystem 
{ 
    public partial class ownerReport : Form 
    { 
     public ownerReport() 
     { 
      InitializeComponent(); 
      loadDB(); 
      setGrid(); 
     } 

     private void loadDB() 
     { 
      string connetionString = null; 
      OleDbConnection connection; 
      OleDbDataAdapter oledbAdapter; 

      DataSet ds = new DataSet(); 
      string sql2 = null; 
      connetionString = ConfigurationManager.ConnectionStrings["RiskDB"].ConnectionString;    
      sql2 = "select * From tbl2_asefot"; 
      connection = new OleDbConnection(connetionString); 

      try 
      { 
       connection.Open(); 

       oledbAdapter = new OleDbDataAdapter(sql2, connection); 
       oledbAdapter.Fill(ds, "Asefot"); 
       oledbAdapter.Dispose(); 

       connection.Close(); 
       dsAsefotGrid = ds; 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message); 
      } 
     } 

     private void setGrid() 
     { 
      Controls.Add(dataGridView1); 
      dataGridView1.DataSource = dsAsefotGrid.Tables[0]; 
     } 

     private void dataGridView1_CurrentCell(object sender, EventArgs e) 
     { 
      try 
      { 
       textBox1.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[2].Value.ToString(); 
       textBox2.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[1].Value.ToString(); 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.ToString()); 
      } 
     } 

     DataSet dsAsefotGrid; 
    } 
} 

Form2.Designer.CS:

this.dataGridView1.CurrentCellChanged += new System.EventHandler(this.dataGridView1_CurrentCell); 

回答

0

取而代之的是try{}catch{}的,你可以測試是否CurrentCell甚至CurrentRow是否t null

if(dataGridView1.CurrentCell != null) 
    { 
     textBox1.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[2].Value.ToString(); 
     textBox2.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[1].Value.ToString(); 
    } 
0

dataGridView細胞沒有價值,你要保存的null的字符串。

嘗試捕捉異常並告知他在小區

try 
{ 
    textBox1.Text = dataGridView1.Rows[dataGridView1. 
    CurrentRow.Index].Cells[2].Value.ToString(); 
} 
catch(NullReferenceException) 
{ 
    MessageBox.Show("You cannot process an empty cell"); 
} 

寫東西的用戶請找到以下鏈接瞭解更多信息:

https://msdn.microsoft.com/en-us/library/sxw2ez55.aspx

相關問題