Reputation: 155
I'm following this SO post to pass DataGridView to second form, so I can access cells to paint them based on values..
In Form1 I'm creating that DataGridView as below :
namespace LightnessComparision
{
public partial class Form1 : Form
{
public DataGridView dgv = new DataGridView
{
Name = "LightnessGrid",
Visible = true,
DataSource = null,
AutoSize = true,
RowHeadersVisible = false,
ColumnHeadersVisible = false,
ScrollBars = ScrollBars.Both,
AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCellsExceptHeader,
};
/* Public Form1 etc */
public void Button3_Click(object sender, EventArgs e)
{
/* SOME LOGIC */
LightnessTable LightnessForm = new LightnessTable();
dgv.DataSource = resulTable;
LightnessForm.dgv = dgv;
LightnessForm.Controls.Add(dgv);
LightnessForm.AutoSize = true;
LightnessForm.Show();
}
}
}
LightnessTable which is Form looks like :
namespace LightnessComparision
{
public partial class LightnessTable : Form
{
public DataGridView dgv { get; set; }
public LightnessTable()
{
InitializeComponent();
DataGridView_Configuration();
}
private void DataGridView_Configuration()
{
dgv.VisibleChanged += DgView_VisibleChanged;
}
private void DgView_VisibleChanged(object sender, EventArgs e)
{
DataGridView_PaintCells();
}
private void DataGridView_PaintCells()
{
foreach (DataGridViewRow row in dgv.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
if (Convert.ToInt16(cell.Value) < -5)
{
cell.Style.BackColor = Color.Yellow;
}
if (Convert.ToInt16(cell.Value) > 5)
{
cell.Style.BackColor = Color.Black;
}
}
}
}
}
}
However dgv.VisibleChanged += DgView_VisibleChanged; this line throws me error that dgv is null.
What's wrong here?
Upvotes: 0
Views: 109
Reputation: 2299
You call dgv.VisibleChanged += DgView_VisibleChanged;
in constructor (throughDataGridView_Configuration()
call), but for this moment dgv
is not initialized yet.
Consider to pass DataGridView as constructor parameter:
public LightnessTable(DataGridView dgv)
{
InitializeComponent();
this.dgv = dgv;
Controls.Add(this.dgv);
DataGridView_Configuration();
}
and change the call:
public void Button3_Click(object sender, EventArgs e)
{
/* SOME LOGIC */
dgv.DataSource = resulTable;
LightnessTable LightnessForm = new LightnessTable(dgv);
LightnessForm.AutoSize = true;
LightnessForm.Show();
}
Also I moved Controls.Add(dgv);
into the form constructor - it is not necessary, but looks more logical.
Upvotes: 2
Reputation: 948
You are calling DataGridView_Configuration() from LightnessTable constructor, so dgv is still null.
Upvotes: 0