C# - Using a ListBox to populate other fields - c#

I'm trying to use the selected value of a ListBox control to populate a TextBox with its Text property, and a HiddenField with its value property. It sounds simple enough, and I went with this:
currentGroupTextBox.Text = currentSiteGroupList.SelectedItem.Text;
currentGroupHiddenField.Value = currentSiteGroupList.SelectedValue;
But upon execution, ASP.NET returns an error:
Object reference not set to an instance of an object.
And highlights the first line. currentGroupTextBox and currentGroupHiddenField are two controls which are enabled in the ASPX file so I'm not too sure why ASP.NET would complain about instancing them.

I'm going to try and pull together answers to all of your questions, including those in the comments.
Even if SelectionMode="Single", the listbox starts out without anything being selected, unless you specify which item should be selected in your code.
To test if the SelectedItem is null, use the following code:
if (currentGroupSiteList.SelectedItem != null) {
currentGroupTextBox.Text = currentSiteGroupList.SelectedItem.Text;
currentGroupHiddenField.Value = currentSiteGroupList.SelectedValue;
}
What does your Page_Load code that loads the listbox look like? Is it wrapped with a if (!Page.IsPostBack) check? If not, pressing the button and initiating a postback will reload the listbox, thus losing the SelectedItem that the user selected.

I'd be willing to bet that your first line is choking on referencing currentSiteGroupList.SelectedItem, as that seems the most likely candidate for being a null reference. Make sure your code is executing in the right place within the ASP.NET page lifecycle, such that the SelectedItem is set properly behind the scenes.

SelectedItem from your currentSiteGroupList.SelectedItem is likely to be null (what represents no selection). You need to test it before assigning it to currentGroupTextBox.Text

Is it currentGroupTextBox or currentGroupTextBox that is null?
In debug if stop on that line..is it one or both that are not existing?
A common issue I find is that controls are placed on an asp formview or similar and so the reference to that control is not actually its id/name, but more likely you need to do;
TextBox myTextBoxReference = (TextBox) formName.FindControl("currentGroupTextBox")
string theValue = myTextBoxReference.Text
Another often issue is the page life cycle. So if your object is not on a form but maybe you are referencing it before it exists in the postback.
hth

Related

ASP .Net - Change/Update Dynamically Created Textbox

OK, got pretty far on this one, but need an assist from someone with superior ASP skills. I'm using code behind to populate an ASP table with the results of a SQL query. The read-only values are stored in the .text of some of the table cells, while read-write values are stored in .text of textbox controls (dynamically created and added to table cells.)
This works fine on the first load. When the page reloads with a different query (for example: a user selects a different column to order by,) the table cell values repopulate correctly, while the textbox values remain unchanged. Throwing in a table.rows.clear() prior to the query does not seem to fix this.
More info:
I created a method to wipe all textbox.text values using table.findcontrol(). When tied to a button, this method works to spec (which indicates findcontrol is able to find/update the textboxes,) though all affected textboxes remain the blank if the page is reloaded. If placed in the page load, the method does nothing (textboxes retain their former values.) In debug mode, findcontrol pulls a value when used on the button, but comes up null when added to pageload. I have done this with table.rows.clear() commented and uncommented.
I have also attempted to throw all the code into oninit. This doesn't seem to make any appreciable difference.
Dynamic controls must be added on each page request, preferably during the Init event. It sounds like you are not recreating them on time.
Add them on every single page request and, as part of the page life cycle, they will receive their values from the viewstate
In order for dynamic controls to retain their values you need to:
a.) Ensure Viewstate is enabled for the page.
b.) Recreate the controls on every page load ensuring you create the controls with the same IDs as were given to the controls originally. Also you need to do this before the viewstate is loaded (preferbly in the Onit or PreInit method. See the page life cycle here: http://msdn.microsoft.com/en-us/library/ms178472%28v=vs.100%29.aspx

Using C#, how can I read the content of dynamic created textboxes?

Hy,
I have created some dynamic textboxes with standard content.
Does anyone know how can I read the content of these textboxes (assuming that user modified the standard content) when I press one button?
Thanks a lot.
Jeff
Update
This is how I am creating the textboxes:
foreach (string name in listOfNames)
{
TextBox tb = new TextBox();
tb.Text = name;
tb.BorderStyle = BorderStyle.None;
tb.BorderWidth = 0;
tb.Font.Name = "Arial";
tb.Font.Size = 8;
}
The specific will vary depending on the technology you are using. However the concept would remain very similar, though for ASP.NET it will be a little more interesting.
WinForms/WPF/Silverlight
Maintain a list of the dynamically created textboxes and when the button is pressed you can run through the list of textboxes and read the Text property to get the user input.
ASP.NET - After the tag update it seems this section is most appropriate to your requirement.
For ASP.NET you will need to create the textboxes in an override of the OnInit method, this should happen on each postback. Then in the Button.Click event you can read the user input from the textboxes that you created in the OnInit function. You need to ensure that the controls are created with the same ID on each post back.
You need to ensure that the text boxes are recreated on every postback.
If you do not recreate them, you will not be able to access their properties or events.
The best place to create dynamic controls is the page Init event handler.
I suggest reading up on the ASP.NET page life cycle.
Update (following updated question)
Make sure to set an ID (and a different one, at that) for the text boxes, so you can refer to them later on.
I can't see where you are adding these controls to the page either.
Request.Form is a collection of Key-Value pairs that represents all of the data coming back from the ASP.NET request. If you access that you can get any value whether its control is specified in the ASPX code or dynamically created in the code behind file.
You can also get their values placed back in them automatically if you recreate them during the init part of the page lifecycle. If you do this, their values will be set when ASP.NET recreates the state of the page and applies the values from the form.
You should be able to access them as you would a normal control, you just need to get a reference to the control.
Remember to re-create all controls on each postback.
this is a useful article on dynamic controls in asp.net

ASP.NET controls added dynamically not visible from the code behind

I'm adding a dynamically built set of checkboxes to an asp.net page from the code behind with something like this in a recursive fashion:
pnlPageAccessList.Controls.Add(myCheckboxControl);
The controls show up fine on the page, but they don't show up when I view source, nor can I access them from the code behind.
If I add the controls in the on_init method, they work. But I have some business rules driving changes to the list of controls itself that require I fire the add method elsewhere.
Has anyone seen this before? I'm away from work so I can't copy the exact code.
I have two terrible ideas for how to get it working. One involves some jQuery and a set of hidden controls holding a big array of integers; the other is run the method on_init AND on my other events so the controls at least show up. Both smell like ugly hacks. The second one I suspect won't work to read the values out of the checkboxes.
On the server side the page is recreated from scratch every postback, so if you add any controls dynamically, you have to re-add them on every postback.
As you add the controls at runtime they are not known at compile time, so there is no variables declared for the controls in the Page object. If you want to access the controls you either have to keep the reference from when you create the controls, or locate them in the Controls collection where you put them.
If you can set the ID for the checkbox controls you can use the FindControl method from code behind to retrieve the control instances.
#Anero is right that you can add an ID and use FindControl.
You can also use a checkbox list, and add checkboxes to that list. Then they're already in a predefined control in your markup and code-behind.
You don't say where the method has to be fired, but once they're added dynamically, they do have to be added on every postback. You probably have a little more flexibility than just adding them at the Init event, as long as you stay aware of where things like validation occurs (if it matters in this case), or where you want to handle the checkbox contents. You can defer as late as PreRender for getting checkbox content.
Well, looks like I'm going to have to do it clientside. Thanks for the answers. I'd be able to do it On_Init, but doing it clientside with a hidden control is gonna save me a lot of overhead and be more flexible moving forward.
If anyone's curious, here's the jQuery for finding all the checked checkboxes and putting their value attribute into a hidden control in a comma delimited list:
<script type="text/javascript">
$(document).ready(function () {
$('[id*=PagesPanel]').find(':checkbox').click(function () {
$('[id*=PagesPanel]').find(':checked').each(function () {
$('[id*=lblHiddenPageArray]').append($(this).val() + ", ");
});
});
});
</script>

how to get text box value in page init?

I am using asp.net 2.0
I set a hidden text box from javascript and on postback, i want to check the value stored on the text box in page init event. Here is what i tried
string t = Request.Form["currentMode"].ToString();
but i get an error saying " Object reference not set to an instance of an object."
Any idea?asp.
In init the postback values have not been loaded into the controls yet, you could in theory fish the values from Request.Form variables, but they are named as the client ID of the controls. If your controls are in any container like a contentplaceholder or detailsview they will have various guff prepended on the ID. e.g. ctl00$cphContentBody$txtMyTextbox could be the id of a control that has a server side id of txtMyTextbox.
Init is the page life cycle where everything is initialized. You can't thrust that anything is availble. In order to do that you have to use the Page_Load event...
I came across this the other day while trying to build->submit->retrieve values from a dynamically created form (assembled during the Init() event of a postback). As Ben stated, you can use the Request.Form collection to pull out the values of the page's controls manually, using the UniqueID of the desired control (which will contain the "guff" Ben is talking about).
Of course, this is only necessary when trying to discover the value of a page's control before it is populated from viewstate (before LoadComplete). Otherwise, you could simply do something like TextBox1.Text.

FindControl() returning copy?

I'm trying to use FindControl() to SET the values of some DropDownLists on a page.
for some reason, it appears that FindControl() is returning a copy of the control object as opposed to a reference, I was under the impression that this would not be the case due to the lack of a copy constructor for Controls?
<EDIT>
Ok, it apparears that it is not in fact returning a copy, it's simply not letting me set the visibilty of a control, the other properties I'm setting work fine.
Does anyone have any insight as to why this might be the case?
I've tried setting it in quick-watch mode then looking at the value straight away, and that isn't actually changing the value either!
</EDIT>
<EDIT> (two)
Ok, I'm doing this in Page_Load, and it's not in a gridview (I like how you guys assumed that one cus I was using FindControl()).
I'm doing this as there is a set of operations I have to perform on a dynamic number of similarly named lists, and it's MUCH better to do it in a loop than to hard code it.
</EDIT>
Can anyone help?
Cheers, Ed
Edit:
Whoa, wait... are you setting the Visible property to true rather than false?
In your comment, you mention it changes back instantly. The Visible property will evaluate to false if it's parent is set to be invisible, no matter how often you tell it the value should be true.
Where are you calling FindControl() and setting the Visible property?
For info, FindControl() gets a reference to a control in the current naming container, based on a string id and does not copy the control. In order to work with the control, you should cast it to the type of control that you expect -
DropDownList ddl = (DropDownList)e.Row.FindControl("myDropDownList");
this example would allow you to work with a DropDownList control in the OnRowDataBound event of a GridView.

Categories