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));
Related
I have a got Gridview, that gets its data by:
internal void updateGrid()
{
List<String> data = dt.getAlldata(UserID(), ListID());
gridViewer.DataSource = data;
gridViewer.DataBind();
}
After a button click the database is updated and the new data is shown. Everything works fine.
Now I have to replace the string with an Usercontrol:
internal void updateGrid()
{
List<String> data = dt.getAlldata(UserID(), ListID());
gridViewer.DataSource = data;
gridViewer.DataBind();
for (int i = 0; i < gridViewer..Rows.Count; i++)
{
UCControl dum = (UCControl)LoadControl("~/UCControl.ascx");
dum.SetData(gridViewer.Rows[i].Cells[0].Text, false);
gridViewer.Rows[i].Cells[0].Controls.Clear();
gridViewer.Rows[i].Cells[0].Controls.Add(dum);
}
}
After first Page_Load(), everything is shown correctly. But when I click my buttons, the Usercontrols do not repaint. The data is set correctly inside, but it does not update.
Because this Control reacts by javascript on UserInputs on the client side, every Usercontrol has got his own Id that is set by
this.ID = "UCControl" + data[0];
data[0] is unique, but known during the whole process.
Can somebody tell me why the UserControl does not repaint? Or better: How do I tell the Usercontrols to update?
From your code I would say that once the data is bound then you can't go in immediately after and start to change it. You would need to hook into one of the databinding events.
If you were using a list viem ItemDataBound would be a good candidate to hook into. But the GridView has a more limited set of events and doesn't offer that level of control - so you are a bit stuck on that score.
In my experience using dynamic controls in asp.net (LoadControl) is just a bit fraught. I think a better option would be to publicly expose a property in your user control and bind to that.
This question gives a good description of how to achieve this
asp.net user controls binds inside gridview
Hope that helps
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.
Hi
In ASPxGridView, is there a way to get a row by its VisibleIndex or KeyValue so that I can change any column value in it?, I mean something like this:
var row = myGrid.SelectRowByKeyValue(myKeyValue);
OR:
var row = myGrid.SelectRowByVisibleIndex(myKeyValue);
row["Column1"] = true;
Edit:
What I'm tring to do is that every time I hit the button I want to check one specific row (I'm using ajax to not reload all the page);
Thanks
This can be done using the ASPxGridView.GetRow() method. NOTE, that changing the value in the DataRow is not enough. If you want these changes to be preserved, save them to the DB.
Since you are using unbound columns, you should handle the CustomUnboundColumnData event and provide modified data for this row within this event handler. The common approach is described in the Providing Data for Unbound Columns topic. If this does not help, please describe in greater details.
UPDATE
Your approach is incorrect. The ASPxGridView does not provide a method to set a text of a certain cell (TD). Instead, you should force the grid to raise the CustomUnboundColumnData event. This can be done using the ASPxGridView's DataBind method. In this event handler, you should determine the KeyField value of the processed row, compare it with the keyField value of the row where the button was clicked and return the required value. This is how I would implement this feature...
I solved it by using this code:
for (int i = 0; i < myGridView.VisibleRowCount; i++)
{
if ( [My condition] )
{
(
(CheckBox)myGridView
.FindRowCellTemplateControl(i,
myGridView.Columns["MyColumnName"] as GridViewDataColumn,
"My_Unbound_Control_Name"
)
).Checked = true;
}
}
I's may not be the right way to do it but I couldn't solve it another way.
I've just moved to web development and need to know how i can implement below requirement using asp.net and vb.net.
I have three fields in a form which are filled by users. Based on these three values, i need to auto-populate the 4th field. I have planned to implement this in the following way
Write a separate class file with a function to calculate the possible values for the 4th fields based on 1st 3 inputs. This function can return some where between 1-10 values. So I've decided to use drop-down for 4th field, and allow users to select the appropriate value.
Call the above function in onchange function of 3rd field and take and use the return values to populate the 4th field. I'm planning to get the return values in array field.(Does this need a post back?)
Please let me know how if there is better way to implement this.
Thanks.
You may want to consider doing this with Javascript. You could read and control the fields pretty easily with pure Javascript, or using a nice library like jQuery (my favorite). If you did it this way, no post-back would be required and the 4th field would update immediately. (Nice for your users)
You can also do it with ASP.NET for the most part. "onchange" in ASP.NET still requires Javascript as far as I know, it just does some of it for you. A post-back will definitely happen when you change something.
You need javascript or to set autopostback=true on your form elements.
From a user perspective the best thing is to use javascript to populate the field for display, BUT when the form is submitted use your backend function to validate it. This will make sure the user didn't change the value.
An easy way is to use jQuery for the UI (that way you don't have to worry about long winded javascript and deal with browser compatibility as it's already taken care of for you) and have it call to the server for the data. For the server, your easiest route is to return JSON for looping values.
Include your jQuery:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
Then add in a handle for the JavaScript:
<script type="text/javascript">
function autoPopulate() {
var value1 = $('#ddl1').val();
var value2 = $('#ddl2').val();
var value3 = $('#ddl3').val();
var url = 'path/to/your/file.aspx?value1=' + value1 + '&value2=' + value2 + '&value3=' + value3;
$.getJSON(url, function(data) {
data == null ? return false : data = eval(data);
var ddl = $('#ddl4')[0];
for (i = 0; i < data.length; i++) {
var option = new Option(data[i][0], data[i][1]);
if ($.browser.msie) {
ddl.add(option);
} else {
ddl.add(option, null);
}
}
}
}
</script>
(Yes, I know I used a native loop but I'm little lazy here today :) )
Now, for your server side code you'll want your code your page to return data in the format of:
[['value1','text1'],['value2','text2'],['value3','value3']]
so something like:
<script type="vb" runat="server">
Private Sub Page_Init()
// get your data
// loop through it and add in values
// ex.
Dim result As String = "[" //start multi-dimensional array
For Each Item As String In data
result += String.Format("['{0}','{1}'],", _value, _text)
Next
result = result.SubString(0, result.Length - 1) // removes trailing comma
result += "]" // closes off m-array
Response.Write(result)
Response.Flush()
End Sub
</script>
I want to instantly update a status line indicating the number of checked checkboxes across all pages of an asp.net gridview. Right now I am only ably to count the number of checkboxes that are checked on the current gridview page.
Here is my code:
$(document).ready(initAll);
function initAll(){
countChecked();
$(".activeBoxes").click(countChecked);
}
function countChecked() {
var n = $(".activeBoxes input:checked").length;
$("#checkboxStatus").text(n + (n == 1 ? " vehicle is" : " vehicles are") + " selected on this page. ");
if( n == 0){
$(".activateButton").hide();
$("#checkboxStatus").hide();
}else{
$("#checkboxStatus").show();
$(".activateButton").show();
}
}
Keep a hidden text field on your page and everytime you check a box, call a javascript method that will write the 'id' of the checkbox to the hidden field. Each time you postback your page, serialise the hidden field's value to the session in your desired objects structure (be it objects, hash table, array etc).
Upon rendering the page, each checkbox can check the session object structure (that you have created before) and determine if the state of the checkbox was last checked or not.
You could use JQuery to loop through all checkboxes on the page and increment a counter if the checkbox is checked.
You can track the total selection in viewstate (or something similar) on page change. I did something similar tracking the selected row ID's in an array. In my case I had to re-check the items when they returned to the page. Additionally if you allow sorting the selection may move across pages.
Edit: Sorry this doesn't actually your Jquery question, but maybe it will help...
What you're missing is removing the ID. When checking rows and tempid is not checked make sure it is not in saveids.
Do you know that Google is your friend?
Selecting CheckBoxes Inside GridView Using JQuery
The WML Video
And without JQuery but for more perfectionist behavior (like the image below), try this link
alt text http://www.gridviewguy.com/ArticleImages/GridViewCheckBoxTwistAni.gif
I am using a viewstate to keep track of all checked items across all pages and rechecking them upon returning to the page.
I will have to add my viewstate value to the page total and somehow subtract overlapping totals. Since my jquery does not include an id, this will be tricky.
protected ArrayList savedIds;
if (ViewState["SavedIds"] == null) savedIds = new ArrayList();
else savedIds = (ArrayList)ViewState["SavedIds"];
List<int> activateList = new List<int>();
foreach (GridViewRow tt in GridView2.Rows)
{
CheckBox cb = (CheckBox)tt.FindControl("ActivateItem");
HiddenField id = (HiddenField)tt.FindControl("IdField");
if (cb.Checked)
{
int tempId = 0;
string tempId2 = id.Value.ToString();
int.TryParse(tempId2, out tempId);
activateList.Add(tempId);
}
}
foreach (int activateId in activateList)
{
if (!savedIds.Contains(activateId.ToString())) savedIds.Add(activateId.ToString());
}
ViewState["SavedIds"] = savedIds;