2011-11-29 69 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

相关问题