Posted: 11/11/2011
Dear Expert, Please help me improve my code to add datamember of class to a generic list.
as i am getting "Object reference not set to an instance of an object".my code is :
{
protected void NoOfOptions_SelectedIndexChanged(object sender, EventArgs e) { int NoOfRadio = Convert.ToInt32(NoOfOptions.SelectedItem.Value); int cnt = (int)ViewState["QuestionNo"]; if (NoOfRadio > 0) { for (int i = 1; i <= NoOfRadio; i++) { RadioButton rd = new RadioButton(); rd.Text = " "; TextBox tb = new TextBox(); Table tbl1 = new Table(); Table tbl2 = new Table(); RadioPlaceHolder.Controls.Add(tbl1); RadioTextPlaceHolder.Controls.Add(tbl2); TableRow tr1 = new TableRow(); TableRow tr2 = new TableRow(); TableCell tc1 = new TableCell(); tc1.Height = 25; tc1.Width = 130; TableCell tc2 = new TableCell(); tc2.Height = 25; tc2.Width = 130; tb.ID = "CheckBox" + i; rd.ID = "RadioButton" + i; tb.Attributes.Add("onchange", "SetRadioName(this," + i + ",'ctl00_BodyContentPlaceHolder_" + rd.ID + "')"); tc1.Controls.Add(rd); tc2.Controls.Add(tb); tr1.Cells.Add(tc1); tr2.Cells.Add(tc2); tbl1.Rows.Add(tr1); tbl2.Rows.Add(tr2); AddToOptionList(rd, cnt, NoOfRadio); } } }
private void AddToOptionList(RadioButton rd, int qno, intnopt)
gopt =newgetOption();
List<getOption> liOpt = newList<getOption>();if (ViewState["Option"] != null)
ViewState.Add("Option", liOpt);
else
for (int i = 0; i < nopt; i++)
gopt.Opt[i] = rd.Text;
}
gopt.Qno = qno;
gopt.NoOfopt = nopt;
liOpt.Add(gopt);
ViewState["Option"] = (List<getOption>)liOpt;
Posted: 12/21/2011
Please post more codes here so that we can check the cause of the error. Also I'd suggest you to set a breakpoint at the event and step into it and let us know what line the error blows up.
Posted: 1/11/2012
Hi Rakesh,
Is "getOption" the class that you want to put in the list? if so, then the error is because you are using the gopt object as list.
Try to use this:
private void AddToOptionList(RadioButton rd, int qno, intnopt) { gopt =newgetOption(); List<getOption> liOpt = newList<getOption>(); if (ViewState["Option"] != null) ViewState.Add("Option", liOpt); else { for (int i = 0; i < nopt; i++) { getOption gopt =new getOption(); gopt.Opt[i] = rd.Text; gopt.Qno = qno; gopt.NoOfopt = nopt; liOpt.Add(gopt) } ViewState["Option"] = (List<getOption>)liOpt; }
I'm just guessin that Qno and NoOfopt is a property in your class.
Also, if you want to get the total number of classes in the list, you can just use the Count propertyo f the list.
Ex:
Int TotalNumberOfItemsInTheList = liOpt.Count
Hope this helps.