Get clientID for multi userControl with same Server ID - c#

I have ASP.Net application that have multiple User Controls in the same page every one have its hidden field that holds a value, and every one have button that calls pop-up and through this value from hidden field to it.
The problem that when i try to access the hidden field and get the value inside , the program always get the last one (which created last).
How can i get the value of the inner hidden field in the current UserControl (Which i'm clicking the button from)?
Attempts:
var hdnRegion = "<%=hdnRegionId.ClientID%>";
var regionIdVal = $("#" + hdnRegion).val();
methodName(regionIdVal);
another one:
var currentControl = "<%=this.ClientID%>";
var hdnRegion = currentControl + "_" + "hdnRegionId";
var regionIdVal = $("#" + hdnRegion).val();
methodName(regionIdVal);
I also tried to call a property from code behind that returns the value and one that returns the whole control with no correct result.
Any suggestions would be appreciated...

Accourding to your comment under the question, your btnUpdate and hdnRegionId controls are in the same container (for instance in the same div) so try this:
$('input[id*="btnUpdate"]').click(function(){
var regionIdVal = $(this).parent().children('input[id*="hdnRegionId"]').val();
methodName(regionIdVal);
});
This is a JSFiddle Demo that simulate your HTML code that is rendered by ASP.NET.

Related

How can I count up the name of a Button with a Variable

I'm trying to make a battleship game in which the game field buttons all start with the letter A and then a number. Now I want to count up the numbers but still be able to do basic button functions like BackgroundImage.
What I'm doing now is just create a sting which adds the A with the number I receive from the function.
string btnr = "A";
btnr = btnr + Convert.ToString(nr);
string btnr = "A";
btnr = btnr + Convert.ToString(nr);
btnr.BackgroundImage = Image.FromFile(#"T:\E\_AUSTAUSCH\Com.Menu_OpenSurce\Battleship\Bilder\ACC_5_W.png");
This should change the Background image of the Button with the "nr" xx but I already get an error message saying:
Error 3 "string" contains no definition for "BackgroundImage", and no
extension method "BackgroundImage" could be found that accepts a first
argument of type "string". (Is there no Using directive or assembly
reference?)
Assuming WinForms, you can use Controls.Find to get a reference to the Button, no matter how deeply nested it is:
string btnName = "A" + nr.ToString();
Control ctl = this.Controls.Find(btnName, true).FirstOrDefault();
if (ctl != null && ctl is Button)
{
Button btn = (Button)ctl;
btn.BackgroundImage = Image.FromFile(#"T:\E\_AUSTAUSCH\Com.Menu_OpenSurce\Battleship\Bilder\ACC_5_W.png");
}
You are getting the button name. But you need to reference to the button object. To do this, you can use the controls property to select the button by name:
Please note that this example assumes that the button exists and the control is of type Button. Update: also assumes that the buttons are inmediate childs of the form
var button = (Button)Controls[btnr];
button.BackgroundImage =
Image.FromFile(#"T:\E\_AUSTAUSCH\Com.Menu_OpenSurce\Battleship\Bilder\ACC_5_W.png");

Asp.net Custom Table Cell ClientID not set

I have a class derived from WebControls.TableCell.
When the Text property is set, I call a method that dynamically adds asp:Panels and asp:LiteralControls to the Cell. I want to reference these controls in Javascript, so naturally I tried using the ClientId of the panels in my JS functions. However, these controls have no ClientId set (the string is empty). Why is this? How do I force the ClientIds to be set?
As a temporary solution, I set the ClientIDMode to "static" and created the IDs on my own, but this is not satisfactory because it's hard to reference those IDs in JS. Why? If you assign, for example, "12345" to one control, it gets changed on client side to something like "MainContent_123456". This is bad because the "MainContent" part is not fixed; thus I never know for sure what the real Id on the client side will be. Currently, I can get the control with jQuery using $ctrl = $('[id$='12345']');, but this is dirty because it would get any control that has '123456' in its id.
So, back to the original question: how do I get my ClientIds set automatically for my panels in my custom TableCells?
Edit: Code added
protected void Page_Load(object sender, EventArgs e)
{
this.ClientIDMode = System.Web.UI.ClientIDMode.Static;
}
Code in the method that adds the controls to the custom TableCell:
Panel remainingTextPanel = new Panel();
remainingTextPanel.ID = Guid.NewGuid().ToString();
remainingTextPanel.Style["display"] = "none";
LiteralControl remainingText = new LiteralControl(myText.Substring(initialStringLength, myText.Length - initialStringLength));
remainingTextPanel.Controls.Add(remainingText);
this.Controls.Add(remainingTextPanel);
Panel linkBtnPanel = new Panel();
LinkButton lnkBtn = new LinkButton() {Text = "...", OnClientClick = "toggleDynamicText('" + remainingTextPanel.ID + "'); return false;" };
lnkBtn.Font.Bold = true;
linkBtnPanel.Controls.Add(lnkBtn);
this.Controls.Add(linkBtnPanel);
And the JS Code:
function toggleDynamicText(id) {
$ctrl = $('[id$=' + id + ']');
$(document).ready(function () {
$ctrl.toggle(1000);
});
}
Without seeing any code it's difficult to say what's going on but to access your controls using jQuery you can do the following:
$("#<%=myElement.ClientID%>")
This way it doesn't matter what .NET assigns as the ID.

How to return value back to parent page from window.ShowModelDialog?

I'm facing some issue with returning value back to the parent page.
Please kindly help.
I have a gridview that allow users to add new record at the row, but users also can click on the Search button on the row, and I will show a pop up with the below code.
TextBox txtCarNo = gvLookup.FooterRow.FindControl("txtNo") as TextBox;
System.Text.StringBuilder s = new System.Text.StringBuilder();
s.Append("<script language='javascript' id='SearchResult'> " );
s.Append("var WinSettings = 'dialogHeight:400px ; dialogWidth: 550px ;center: Yes ;resizable: No;status: no'; ");
s.Append("javascript: window.showModalDialog('Search.aspx?no=" + txtNo.Text.Trim().ToUpper() + "','',WinSettings); ");
s.Append("</script > ");
if ((!ClientScript.IsStartupScriptRegistered("SearchResult")))
{
ClientScript.RegisterStartupScript(this.GetType(), "SearchResult", s.ToString());
}
At the child page, there will be another gridview that shows the search result, and users can click on one of the row to return the number back to the parent page.
I thought of using Session to pass the value back, but when showing the ShowModalDialog, the code at the parent page already went through, meaning Session won't work on this scenario.
Please advise how do I return a value to the parent page.
Appreciate very much.
Example from Wrox
When you call showModalDialog you do this:
var oReturnValue = showModalDialog(....);
Within showModalDialog, assuming your textboxes have IDs of "txtForename" and "txtSurname":
<body onbeforeunload="terminate();">
function terminate()
{
var o = new Object();
o.forename = document.getElementById("txtForename").value;
o.surname = document.getElementById("txtSurname").value;
window.returnValue = o;
}
Then continuing in your main window:
alert(oReturnValue.forename + "\n" + oReturnValue.surname);

Is it possible to create a dropdown list (not menu) of hyperlinks

nyone know if its possible to create a dropdown list of hyperlinks. So besides the hyperlink replacing the text field, there's also a value for each item in the list. Wondering if there's any jquery or other client side script that will let me turn my list item names into links. Using MVC2 as serverside.
Ultimately clicking on any link in the dropdown list will open a new window, this is so people can not only select a product variant but also view the details of the selected product variant in a pop-up window before submitting the form.
The hyperlink would be constructed from the items value, which is the productID and the URL that will open in a new window will just pass that as a perimeter to an action method.
Currently using this script to do the job, but I have to employ a button next to
the drop down list and its kinda ugly and confusing as you won't write too much on
a button.
function JumpToIt1(frm) {
var newPage = frm.droppa.options[frm.droppa.selectedIndex].value
if (newPage != "None") {
window.open("http://mydomain.com/category/" + newPage, "mywindow", "menubar=1,resizable=1,width=550,height=250");
}
}
$(function() {
$('#dropdownId').change(function() {
var page = $(this).val();
if (page != "None") {
window.open("http://mydomain.com/category/" + page, "mywindow", "menubar=1,resizable=1,width=550,height=250");
}
});
});
Be aware though that the new window will only open when the user selects a different value from the currently selected one. So if you remove your button the user will have no way of opening the window twice in a row without first selecting a different value.
You can have a dropdown with an onChange handler that causes it to run JavaScript whenever the dropdown changes (ie someone selects something out of the list). I think that will do what you want.
try this:
function openPopup(newPage){
if (newPage != "None") {
window.open("http://mydomain.com/category/" + newPage, "mywindow", "menubar=1,resizable=1,width=550,height=250");
}
}
$(#dropdownId").find("option").each(function(){
var $Obj= $(this);
$(this).text("<a href='javascript:void(0);' onclick='openPopup("+$Obj.val()+")'>" + $Obj.text() +"</a>");
});

C# dynamically created control issue

i'm having issues retreiving the values out of a dynamically created dropdownlist. all controls are created in the Page_Init section. the listitems are added at that time as well from an array of listitems. (the controls are named the same so should be accessable to the viewstate for appropriate setting.)
here is the function that attempts to retrieve the values:
protected void Eng98AssignmentComplete_Click(object sender, EventArgs e)
{
String myID = "0";
Page page = Page;
Control postbackControlInstance = null;
// handle the Button control postbacks
for (int i = 0; i < page.Request.Form.Keys.Count; i++)
{
postbackControlInstance = page.FindControl(page.Request.Form.Keys[i]);
//Response.Write(page.Request.Form.Keys[i].ToString());
if (postbackControlInstance is System.Web.UI.WebControls.Button)
{
myID = Convert.ToString(
postbackControlInstance.ID.Replace("button_", ""));
}
}
String txtholder = "ctl00$ContentPlaceHolder$Eng098Instructors_" + myID;
Response.Write("MYID: " + myID + "<br/>");
DropDownList ddInstructorCheck = (DropDownList)Page.FindControl(txtholder);
Response.Write("Instructor Selected: "
+ ddInstructorCheck.SelectedValue + "<br/>");
}
here is the output I get, no matter which instructor was selected.....
MYID: 1_1
Instructor Selected: 0
ctl00$ContentPlaceHolder$Eng098Instructors_1_1
the name of the control is correct (verified via view source)....
ideas?
You're going to a lot of work to build this fancy string:
ctl00$ContentPlaceHolder$Eng098Instructors_1_1
That is the client ID of your control, not the server id. This code is running on the server side, and so you need the server id. To get that control using the server id, you need to do this:
ContentPlaceHolder.FindControl("Eng08Instructors_1_1");
Notice I didn't look in the page, because your content place holder created a new naming container.
Also, the way your loop is set up the myID variable will always end up holding the last button in the Keys collection. Why even bother with the loop?
Based on your comments, a better way to find the id of the dropdownlist is like this:
string id = ((Control)sender).ID.Replace("button_", "Eng098Instructors_");
why not just save the control in an instance in your class so that you don't have to use FindControl?
Do you also re-create the controls during the postback? Dynamically generated/added controls must be re-created with every request, they are not automatically re-created.
Why don't you cast the sender? This should be the button that caused the postback:
string myId = "0";
Button btn = sender as Button;
if (btn != null)
myId = btn.ID
...
You need to perform something like this because the UniqueID property is the key in Request.Form.
List<Button> buttons = new List<Button>();
List<DropDownList> dropdowns = new List<DropDownList>();
foreach (Control c in Controls)
{
Button b = (c as Button);
if (b != null)
{
buttons.Add(b);
}
DropDownList d = (c as DropDownList);
if (d != null)
{
dropdowns.Add(d);
}
}
foreach (String key in Request.Form.Keys)
{
foreach (Button b in buttons)
{
if (b.UniqueID == key)
{
String id = b.ID.Replace("button_", "");
String unique_id = "ctl00$ContentPlaceHolder$Eng098Instructors_" + id;
Response.Write("MYID: " + id + "<br/>");
foreach (DropDownList d in dropdowns)
{
if (d.UniqueID == unique_id)
{
Response.Write("Instructor Selected: " + d.SelectedValue + "<br/>");
break;
}
}
}
}
}
I'm not sure why you are generating the control in code (you can still add items dynamically if you do), but the code that generates the controls would probably be a huge help here. I'm guessing you are not setting the list item value, and instead just setting the list item text. Try seeing what you get from the SelectedText field and post your control creation function.
EDIT:
In response to your comment on #Martin's post, you said "yes I recreate the controls in the Page_Init function each time the page is created (initial or postback)". Are you also setting the selected value when you create them?
You can also use controls on the page even if your data comes from a database, the controls themselves don't have to be dynamically generated.
How about this?
((Button)sender).Parent.FindControl(myid)
Edit:I misunderstood your question. But i think you should follow page lifecycle. it is common issue for dynamically created controls.
I did some research and here is some info about Dynamically Created Controls may help you...
I had 2 catches.... here's what they were.
1. I didn't clear the table I was adding to before re-creating the controls.
apparently my attention to detail was off yesterday, i'm pretty sure the ctlXX frontrunner of the control was some different number upon postback due to how I was recreating the controls.
2. I was assigning the same list to all the dropdownlist controls.
once I called the lookup upon each creation a dropdownlist control, all works well.
anyway for what it's worth....

Categories

Resources