Setting SelectedIndex -1 ASP.NET DropDownList - asp.net

Is there a way to select -1 index without adding a new ListItem("", "-1",true)) from code behind like jQuery does?
Here is an example:
http://jsfiddle.net/eL8sn/

If you're binding it on Page_Load event it does a post back (AutoPostBack='True').It will simply rebind ever time the index is changed
if (!IsPostBack)
{
BindDropDownList1();
}
(or)
If the above solution dosen't work try to add an empty item as shown:
this.myDropDownList.Items.Add(new ListItem("Select...", ""));

Do you mean like this?
DropDownList1.SelectedIndex = -1;
That's how one usually does it from code-behind.
ETA: I now see what you are talking about. And I'm afraid I don't see how it can be done from server side. All you can do on the server side is control the rendering. As far as I can tell, even if you render this code:
<select id="testSelect" selectedIndex="-1">
... it still appears with the top option appearing to be selected.
It looks as if only by explicitly setting it to -1 with javascript after rendering will it appear with absolutely nothing selected. It appears as if it can't be done declaratively in HTML.
If you can find a way to write the tag in HTML so that it appears this way on load, then you could tweak the rendering in code-behind (using .AddAttribute() or similar) but if it can't be done with a declaration, it'll need javascript.
(You could of course write a jQuery snippet to change all your dropdowns to selectedIndex = -1, but you'll have thought of that!)

You can do this
string selectStr = "SELECT";
string allStr = "ALL"
ListItem allLI = new ListItem(allStr,allStr);
ListItem selectLI = new ListItem(selectStr,selectStr);
DropDownList.Items.Add(selectLI);
DropDownList.Items.Add(allLI);
//code to fill the DropDownList with the list that your query returns
DropDownList.SelectedValue = selectStr;

Related

using JavaScript, find the ClientID of .NET control nested deep within a master page

The short question:
*takes deep breath*
How I can ClientID of TableRow inside Table added to PlaceHolder, which is in a UserControl inside a Web Part added to a SharePoint page using a MasterPage?
The explanation:
I'm building a usercontrol that dynamically shows SPList items, one per Web.UI.Table(). The 2nd row of the Table() will be hidden at first, with an image used to initiate some JavaScript to hide/show the row at the clients browser (rather than use postback or ajax - I have reasons).
The Table() is then added to a PlaceHolder in a UserControl, which is then used by a WebPart, and that WebPart is added to a SharePoint Page, which of course uses a MasterPage. I'm having real trouble working out the JavaScript method to find the ClientID of the TableRow, given that it's nested so deeply.
My .ascx code looks something like this..
<script type="text/javascript">
function showHidden(itemId) {
var controlId = document.getElementById('<%= phDownloadTable.ClientID %>');
//alert(controlId);
document.getElementById(controlId).style.display = (document.getElementById(controlId).style.display == "table-row") ? "none" : "table-row";
}
</script>
<asp:PlaceHolder ID="phTable" runat="server"></asp:PlaceHolder>
and my .cs codebehind is something like this..
Table myTable = new Table();
TableRow hiddenRow = new TableRow();
hiddenRow.ID = "row" + itemId;
hiddenRow.Attributes.Add("style","display: none;");
... create TableCells and add to hiddenRow...
TableRow displayRow = new TableRow();
TableCell toggleCell = new TableCell();
Image toggleImage = new Image();
toggleImage.ImageUrl = "/images/myimage";
toggleImage.Attributes.Add("onclick","javascript:showHidden('" + hiddenRow.ClientID + "');
toggleCell.Controls.Add(toggleImage);
displayRow.Cells.Add(toggleCell);
... create more TableCells and add to displayRow
myTable.Rows.Add(displayRow);
myTable.Rows.Add(hiddenRow);
the result is that the toggleImage "onclick" attribute shows showHidden('row999');, which passes 'row999' to the JavaScript function, but I cannot figure out there how to get the full clientId of the TableRow it refers to.
The source of my page shows the clientId to be ctl00_SPWebPartManager1_g_eda9b9e9_4c7a_48e0_a2aa_fd8cdd65de6c_ctl00_row999, which is longer than I'm used to seeing, and seems to contain two 'ct100_' parts, suggesting multiple levels of controls.
Any ideas would be greatly appreciated. I've tried all the usual avenues (googleing for 'javascript .net control client id' and the like, but so far I've not found anything that helps. Most suggest document.getElementById('<%= myControl.ClientId %>')... which is fine, but I don't know 'myControl' - I need that send from the toggle image.
Fingers crossed!!
Kevin
If you cant set the client id, you should be able to set a class, and that should be respected by .nat.
Them you can select the element by class name.
JavaScript has no wildcard selection options. Try using jQuery, that makes things more flexible.
Then you can use something like:
$("tr[id*='<%= phDownloadTable.ClientID %>']").css("display", your value);
this way you will still find the right element, even when it's moved to another place on the page.
Here is a more detailed explanation on how to use these wildcard selectors:
http://api.jquery.com/attribute-contains-selector/
With plain JavaScript you can do a document.getElementsByTagName('tr') and then loop those to find the right object.
If you are using Framework 4.0 you can set the ClientIdMode of the page like this:
Page.ClientIDMode = System.Web.UI.ClientIDMode.Static;
That way you can have more predictable client ids. For example, you can have id's without all the ctl00_ prefixes.

How can I execute JavaScript from my code-behind after my UpdatePanel has finished loading its DOM elements?

I have an UpdatePanel with a repeater in it that is re-bound after a user adds an item to it via a modal popup.
When they click the button to add a new row to the repeater the code-behind looks something like this:
protected void lbtnAddOption_Click(object sender, EventArgs e)
{
SelectedOption = new Option()
{
Account = txtAddOptionAccountNumber.Text,
Margin = chkAddOptionMargin.Checked,
Symbol = txtAddOptionSymbol.Text,
Usymbol = txtAddOptionUsymbol.Text,
};
Presenter.OnAddOption(); // Insert the new item
RefreshOptions(); // Pull down and re-bind all the items
mpeAddOptionDialog.Hide(); // Hide the modal
// ... Make call to jQuery scrollTo() method here?
}
This works fine and the new row will show up quickly via the UpdatePanel.
However, there are often hundreds of rows and where the new one is added is based on the current sorting column used.
So, I wanted to take this as a chance to use the sweet jQuery ScrollTo plugin. I know that if I give it the ID of my overflowed container div and the ID of an element within it, it will smoothly scroll straight to the users newly added row.
However, there are two problems:
I need to find the appropriate row so I can snag the ClientID for it.
I need to execute the jQuery snippet from my code-behind that will cause my newly updated repeater to scroll to the right row.
I've solved #1. I have a reliable method that will produce the newly added row's ClientID.
However, problem #2 is proving to be tricky. I know I can just call ScriptManager.RegisterStartupScript() form my code-behind and it will execute the JavaScript on my page.
The problem I'm having is that it seems that it is executing that piece of JavaScript before (I'm guessing) the newly refreshed DOM elements have fully loaded. So, even though I am passing in the appropriate jQuery line to scroll to the element I want, it is erroring out for me because it can't find that element yet.
Here is the line I'm using at the end of the method I posted above:
string clientID = getClientIdOfNewRow();
ScriptManager.RegisterStartupScript(this, typeof(Page), "ScrollScript", String.Format("$(\"#optionContainer\").scrollTo(\"{0}\", 800);", clientID), true);
What do I need to do so I can ensure that this line of JavaScript isn't called until the page with the UpdatePanel is truly ready?
If the stuff you need to process is in the update panel, then you need to run your JS once that panel is loaded. I use add_endRequest for that. This below is hacked from something rather more complex. It runs once on document ready, but installs the "end ajax" handler which is triggered every time your update panel is updated. And by the time it fires, it's all there for you.
var prm = Sys.WebForms.PageRequestManager.getInstance();
jQuery(document).ready(function () {
prm.add_endRequest(EndRequestHandler);
});
function EndRequestHandler(sender, args) {
// do whatever you need to do with the stuff in the update panel.
}
Obviously you can inject that from code-behind if you want.
You can use the Sys.Application.load event which is raised after all scripts have been loaded and the objects in the application have been created and initialized.
So your code would be:
string clientID = getClientIdOfNewRow();
ScriptManager.RegisterStartupScript(this, typeof(Page)
,"ScrollScript"
,String.Format("Sys.Application.add_load(function(){{$(\"#optionContainer\").scrollTo(\"{0}\", 800);}});"
, clientID)
, true);

How can I get value from radio-button inserted into innerHtml

I have sort of a table with a radio-button column. I managed to make radio-button column work dynamically inserting into a cell (div if matter). But, on postback innerHtml hasn't been updated with "checked" attribute.
Could you give me an idea how can I find out (on the server) if radio-button has been checked?
More info: This is on user control inside update panel.
This would be good post on my topic, still doesn't help
Any reason you cannot use a standard asp:RadioButton and use javascript to ensure it is mutually exclusive. I have done this before by adding a custom attribute to the radiobutton and then using a js function to uncheck all items with that attribute and then check the selected one. This works around the IE issue which prevents the groupname attribute from working on radioboxes that are in different containers.
radioButton.InputAttributes.Add("ClientGroupName", "grpRadioList");
radioButton.InputAttributes.Add("onclick",
string.Format(
"javascript:radiobuttonToggle('{0}','ClientGroupName','grpRadioList');"
,radioButton.ClientID));
and use the following JS to uncheck all radios and then check the one you want.
Note i used InputAttributes instead of Attributes as the radiobutton is wrapped inside a span tag so InputAttributes is for items added to the actual input control rather than the span.
function radiobuttonToggle(selectedRB, attribName, attribValue)
{
var objRadio = document.getElementById(selectedRB);
for(i = 0; i < document.forms[0].elements.length; i++)
{
elm = document.forms[0].elements[i];
if (elm.type == 'radio')
{
if(elm.getAttribute(attribName) == attribValue)
elm.checked = false;
}
}
objRadio.checked = true;
}
You can then expose radioButton.Checked as a property in your CS file and reuse this as a control.
Check Form.Request("radio-name") != null
You only get a non-null value when it's been checked.
Make sure your page elements are being rebuilt correctly on postback. Any binding process that inserted the radio buttons the first time around will have to be re-run before you can access them the second time.
Here is a working example, first I add radios to my webform by the method you linked :
function addRadio()
{
try{
rdo = document.createElement('<input type="radio" name="fldID" />');
}catch(err){
rdo = document.createElement('input');
}
rdo.setAttribute('type','radio');
rdo.setAttribute('name','fldID');
document.getElementById('container').appendChild(rdo);
}
Then at code behind I used only the code below to get the radio's value :
string value = Request["fldID"];
So, be sure you're trying to get the name of the radio buttons at server side. You should use name attribute at server side, not id.

How do I programatically put telerik rad grid in "add new" mode on page load

Seems like this should be easy but I must just be missing something... I have a Telerik RadGrid on a page that allows inline editing. How do I programatically put the grid into edit mode to insert a new row into the grid. When the page loads I would like show the existing data and also display 1 empty row that a user can easily type into to add a new record to the table. (I don't want them to have to push the add new button)
Found the answer while back.... updating this in case others need it
RadGrid1.MasterTableView.IsItemInserted = true;
RadGrid1.Rebind();
Lifesaver!!
You can set
radGrid1.MasterTableView.IsItemInserted = false;
radGrid1.Rebind();
that will remove the inserted item (like pressing cancel).
If you need show inset form always you can use next:
protected void NeedDataSource(object sender, GridNeedDataSourceEventArgs e) {
parametersGrid.DataSource = data;
parametersGrid.MasterTableView.IsItemInserted = true;
}
You could try using jQuery to press your add button once the page is ready.
Something along the lines of -
$(document).ready(function() {
$("#addButton").click();
}
What I did when I wanted to do the same with the Telerik grid is to set the MasterTableView.IsItemInserted property of the control to true inside the OnNeedDataSource event handler. I suppose that it should work if you set the property inside the OnDataBound grid handler as well.
Dick
RefreshGrid(userName, "priority", true, false);
RadGrid radGrid = RadGrid1;
radGrid.MasterTableView.InsertItem();
radGrid.Rebind();

Set HTML input checkbox name in listview

I am trying to add a checkbox in a listview with value as ids of the records from the database so I can allow the user to check the ones they want to delete and when they click the delete button I can get value collection of checkbox with request.form.
My problem is, because checkbox in a listview ASP.NET renders the listview name into the name property of the checkbox, it prevents me to do request.form["checkboxname"].
I don't want to use Listviews delete commands but simply use request.form to get the collection of checked values.
How can I set name of the htmlinput checkbox so .NET doesn't change it in render time?
I have tried:
ListViewDataItem dataItem = (ListViewDataItem)e.Item;
HtmlInputCheckBox _CheckBoxDelete = (HtmlInputCheckBox)e.Item.FindControl("CheckBoxDelete");
_CheckBoxDelete.Visible = true;
_CheckBoxDelete.Value = DataBinder.Eval(dataItem.DataItem, "id").ToString();
_CheckBoxDelete.Name = "deletechecked";
But still it renders like:
<input name="PmList$ctrl0$CheckBoxDelete" type="checkbox" id="PmList_ctrl0_CheckBoxDelete" value="3" />
This is happening because ListView is a Naming Container. You can get around this in a couple of ways, but they all boil down to the choice of:
Rendering the HTML you want.
Pulling out the checked items in a different way.
The former is doable, but you'll likely loose a lot of ASP.NET's built in functionality. I'd advise against it unless you're deeply familiar with the control life cycle.
You've got everything you need for the pulling the values out in a way ASP is expecting:
HtmlInputCheckBox _CheckBoxDelete = (HtmlInputCheckBox)item.FindControl("CheckBoxDelete");
You just need to wait for the control hierarchy to be populated, and then loop over the ListView.Items looking for the checkboxes. Your "Delete" button's event handler is probably a good place to call this from.
Incidentally, why are you using a HtmlInputCheckbox, rather than a CheckBox?
I have sorted it out with:
string idCollectionTodelete = string.Empty;
foreach (string x in Request.Form)
{
if (x.IndexOf("CheckBoxDelete") > -1)
{
idCollectionTodelete += Request.Form[x] + ",";
}
}
new DB().DeleteUserPm(
ActiveUsername(), subdomain, idCollectionTodelete.TrimEnd(','));
It is not an ideal solution but it does work for me.
I do this
List<HtmlInputCheckBox> chkDeleteContacts = new List<HtmlInputCheckBox>();
foreach (RepeaterItem item in rptrFamilyContacts.Items)
{
chkDeleteContacts.Add((HtmlInputCheckBox)item.FindControl("chkDeleteContact"));
}
foreach(HtmlInputCheckBox chkDeleteContact in chkDeleteContacts)
{
//Delete Contact
if(chkDeleteContact.Checked)
blnStatus = BusinessUtility.DeleteConsumerContact(LoginConsumerID, chkDeleteContact.Value);
}
Slightly easier in my opinion

Resources