-1
RadioButton yes = null;
RadioButton no = null;
GridViewRow row = GV_College_Information1.Rows[i];
yes = (RadioButton)row.FindControl("yes");
no = (RadioButton)row.FindControl("no");

if (yes.Checked && yes!=null)

I'm getting exception at this statement . Anyone plz guide me through this

Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71
Kunal Jamdade
  • 39
  • 3
  • 8

3 Answers3

0

Remove second condition from if block or you can see sample code below like this

  for (int i = 0; i < GV_College_Information1.Rows.Count; i++)
    {
        RadioButton yes = (GV_College_Information1.Rows[i].FindControl("grdRdo")) as RadioButton;
        if (yes.Checked == true)
        {

        }
    }           
}
0

It is obvious that by some reason this code (RadioButton)row.FindControl("yes") returns null.

You have tried to handle this situation by if (yes.Checked && yes!=null) but in fact you've done it incorrectly (wrong order of confitions to check).

It should be if (yes!=null && yes.Checked) instead.

The reason is: if you attempting to access property of null object - you'll get that exception, so first you have to check if object is not null and only then access its properties and methods.

Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71
0

If the radiobutton with id="row" really exists in the row, you wont get the null reference exception in your if statement. But anyway, you should make the null checking prior to yes.Checked in your if statement, as Andy Korneyev points out.

yes = (RadioButton)(row.FindControl("yes"));
if (yes!=null && yes.Checked)
Avishek
  • 1,896
  • 14
  • 33
  • you should also see Andy Korneyev's answer, and make sure you make the null checking prior to `yes.Checked` in your if statement – Avishek Apr 24 '15 at 11:15
  • He is not casting `row` to `RadioButton`. In fact `(RadioButton)row.FindControl("yes")` is absolute equivalent to `(RadioButton)(row.FindControl("yes"))`. If it was cast of row - it would be written as `((RadioButton)row).FindControl("yes")`. Also , in the case of casting row to radiobutton it should be `InvalidCastException`, not `null` as result of cast. – Andrey Korneyev Apr 24 '15 at 11:16