So I'm creating a dummy webpage for basics right now. The Goal:
On a button click, I want to update information shown in the textbox.
The method myButton_Click takes in the parameters of the button. How can I access an object like textbox (or any object for that matter) since it is not being accessed from a buttonclick event? I set up a public variable, myTextBox_, which I think I could then edit freely. But I'm still not sure how to set myTextBox_ to understand that it is connected to the webpage.
Html:
<form id="form1" runat="server">
<p style="height: 324px">
<asp:Button ID="myButton" runat="server" EnableTheming="True" Text="Button" onclick="myButton_Click"/>
<asp:TextBox ID="myTextBox" runat="server">Hello</asp:TextBox>
</p>
</form>
Then the C# Code:
Textbox myTextBox_;
protected void Page_Load(object sender, EventArgs e)
{
//possibly initialization code set myTextBox_ to the id myTextbox, but how?
}
protected void myButton_Click(object sender, EventArgs e)
{
myTextbox_.text = "goodbye";
}
You're very close. All you need to do is:
protected void myButton_Click(object sender, EventArgs e)
{
myTextBox.Text = "goodbye";
}
You don't need to set up anything in the Page_Load method, as you have them set up as runatserver, so they are accessible from the code behind.
As already stated, this will require a postback to work, to avoid this use AJAX or do it in pure JavaScript.
If you want to learn web on .NET, you should start learning ASP.NET MVC, not web pages.
Anyhow, I believe you don't get the same behaviour as in a desktop app, because when you click the button, you get a page postback (whole page is refreshed). You should use the page's postback event to change the text, not the button.
Or you should use the old "UpdatePanel" from ASP.NET Ajax 1.0, to put the button and the textbox in the same UpdatePanel (but you must first install that ASP.NET Ajax 1.0)
But pls, start using MVC :)
http://www.asp.net/mvc
Related
I have a Update Panel inside a User Control i use on 2 pages in my website
Both pages use the same MasterPage, ScriptManger is declared in the MasterPage.
Both pages call the UC the same way:
<uc:SearchCube runat="server" ID="searchCube" />
in the Update panel i have many RadioButtons that on change generate a server side event that fill dropdown in the update panel and update the panel
protected void SearchCategoryChanged(object sender, EventArgs e)
{
FillDropdowns();
SearchOptions.Update();
}
Update Panel is set like this:
<asp:UpdatePanel ID="SearchOptions" runat="server" UpdateMode="Conditional"
hildrenAsTriggers="true"/>
Each RadioButton is set like this:
<asp:RadioButton ID="RadioButton1" GroupName="SearchCategory" runat="server"
AutoPostBack="true" OnCheckedChanged="SearchCategoryChanged" Text="Text"/>
I also have an AsyncPostBackTrigger on each Radio Button Controller
The problem i have is that on one page when i call the Update() function the panel is updated and Page_Load is triggered which causes the UC to refresh and reload the default settings of the UC
I can see in DEBUG mode that on the working page Update() does not generate Page_Load.
Can anyone explain to me why this is happening?
Everytime a request goes to the server, it executes the Page_Load event.
What you need to do is make sure you have a PostBack validation on all your pages:
protectec void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
//Not a postBack: Normal page load
//Init your page here
}
else
{
//It's a PostBack (from a command).
//Do nothing or init stuff your all your commands.
}
}
If you put some breakpoints in your Page Load and your SearchCategoryChanged method, you'll be able to see what the pipeline looks like.
Fixed my problem.
the problematic page is an index page that takes a few parameters in.
I have a Response.Redirect() on the page to avoid duplication of pages.
Apparently when the PostBack() is made it calls the page without any parameters and i was forcing it to be redirected into a default view since no parameters were sent to the page.
i found a lead to my problem in a Microsoft help forum that stated:
By calling Response.Write() directly you are bypassing the normal
rendering mechanism of ASP.NET controls. The bits you write are going
straight out to the client without further processing (well,
mostly...). This means that UpdatePanel can't encode the data in its
special format.
Anyway the page was reloading every time which caused it to reload the User Control with it's default values.
I have a web form that allows the user to modify data in certain fields (mostly TextBox controls, with a couple of CheckBox, DropDownList, and one RadioButtonList control) with a submit button to save the changes. Pretty standard stuff. The catch is, I need to keep track of which fields they modified. So I'm using ASP.NET HiddenField controls to store the original value and then on submit comparing that to the value of the corresponding TextBox (for example) control to determine which fields have been modified.
However, when I submit the form and do the comparison, the value of the TextBox control in the code behind still reflects the original value, even though I have changed the contents of the TextBox, so it isn't registering the change. Here is an example of a set of TextBox/HiddenField pairings (in this case last, first, middle names) in my ASP.NET form:
<div id="editName" class="editField" style="display: none">
<asp:TextBox ID="tbxLName" runat="server" class="editable"></asp:TextBox>,
<asp:TextBox ID="tbxFName" runat="server" class="editable"></asp:TextBox>
<asp:TextBox ID="tbxMName" runat="server" class="editable"></asp:TextBox>
<asp:HiddenField ID="hdnLName" runat="server" />
<asp:HiddenField ID="hdnFName" runat="server" />
<asp:HiddenField ID="hdnMName" runat="server" />
</div>
I'm setting the original values of all these controls (".Text" for the TextBox controls, ".Value" for the HiddenField controls) on PageLoad in the code behind.
Here's an example of where I'm doing the comparison when I submit the form (I'm adding the field name, old value, and new value to List<string> objects if the values differ):
if (tbxLName.Text != hdnLName.Value)
{
changes.Add("ConsumerLastName");
oldVal.Add(hdnLName.Value);
newVal.Add(tbxLName.Text);
}
But when I enter a new value into the TextBox control and click Submit:
then step through the code in the debugger, it shows me that the value of the control is still the old value:
Why is the comparison happening against the original value of the TextBox even though the new value is there when I click the submit button?
Update: #David gets the credit for this, even though he didn't post it as an answer -- I was forgetting to enclose the method for pre-filling the original values of the controls in a check for IsPostBack; I really should have known better, I've been doing this for quite a while!
Are you checking for IsPostback in Page_Load so you don't overwrite the values sent in the Postback?
Make sure that you are not overwriting your values in the Page_Load method:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
someTextField = "Some Value";
}
}
It took a while for me to get that the Page_Load method works as an "before anything goes" method and not only a method that is being ran when you visit the page with GET.
Make sure you're not overwriting the value for the textbox somewhere in page init or load without checking for the IsPostback flag.
It may happen due to postback. If you code for set textbox not in !isPostBack then put it.
i.e.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
tbxLName.Text="anything";
}
}
I have an internal web service (ASP.NET) written on C# in a company I work for. There are only 2 pages in it, one of this pages contains DropDownList.
Every time when user selecting an item from that DropDownList I need to somehow pass selected item value to a static method and show result string of that method anywhere on page.
I've never worked with ASP.NET or any web programming before and a bit confused about how to do it, not sure where to start looking even.
In your aspx file you should have this:
<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True"
onselectedindexchanged="ListBox1_SelectedIndexChanged"></asp:ListBox>
Notice the AutoPostBack="True" which goes back to the server and fires the selectedindexchanged event immediately after the user changes the selection in the listbox
In your code-behind (.cs file)
You should have this:
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// Call static method and pass the ListBox1.SelectedIndex
// MyStaticMethod(ListBox1.SelectedIndex);
}
you can either se5t the autoPostBack="true" and handle the change event on the server side or using jQuery subscribe for the change event and get the value on the client side
You should probably check out some of the great resources that microsoft provides for new .NET developers. They will be really helpful in getting you started. Her is a link of some really good videos to help you out: http://www.asp.net/web-forms/videos
Not sure what language you are coming from, if any... But for the most part webforms is going to work a lot like other web based methodologies.
Your ASP.NET Controls (in your case the DropDownList) have both client and server side events.
You will probably want to map the server-side OnSelectedIndexChanged event on your DropDownList.
In order to cause a postback on that control you will want to set the AutoPostBack property to true on your DropDownList.
try this one
In html ,
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
In aspx.cs page,,
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string selctedValue = DropDownList1.SelectedValue;
/// Call yours static methid here
YourMethod(selctedValue);
}
For my internal webpage at work, I display a DataGrid based on entries in a SQL table (not directly, but with some processing on entries).
Each row in the DataGrid has a button that the user clicks. I need this button to open a new window or tab (I believe I can't decide as this is based on browser config) and also change a value in the SQL table to say the button was clicked.
If I use an asp:Hyperlink then the page opens nicely, but I don't know how to update SQL. Vice-versa if I use an asp:LinkButton I can get the SQL updated but can't get a new page to open.
Is what I am trying to do impossible?
Thanks
EDIT:
I've tried both these in my .cs file, but neither worked:
ClientScript.RegisterStartupScript(GetType(), "openwindow", "window.open('" + url + "','_preview'");
Response.Write("<script type='text/javascript'>detailedresults=window.open('" + url + "');</script>");
<asp:TemplateField HeaderText="Action"> <ItemTemplate>
<asp:LinkButton ID="lbtnConfigureSurvey" runat="server" CausesValidation="False"
CommandName="ConfigureSurvey" CommandArgument='<%# Eval("intSurveyID") %>'
OnClientClick="aspnetForm.target ='_blank';">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
protected void gvSurveyList_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "ConfigureSurvey")
{
Response.Redirect('Your page url');
}
}
You can use LinkButton and use OnClientClick property to set the java-script that would open the page in new browser window. This script must return true so that post-back can happen and you can handle click event on server side to update your database.
IMO, better way would be to use hyper-link and open the page in new browser window. However, you must pass a query-string parameter while opening the page (say Page2) that would tell the new page that it should update the database. So url for opening the page will be something like "page2.aspx?recordId=xyz". And within page2.aspx.cs, you will have code such as
protected void page_load(object sender, EventArgs e)
{
if (!IsPostback)
{
var recordId = Response.QueryString["recordId"];
if (!string.IsNullOrEmpty(recordId))
{
// update database
...
}
}
...
}
From security perspective, you may want to include time-out within parameter value and encrypt the entire thing.
You could use your LinkButton and call RegisterStartupScript on postback to execute something like this on page load
.aspx:
<asp:LinkButton OnClick="OnButtonClick" Text="Update" runat="server" />
.aspx.cs:
protected void OnButtonClick(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(GetType(), "openwindow", "<script type=text/javascript> window.open('About.aspx'); </script>");
}
You need to supply the whole script element to RegisterStartupScript.
try this
Response.Write("<script type='text/javascript'>detailedresults=window.open('PAGE NAME.aspx');</script>")
EDIT:
you can set command name for link button and execute code in rowcocommand event
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("commandname for linkbutton"))
{
//update code
Response.Write("<SCRIPT language=\"javascript\">open('Yourpage.aspx','_blank','top=0,left=0,status=yes,resizable=yes,scrollbars=yes');</script>");
}
}
Hyperlink will not call server side event on click, so you won't get post back to perform the SQL task, and by using the LinkButton you can open the page in the new window or tab. To do so you need to add a little code below in the Grid_RowBoundEvent.
Ex: LinkButton.OnClientClick="window.open('http://www.google.com');";
The url you can change as per your requirement.
Again, in the Code behind you will get a server side event. There you can do your sql task.
Hope it will be helpful to you.
I'm building an asp.net cutom control inside which I have two dropdownlists: companyIdSelection and productFamilySelection.I populate the companyIdSelection at Page_Load and in order to populate the productFamilySelection depending on the selected item in companyIdSelection.I'm using UpdatePanels to achieve this, but for some reason every time I update companyIdSelection Page_Load is being called ( which as far as I know should happen only when the entire page is reloaded ), the list is being reloaded again and the item the user selected is lost( the selected item is always the top one ).Here's the code
<asp:UpdatePanel ID="updateFamilies"
runat="server"
UpdateMode="Always">
<ContentTemplate>
Company ID:<br>
<br></br>
<asp:DropDownList ID="companyIdSelection"
runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="companyIdSelection_SelectedIndexChanged">
</asp:DropDownList>
<br></br>
Product Family:
<br></br>
<asp:DropDownList ID="productFamilySelection" runat="server"
AutoPostBack="True"
onselectedindexchanged="productFamilySelection_SelectedIndexChanged">
</asp:DropDownList>
<br>
</ContentTemplate>
</asp:UpdatePanel>
protected void Page_Load(object sender, EventArgs e)
{
this.companyIdSelection.DataSource = companyIds(); //companyIds returns the object containing the initial data items
this.companyIdSelection.DataBind();
}
protected void companyIdSelection_SelectedIndexChanged(object sender, EventArgs e)
{
// Page_Load is called again for some reason before this method is called, so it
// resets the companyIdSelection
EngDbService s = new EngDbService();
productFamilySelection.DataSource = s.getProductFamilies(companyIdSelection.Text);
productFamilySelection.DataBind();
}
Also, I tried setting the UpdateMode of the UpdatePanel to "Conditional" and adding an asyncpostback trigger
but the result was the same.
What am I doing wrong?
PS:
I fixed the updating problem, by using Page.IsPostBack in the Page_Load method, but I would still want to avoid a full postback if possible
I think you misunderstand how UpdatePanels work. They DO actually do a full page postback, it's just that during the rendering stage they capture only a portion of the output and send it back in the AJAX response so the page can be updated. More info here.
So you will still need to check whether it is a postback in your page_load event and only perform your data load if it isn't one.
The update panel call back will go through the page load on every call back. In face, the pull page lifecycle (minus render and prerender) will occur. Update panels give the appearance of ajax, but your client side code still posts back to the same page - which is the problem you are describing. If you can avoid using Update Panels, I suggest you do so. Use something like jQuery instead. If not, then use this in your Page_Load
if (Page.IsCallback) { } //Do callback specific code here
else { } //Do Postback specific code here
Hope this helps. Good Luck.