我想在DataGridView
獲得「改變currentcell」事件,但每次我嘗試加載形式(這是另一種形式的孩子),我得到的datagridview_currentcell
事件異常:爲什麼我在引用DataGridView CurrentRow時遇到異常?
SystemNullReferenceException:未將對象設置爲對象的實例。
我想這是因爲我沒有選擇任何行。當然,我可以使用catch
和try
繞過,但我想要一個更優雅的方式,並知道我做錯了什麼。
這裏是我的代碼:
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);