This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I attach event with radiobuttonlist in code behind page, radiobuttonlist is inside a
listview .When I run program it generates an error :
"object referance not set to instant of object"
.aspx code:
<asp:ListView ID="ListView1" runat="server" >
<ItemTemplate>
<tr><td>
<asp:RadioButtonList ID="radiobuttonlist4" runat="server" AutoPostBack="true"
RepeatDirection="Horizontal"
OnSelectedIndexChanged="selected" Width="240px">
<asp:ListItem Value="agree"></asp:ListItem>
<asp:ListItem Value="disagree"></asp:ListItem>
<asp:ListItem Value="strongagree"></asp:ListItem>
<asp:ListItem Value="strongdisagree"></asp:ListItem>
</asp:RadioButtonList>
</td>
</tr>
</ItemTemplate>
</asp:ListView>
.aspx.cs Code
assessdal s = new assessdal();
ListView1.DataSource = s.showop1();
ListView1.DataBind();
RadioButtonList list= ListView1.FindControl("radiobuttonlist4") as RadioButtonList;
list.SelectedIndexChanged += new EventHandler(handle);
public void handle(object sender, EventArgs e)
{
Label2.Text = "y";
}
First, i fixed a ton of typos in your code.
Second, it's not finding it because FindControl is being called on ListView1, not the page (or the control hierarchy in which it exists) and FindControl only looks within that instance's child controls.
Try Page.FindControl("radiobuttonlist4") to find it in the page.
You should attach the event handler declaratively on the aspx, that's the easiest way.
<asp:RadioButtonList ID="radiobuttonlist4" runat="server" AutoPostBack="true"
RepeatDirection="Horizontal"
OnSelectedIndexChanged="selected"
Width="240px">
</asp:RadioButtonList>
Since the ListView can contain multiple items, the NamingContainer of a control in it's Itemtemplate is not the ListView, but the ListViewItem. That ensures that every control gets a unique id on clientside.
So you can find your RadioButtonList in the button's click event handler in this way:
var button = (Button)sender;
var item = (ListViewItem)button.NamingContainer;
var radiobuttonlist4 = (RadioButtonList)item.FindControl("radiobuttonlist4");
If you want to "find" the RadioButtonList in it's SelectedIndexChanged event, simply cast the sender argument accordingingly (var rbl = (RadioButtonList)sender;).
Related
I have a survey composed of nested repeater objects of questions that are within subjects. Everything is populated dynamically via the database. Each question has a radiobuttonlist of answers. There can be one or many questions per subject. When the user complete the form and click submit, how does my click function loop through all controls, find each radiobuttonlist and its' selected answer?
<div id="qDiv" runat="server" >
<asp:Repeater runat="server" ID="rptSubject" OnItemDataBound="rptSubject_ItemDataBound">
<ItemTemplate>
<h2><%#DataBinder.Eval(Container.DataItem, "Subject")%></h2>
<asp:Repeater runat="server" ID="rptQuestion" OnItemDataBound="rptQuestion_ItemDataBound">
<ItemTemplate>
<p><%# DataBinder.Eval(Container.DataItem, "Question")%></p>
<asp:RadioButtonList ID="rblAnswers" runat="server"></asp:RadioButtonList>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
</div>
protected void submitButton_Click(object sender, EventArgs e)
{
???
}
As well as the selected answer, can I also get access to the repeaters values question & subject in the click function?
Use the Page.FindControl(string) method to find server controls based on a known ID pattern.
I have a radiobuttonlist, a label, and a dropdown as follows:
<asp:RadioButtonList id="rbList" runat="server" AutoPostBack="true" EnableViewState="false"
OnSelectedIndexChanged="rbList_SelectedIndexChanged"
RepeatLayout="Table" RepeatDirection="Horizontal" RepeatColumns="3">
<asp:ListItem Selected="True"> Radio 1 </asp:ListItem>
<asp:ListItem> Radio 2 </asp:ListItem>
<asp:ListItem> Radio 3 </asp:ListItem>
</asp:RadioButtonList>
<asp:Label runat="server" ID="lbl" text="1,2" EnableViewState="false"></asp:Label>
<asp:DropDownList runat="server" ID="ddl" Visible="false">
</asp:DropDownList>
My rbList_SelectedIndexChanged is as follows:
protected void rbList_SelectedIndexChanged(object sender, EventArgs e)
{
if (rbList.SelectedIndex == 0 | rbList.SelectedIndex==1)
{
lbl.Text = "1,2";
ddl.Visible = false;
//ddl.Attributes.Add("style", "display:none");
}
else if (rbList.SelectedIndex == 2)
{
lbl.Text = "3";
ddl.Visible = true;
//ddl.Attributes.Add("style", "");
}
}
Now when I change from radio3 to radio2, the event is getting fired as usual and everything looks good. But when I change from radio3 to radio1, I don't see the event getting fired (I inserted a breakpoint) the ddl stays visible but the value of lbl changes to 1,2.
My 2 questions are as follows:
1) Why is the event not getting fired on changing from radio3 to radio1?
2) How is the label value getting changed when the event is not firing?
Any help or comments are much appreciated..Thanks in advance!
I am not sure this is a bug or not, but...
When EnableViewState="false" with DDL or RBL and user trying to pick the first list item (index 0), the SelectedIndexChanged will NOT get fired.
If you set EnableViewState="true", then the DDL or RBL should work properly when user pick the first list item while non-first item was selected...
Preselecting a radio button in your markup is causing your problems. going from any other option back to option 1 will not trigger the changed event.
this line is your culprit.
<asp:ListItem Selected="True"> Radio 1 </asp:ListItem>
if you remove the Selected attribute the event should register properly
<asp:ListItem> Radio 1 </asp:ListItem>
you could handle the preselection in your code behind.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
rbList.SelectedIndex = 0;
}
}
As far as I can tell, programmatically setting SelectedIndex (even on first post) results in the same behaviour as setting Selected="True" on the markup.
The only sure-fire way seems to be using an UpdatePanel with the RadioButtonList as an async trigger, making sure the markup changes with every change.
That is, unless you want to go the jQuery route..
I had a similar problem, but it had to do with the "ChildrenAsTriggers" property of the update panel being set to false. All other radio button indexes worked fine this way, except index 0.
I'm not sure what to do here, I might have to use viewstates, but I need help.
I have a dropdown list, I am not databinding. I would know if I was I should do a Page.IsPostBack and not databind.
<asp:DropDownList ID="ddlWeeklyWeightIn" runat="server">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
</asp:DropDownList>
Now in my code behind I have this:
protected void Button1_Click(object sender, EventArgs e)
{
string wwin = "";
wwin = ddlWeeklyWeightIn.SelectedItem.Text;
}
On the button click is always "1", never the selected item.
Thank you
Aspx side:
add autopostback=true to dropdown property and and use listitem as following:
ListItem Text="4" Value="4"> etc
Code Behind: string wwin = ""; wwin = ddlWeeklyWeightIn.SelectedValue;
try adding EnableViewState="True" to your dropdown control.
A post back is causing to reset your selected value. either use if(!IsPostBack) or use update panel to prevent post back.
This is just to make sure but could you try using:
<asp:DropDownList ID="ddlWeeklyWeightIn" runat="server">
<asp:ListItem Text="1"></asp:ListItem>
<asp:ListItem Text="2"></asp:ListItem>
<asp:ListItem Text="3"></asp:ListItem>
<asp:ListItem Text="4"></asp:ListItem>
</asp:DropDownList>
Could you check you don't just SET the selected item during page's initialization?
In asp.net I have a table in database containing questions,date of submission and answers.On page load only questions appear.now i want to use any link which on clicking show answers and date specified in table data, either in textbox or label and clicking again on that link answer disappear again like expand and shrink on click.
So what coding should i use for this in C#?
I believe you could handle the ItemCommand event of the Repeater.
Place a LinkButton control for the link that you want the user to click in the Repeater's item template. Set the CommandName property of this to something meaningful, like "ShowAnswers". Also, add a Label or TextBox control into the Repeater's item template, but set their Visible property to false within the aspx markup.
In the code-behind, within the ItemCommand event handler check if the value of e.CommandName equals your command ("ShowAnswers"). If so, then find the Label or TextBox controls for the answers and date within that Repeater item (accessed via e.Item). When you find them, set their Visible property to true.
Note: you could take a different approach using AJAX to provide a more seamless experience for the user, but this way is probably simpler to implement initially.
I think the implementation would look something like this. Disclaimer: I haven't tested this code.
Code-Behind:
void Repeater_ItemCommand(Object Sender, RepeaterCommandEventArgs e)
{
if (e.CommandName == "ShowAnswers")
{
Control control;
control = e.Item.FindControl("Answers");
if (control != null)
control.Visible = true;
control = e.Item.FindControl("Date");
if (control != null)
control.Visible = true;
}
}
ASPX Markup:
<asp:Repeater id="Repeater" runat="server" OnItemCommand="Repeater_ItemCommand">
<ItemTemplate>
<asp:LinkButton id="ShowAnswers" runat="server" CommandName="ShowAnswers" />
<asp:Label id="Answers" runat="server" Text='<%# Eval("Answers") %>' Visible="false" />
<asp:Label id="Date" runat="server" Text='<%# Eval("Date") %>' Visible="false" />
</ItemTemplate>
</asp:Repeater>
I'm trying to do a job filter for the list of jobs on our website. The filter for the job type is wrapped in an UpdatePanel and the button to apply the filters redirects back to the same page.
This is because I will be using the umbraco.library:RequestQueryString in the XSLT to populate the jobs list.
However, the querystring filter value doesn't seem to select the RadioButtonList. For example:
The page loads, but nothing happens because vt is null:
protected void Page_Load(object sender, EventArgs e)
{
string vt = Request.QueryString["vt"];
if (vt != null)
{
foreach (ListItem li in rblVacancyType.Items)
{
if (li.Value == vt)
{
li.Selected = true;
}
}
}
}
<asp:UpdatePanel ID="upSearchFilters" runat="server">
<ContentTemplate>
<p>
<asp:RadioButtonList ID="rblVacancyType" runat="server">
<asp:ListItem Text="All" Value="all"></asp:ListItem>
<asp:ListItem Text="Permanent" Value="permanent"></asp:ListItem>
<asp:ListItem Text="Temporary" Value="temporary"></asp:ListItem>
</asp:RadioButtonList>
</p>
</ContentTemplate>
</asp:UpdatePanel>
Here's the button:
<asp:ImageButton ID="ibFilters" ImageUrl="~/images/buttons/filter-button.png" OnClick="ibApplyFilters_Click" runat="server" />
Here's the procedure:
protected void ibApplyFilters_Click(object sender, EventArgs e)
{
Response.Redirect("/careers/join-us/?filters=true&vt=" + rblVacancyType.SelectedValue.ToString());
}
Yet when the page redirects the first time, nothing is selected, I click permanent, permanent gets selected. If I then select 'All' or 'Temporary' the selection doesn't change.
Any ideas?
Based on the behavior (it works the first time) I believe this describes what's happening:
MyPage.aspx (original load)
Page controls initialized to default
Page Load - No query string, no radio button selected
(user clicks button - causes postback)
MyPage.aspx (postback)
Page controls initialized to default
Radio Button Set from ViewState
Page Load - No query string, no radio button selected
ButtonClick - uses radio button setting, does response redirect
MyPage.aspx?VT=Permanent (load from redirect)
Page controls initialized to default
Page Load - Query string set, radio button selected
(user clicks button - causes postback)
MyPage.aspx?VT=Permanent (postback)
Page controls initialized to default
Radio Button Set from ViewState
Page Load - Query string set, radio button set to Permanent (Here is the problem)
ButtonClick - uses radio button setting, does response redirect
I believe a simple (if !IsPostback) will fix things
Sounds like postback values being re-applied. See this article on ASP.NET page lifecycle: http://msdn.microsoft.com/en-us/library/ms178472.aspx.
Values for controls are re-applied via postback after page_load.
Due to the strange nature of code + postbacks the logic in Mark's answer seems to be quite accurate, but the suggested fix did not work as I had tried that as a possible solution. The below is a modification, but as far as I could see it works. Give it a try, it might work out for you.
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="upSearchFilters" runat="server">
<ContentTemplate>
<p>
<asp:RadioButtonList ID="rblVacancyType" runat="server"
AutoPostBack="True">
<asp:ListItem Text="All" Value="all"></asp:ListItem>
<asp:ListItem Text="Permanent" Value="permanent"></asp:ListItem>
<asp:ListItem Text="Temporary" Value="temporary"></asp:ListItem>
</asp:RadioButtonList>
</p>
<p>
<asp:ImageButton ID="ibFilters" runat="server" CausesValidation="False"
Height="30px" OnClick="ibApplyFilters_Click" />
</p>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
ibFilters.PostBackUrl = "~/WebForm1.aspx?filters=true&vt=" + rblVacancyType.Text;
string vt = Request.QueryString["vt"];
}
Important:
The way this is set up, it will maintain your selection, update the filter parameters in the url on button push, and then assign vt the correct value to be used on filtering anything else on your page.
You must change out my "~/WebForm1.aspx?filters=true&vt=" for your url as well.