Add properties to every control with a specific name/pattern in the ID - ASP.NET (VB) - asp.net

I have several controls on a page that contain the word "DATE" in the ID. These are specific text boxes for dates only.
Here is an example of what I need to do for each text box control with "DATE" in the ID:
Birth_Date.Text = fnLib.formatDate(Birth_Date.Text, 1)
Anniversary_Date.Text = fnLib.formatDate(Anniversary_Date.Text, 1)
Rather than do this for every single control, is there a way I could do this in some kind of For Each Loop? I am fairly new to ASP.Net (VB) so I am still learning. Thanks

Technically you could do this with a loop, something pseudocoded like this.
foreach(Control currentControl in this.Controls)
{
var currentTextbox = currentControl as TextBox;
if(currentTextbox != null && currentTextbox.Id.EndsWith("_Date"))
//DO your stuff here
}
But honestly I'm not sure that is going to get you much, especially if there are lots of other controls...As this has to attempt to cast the item to the target type first. WHich if you have a lot of failures, could be a big performance hit.

Related

Binding database data to a dropdownlist

I have been trying for a long time to fix the bugs I'm encountering with my dropdownlists in my project. I'm getting data this with at the moment and it's working fine:
using (InfoEntities ie = new InfoEntities())
{
var sqlddl = (from query in ie.Table_Customers
from q in ie.Accounting_PriceType
where query.TypeID == 1 && q.ID == 1
orderby query.Customers
select query).Distinct().ToList();
DropDownListCust.DataTextField = "Customers";
DropDownListCust.DataValueField = "ID";
DropDownListCust.DataSource = sqlddl;
DropDownListCust.DataBind();
}
Now when the user saves the data and opens the website again I need the saved value that was chosen on the dropdownlist earlier retreived. This also works fine but the problem is I'm getting duplicates. Anyways I'm doing it like this and I'm pretty sure I'm doing it wrong:
On the page load i load my dropdownlist to get all the items plus the following to get the saved value:
DropDownListCust.SelectedItem.Text = sql.Customers;
This makes my DDL very buggy, some items dissapear and also sometimes dupicated values. Can anyone please help? I'm using LINQ but I can use some other methods as long as it's fixed.
Cheers
I solved my problem like this:
DropDownList1.ClearSelection();
DropDownList1.Items.FindByText(sql.Customer).Selected = true;

asp.net dynamic controls values

I am trying to create a poll system that will ask the users for the number of options they would like to add from a dropdownlist.
Then when the user choose a number i would like to add text-boxes for those numbers and finally use asp.net to iterate through the text-boxes and add their values in the database.
Example:
User chooses to add 5 options.
I use Jquery to to append 5 inputs to the form.
User adds their values.
I iterate through the text-boxes and execute a void based on these
values.
i am able to do the first 3 steps but i am stuck on the 4th step. To solve it i tried to use a loop:
foreach (TextBox tb in form1.Controls)
{
Response.Write(tb.Text);
}
but that throws an error:
Unable to cast object of type 'System.Web.UI.LiteralControl' to type 'System.Web.UI.WebControls.TextBox'.
how can i iterate throw the text-boxes?
thanks
Any static content is represented by a LiteralControl, which is why you experience that. A real easy way is to use LINQ:
var ctls = form1.Controls.OfType<TextBox>();
foreach (var ctl in ctls) { .. )
Or check the type as you loop through the controls to make sure it's a textbox first:
foreach (Control tb in form1.Controls)
{
if (tb is TextBox)
Response.Write(((TextBox)tb).Text);
}
Brian's answer seems a solid one. Another option that comes to mind at first sight is:
Declare a function...
Declare a simple array or even a string in js
Iterate from client side your inputs
And for each iteration you should be saving the value in that array or concatenating the value.
The array then can be saved as a string in some asp hiddenfield in order to do your server-side stuff.
Best regards.

ASP Multiselect listbox separator

I have encountered a problem and I didn't manage to find any soultions yet. Let me simplify things a bit.
I have 2 forms, the first contains an ASP ListBox with multi select mode enabled. I submit the form and in the other form I use just for testing purposes this snippet of code:
protected void Page_Load(object sender, EventArgs e)
{
foreach (string formKey in Request.Form.AllKeys)
{
if (formKey != null)
{
if (formKey.Equals("ctl00$MainContent$ListBox1"))
Label1.Text = Request.Form[formKey];
}
}
}
The problems is that the values that come from the listbox (the values that i selected in the previous form) are separated by "," for ex. "test1,test2,test3". How can i change this separator to "$" for example? I need to change it because the actual values may contain "," and i don't manualy feed them to the listbox.
I can't use any other mode of transfering this values between the form because the entire application uses this model. The values that i get are then sent to a workflow where there will be manipulated and in the workflow i need to know where each listbox item starts and ends so it must be an unique separator.
Any help is apreciated! Thank you very much
Thank you MatteKarla but unfortunately this does not solve my problem. Yes, this is a good way of transfering the values from one form to another.
However i must use the method I described above with Request form keys because the listbox is one of many others "parameters" that are generated at runtime and have their values sent to a workflow method that takes this values. And i can't afford to change that in my application.
My problem is that coma (",") separator is used by default with a multiselect listbox.
I thought that there maybe is a method to change that separator from coma to another char because the coma can also be included in the value itself and this will create confusion.
As i said if i select three values test1, test2 and test3, the result with my method will be a string looking like "test1,test2,test3". However a "test1$test2$test3" would be much better.
But I'm affraid that changing this default separator is not possbile. I must think at a method to overcome this problem like replacing before feeding the listbox all the intended coma from the values with some other char not to create confusion. But this is not a great way of doing it.
On your first page/form (First.aspx.cs) create a public property with the listbox:
public ListBox PostedListBox { get { return ListBox1; } }
Set the postback-url for the button to Second.aspx
Second page in the aspx-file after the #Page-directive add:
<%# PreviousPageType VirtualPath="~/First.aspx" %>
Then in Form_Load on Second.aspx.cs you can extract the values:
if (PreviousPage != null)
{
ListBox postedListbox = PreviousPage.PostedListBox;
foreach (var index in postedListbox.GetSelectedIndices())
{
var itemText = postedListbox.Items[index].Text;
}
}
Or you could just try to locate the control by using:
if (PreviousPage != null)
{
var control = PreviousPage.FindControl("ListBox1") as ListBox;
}
Third Edit:
You could use GetValues:
Request.Form.GetValues("ctl00$MainContent$ListBox1");
returns a string array containing each of the selected items.

Request.Form "Collection is only readonly" when trying to set text box content

Saving the values in the Lists & works fine.
abc= (ABC)(Session["xml"]);
string ctrlStr = String.Empty;
foreach (string ctl in Page.Request.Form)
{
if (ctl.Contains("something"))
{
ctrlStr = ctl.ToString();
abc.student[0].marks[j].science.something.Value = Convert.ToDecimal(Request.Form[ctrlStr]);
}
Want to retrieve the values from the saved object when I click on edit button back on the respective dynamic textboxes....
foreach (string ctl in Page.Request.Form)
{
if (ctl.Contains("studentname"))
{
ctrlStr = ctl.ToString();
(Request.Form[ctrlStr]) = abc.student[0].marks[x].science.studentname.ToString();---Gives an error stating the collection is only readonly
}
}
Request.Form — like the Request object generally — is read-only, reflecting the fact that, by the time you are responding to a request, the request itself cannot be changed. ASP.NET uses the values from the form POST to create server controls on the Page, and these allow you to control the values of the input and other form elements that are written to the Response object.
In your case, the TextBox controls are being generated dynamically, so they are not automatically bound to form values — hence your problem. You will need to keep references to the controls when they are created (or find them afterwards using the FindControl() method) and set their Text property.
(original answer follows)
The Controls collection becomes read-only at a certain point in the construction of the page. You have to do manipulation before that point. I don't remember offhand when it is, but you're safe with OnLoad through OnPreRender.
Where is your code firing from?
Update: Okay, I see what you're trying to do. This will be easiest if you're dealing with server-side controls (that is, controls generated by ASP.NET. That would look like this in your aspx (or ascx):
<asp:TextBox runat="server" ID="studentname"/>
Then you could update the value like this:
abc = (ABC)(Session["xml"]);
studentname.Text = abc.student[0].marks[j].science.something.Value.ToString();
That will set the value of the studentname text box automatically without needing to search through all of the Request.Form items. (Assuming you set j somewhere... I don't know the context for that.)
I can't tell for sure from your code, but it looks like you may just have a "plan HTML" input, which would look more like this:
<input type="text" name="studentname"/>
In that case, there is no simple way to update the value from your page's code, so I'd start by making sure that you're using server-side controls.
You can set the Request.Form values with reflection:
Request.Form.GetType().BaseType.BaseType.GetField("_readOnly", BindingFlags.NonPublic | BindingFlags.Instance)
.SetValue(Request.Form, false);
Request.Form["foo"] = "bar";
What you are trying to achieve?
The Form collection retrieves the values of form elements posted to the HTTP request body, with a form using the POST method. - http://msdn.microsoft.com/en-us/library/ms525985(v=vs.90).aspx

I want to add items to an ASP.Net combobox using Javascript

I want to add an item to an ASP.Net combobox using Javascript. I can retrieve the ID (No Masterpage). How can I add values to the combobox from Javascript? My present code looks like this.
//Fill the years (counting 100 from the first)
function fillvarYear() {
var dt = $('#txtBDate').val();
dt = dt.toString().substring(6);
var ye = parseInt(dt);
//Loop and add the next 100 years from the birth year to the combo
for (var j = 1; j <= 100; j++) {
ye += 1; //Add one year to the year count
var opt = document.createElement("OPTION");
opt.text = ye;
opt.value = ye;
document.form1.ddlYear.add(opt);
}
}
To see the value on postback:
string selectedValue = Request.Params[combobox.UniqueId]
Remember, changing the values in a combobox with javascript will cause an Event Validation exception to be thrown, and is generally a bad idea, as you'll have to explicitly disabled event validation.
I'd recommend placing the combobox in an update panel, so you can read txtBirthDate on the server and generate the appropriate data. You then won't have to manually preserve state either.
Always remember, ASP.NET controls are nothing "fancy" - they always end up at some point becoming standard HTML elements.
Try checking out this site. It has a pretty nice demo and overview. Take note however that you are altering the data at the client side - this means you will need to do it on each and every request because the ViewState will not be updated.
TBH, you are probably better off just using a HTML control rather than ASP ComboBox..
Can I ask why you are changing items via Javascript? (out of curiosity) :)
I found a possible solution. I don't know why the earlier code didn't work for me, but the line below
document.form1.ddlYear.appendChild(new Option(ye, ye));

Resources