Handling multiple UserControls - c#

I have a webpage Containing UserControl repeated 2 times with same functionality. I want to disable the textbox in first UserControl but it is getting disabled in 2nd UserControl.
How to check this?
<script type="text/javascript">
function confirmCallBackFn(arg)
{
if (arg == true)
{
$find('<%= txtOne.ClientID %>').disable();
}
}

Method 1 - If the event is triggered by a control in the parent form
In the user control, you can define a property that returns the ID of the TextBox:
public string TextBoxID
{
get { return txtOne.ClientID; }
}
If your form contains two instances of the user control, ctrl1 and ctrl2, you can target a specific one like this:
document.getElementById('<%= ctrl1.TextBoxID %>').disabled = true;
Note: In the user control, make sure that you don't use ClientIDMode="Static" for the inner controls.
Method 2 - If the event is triggered by an inner control of the user control
If your user control contains the following markup:
<asp:CheckBox ID="chk1" runat="server" />
<asp:TextBox ID="txtOne" runat="server" />
you can add Javascript event handlers to the CheckBox in the Page_Load method of the user control:
protected void Page_Load(object sender, EventArgs e)
{
string js = string.Format("txtBoxID = '{0}';", txtOne.ClientID);
chk1.Attributes.Add("onmousedown", js);
chk1.Attributes.Add("onkeydown", js);
}
These event handlers set the value for a txtBoxID variable that you can define and use in your Javascript block:
<script type="text/javascript">
var txtBoxID;
function confirmCallBackFn(arg) {
if (arg == true) {
document.getElementById(txtBoxID).disabled = true;
}
}
</script>
This method assumes that there is no postback during the process. If a postback occurs, we may have to modify that method and register a script in the event handler in code-behind.

Related

System.Web.UI.WebControls.Button click event not firing

In my C# code I have function to dynamically create buttons
private Button createPageButton(string id, string text, int navTo = 0)
{
Button btn = new Button();
btn.ID = id;
btn.Text = text;
btn.Click += new EventHandler(btnNavigate_To_Page);
return btn;
}
Which gets setup like this:
C#:
public void someMethod()
{
Button btnPage_First = createPageButton("btnFirst_Page", "First", 1);
panelNavPageButtons.Controls.Add(btnPage_First);
}
aspx:
<asp:Panel ID="panelPageNavButtons" CssClass="pageNavBtns" runat="server"></asp:Panel>
Problem: The btnNavigate_To_Page event does not fire. The createPageButton method is not called within Page_Load but if I include an asp button in the panel (see below) then any additional button I add on the server side works properly
<asp:Panel ID="panelPageNavButtons" CssClass="pageNavBtns" runat="server">
<asp:Button ID="btnPage_Prev" runat="server" OnClick="btnNavigate_To_Page" />
</asp:Panel>
I would like to set up all the buttons dynamically without including any reference to btnNavigate_To_Page in the .aspx file
You have to call someMethod method inside either Init or Load event.
The reason is dynamically created controls are not in the control tree, so you have to reload them on every post back with same id.
protected void Page_Init(object sender, EventArgs e)
{
someMethod();
}

Cannot get new value of control in popup modal

Do web controls ever appear like you are changing their values but actually retain the previous value?
I created a pop-up modal for users to edit an item. When the user clicks edit on an item on the main page, the following sequence happens:
The item's ID is passed to the Page_Load event of the modal page, and is used to populate the page control's with the item's data.
The user changes a value in a control. Ex: Changes text in a TextBox contol.
The user clicks save, triggering the Click event which creates a DataTransferObject with the values in the textboxes, which will be stored.
However, on step 3, the control's new value (TextBox.Text) still holds the value that it orginially had, not the value the user put in.
Add.aspx:
<%# MasterType VirtualPath="../MasterPages/Popup.Master" %>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:TextBox ID="TextBoxDescription" runat="server"></asp:TextBox>
<telerik:RadButton ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click"/>
</asp:Content>
Add.aspx.cs
//Cannot access the new values here
protected void btnSave_Click(object sender, EventArgs e)
{
//This will print the new text on Create, but the old text on Edit
System.Diagnostics.Debug.WriteLine(TextBoxDescription.Text);
}
//works properly
protected void Page_Load(object sender, EventArgs e)
{
objIDParam = Convert.ToInt64(Request.QueryString["ObjectID"]);
editMode = (objIDParam != 0) ? true : false;
if(editMode)
PopulateFields(objID);
}
//works properly
private void PopulateFields(long objID)
{
MyObject obj = GetObjectByID(objID);
TextBoxDescription.Text = obj.Description;
}
It is worth noting that this popup page is used for both creating items AND editing items. Create works fine (i.e. The item isn't saved with all blanks, but rather the user input). Editing an item will properly pull all that data back in, and let the user edit the fields, however I can't access the changed values in my code.
You need to check for IsPostBack in the Page_Load method.
The Page_Load gets called before the btnSave_Click method, so the TextBoxDescription.Text is getting reset to obj.Description before the btn_Save method runs.
Try returning out of Page_Load if you're posting back:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
return;
objIDParam = Convert.ToInt64(Request.QueryString["ObjectID"]);
editMode = (objIDParam != 0) ? true : false;
if(editMode)
PopulateFields(objID);
}
Have a look at ASP.NET Page Life Cycle Overview for more info.

Having to click button twice to trigger postback in asp.net

I have some validation code in my searchbutton click event and have been having problems with it having to be clicked twice to work.
Asp Code:
<asp:Button ID="SearchButton" runat="server" Text="Search" Width="148px" OnClick="SearchButton_Click" style="height: 35px" />
Code Behind
protected void SearchButton_Click(object sender, EventArgs e)
{
string title = TitleSearch.Text;
Regex rgx = new Regex("^[0-9A-Za-z ]+$");
if (title != "" && !rgx.IsMatch(title))
{
ErrorLabel.Text = "Special characters are not allowed";
}
else
{
SearchButton.PostBackUrl = "results.aspx";
}
}
does the textbox have postback ? becaus if you change the text in the textbox it will do postback when you leave the textbox.so if you click the button the postback of the textbox fires.
I would check the textbox with java
Add in you page load event "Change EditGroup to the TextBoxName you want to check"
EditGroup.Attributes.Add("onchange", "return SomeTextChanged();");
This will add an onchange event to the textbox and it will call the java function in your aspx page when you click the button
Then in your aspx page you add "Again change EditGroup to the name of the TextBox you want to check"
<script type="text/javascript">
function SomeTextChanged() {
var Entered = document.getElementById('<%= EditGroup.ClientID %>');
if (Entered.value != "" && !Entered.value.match("^[0-9A-Za-z ]+$"))
{
alert("Special characters are not allowed");
document.getElementById('<%= EditGroup.ClientID %>').value = '';
}
else
{
}
}
</script>
So if you enter something that is not allowed you will get a message saying "Special characters are not allowed"
This will also stop you page from executing the rest of the code in the button click event.
And you also need to empty the textbox"i know this is maybe not the best way but if you don't empty the textbox and the user will click the button again it will not run the java code because the text didn't change"
So if if the text is good the java script will do nothing and the button click event will fire

How to make FileUpload control upload file right after clicking 'Browse'?

Untill now, I've been using 2 controls (FileUpload and additional button).
After file was chosen in a fileUpload control, user had to accept his choice by pressing save button.
Here's button's code:
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
FileUpload1.SaveAs(Server.MapPath("~/file.jpg"));
Label1.Text = Server.MapPath("~/file.jpg");
Image1.ImageUrl = "file.jpg";
}
}
I'm wondering whether there is a way to avoid using that button, so the FileUpload control's button would do the additional button's job.
The FileUpload control renders an <input type="file> in the browser. You can use the javascript change event to trigger the upload.
First make sure you have a load event handler registered in the body of your page:
<body onload="body_onload()">
And add this code inside your event handler:
<script type="text/javascript">
function body_onload()
{
...
$get('<%=FileUpload.ClientID%>').onchange = function() {
$get('<%=this.Page.Form.ClientID%>').submit();
};
}
</script>
Or to do this using pure jQuery, place this in the head of your page (if you don't already have jQuery included):
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
Then use this code to bind to the event (replace #fileUpload1 and #form1 with the id's of your FileUpload and Form elements, respectively):
<script type="text/javascript">
$(document).ready(function() {
$("#fileUpload1").change(function() {
$("#form1").submit();
});
});
</script>

List of Hyperlinks, buttons, whatever that open to new browser window

I have a need to create a small window inside of a ASP.NET Web Page(aspx) which displays a list of usernames, when you click the username, I need a new broswer window (not tab) to open up to a specific size. I can handle opening the new browser window assuming whatever control I use gets me into a code behind function where I can call....
string url = "http://www.dotnetcurry.com";
ScriptManager.RegisterStartupScript(this, this.GetType(), "OpenWin", "<script>openNewWin ('" + url + "')</script>", false);
Here's the markup that's in the page for the link.
<script language="javascript" type="text/javascript">
function openNewWin(url) {
var x = window.open(url, 'mynewwin', 'width=600,height=600,toolbar=1');
x.focus();
}
</script>
1.) What controls should I be using for this problem, what does the structure look like after I get the respective usernames back from the database?
Here's the closest I've come...This code uses an ASP.NET Bulleted List which I'm trying to bind to a list of HTML links which I would like to instead not POINT anywhere, but get me to the codebehind. Instead this Code actually renders on the page as the HTML (it isn't parsed into hyperlinks..)
protected void Page_Load(object sender, EventArgs e)
{
UsersBulletedList.DataSource = theContext.GetOnlineFavorites(4);
UsersBulletedList.DataBind();
}
public IQueryable<String> GetOnlineFavorites(int theUserID)
{
List<String> theUserList = new List<String>();
IQueryable<Favorite> theListOfFavorites= this.ObjectContext.Favorites.Where(f => f.SiteUserID == theUserID);
foreach (Favorite theFavorite in theListOfFavorites)
{
string theUserName = this.ObjectContext.SiteUsers.Where(su => su.SiteUserID == theFavorite.FriendID && su.LoggedIn == true).FirstOrDefault().UserName;
yourOnlineFavorites.Add("<a href='RealTimeConversation.aspx?UserName=" + theUserName + "'>" + theUserName + "</a>");
//this needs to help me get into a codebehind method instead of linking to another page.
}
return yourOnlineFavorites.AsQueryable();
}
I would create a Repeater on your page and bind your results from the GetOnlineFavorites method. Inside the Repeater, place a LinkButton with a ItemCommand event that adds your script to the page.
Markup:
<asp:Repeater ID="repeater" runat="server" OnItemCommand="repeater_ItemCommand">
<ItemTemplate>
<asp:LinkButton runat="server" ID="linkButton"
Text='<%# Eval("PropertyFromBindingCollection") %>'
CommandName="OpenWindow"
CommandArgument='<%# Eval("AnotherProperty") %>' />
</ItemTemplate>
</asp:Repeater>
In here, the Text property of the LinkButton and the CommandArgument of the Repeater would be set to some properties from your collection.
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
repeater.DataSource = theContext.GetOnlineFavorites(4);
repeater.DataBind();
}
}
protected void repeater_ItemCommand(object sender, RepeaterCommandEventArgs e)
{
if(e.CommandName == "OpenWindow")
{
string arg = e.CommandArgument; // this could be the url, or a userID to get favorites, or...?
//Your open window script
}
}
Now, when the user clicks one of the LinkButtons, it will fire the ItemCommand event for the Repeater, check the CommandName (set on the LinkButton), and then get the CommandArgument set on the LinkButton. If you set the CommandArgument as a URL, you can use that in your OpenWin script, otherwise use whatever data you set as the argument to get the URL you want to open.

Categories