I create textbox by this code:
<div style="clear:left;">
<asp:TextBox TextMode="MultiLine" runat="server" ID="selectText" ReadOnly="true" Width="560px" Height="50px"></asp:TextBox>
</div>
I fill it by this code:
elSelText.value = elSelText.value.substr(0, position) + chosenoption2.value + " ";
And then i try to send value in textbox to server, but it's empty!
protected void btnUseSelectClick(object sender, EventArgs e)
{
sourceDetails.SelectCommand += " and " + selectText.Text;
Session["FilterSelectCommand"] = sourceDetails.SelectCommand;
tableResults.DataBind();
}
On the advice I added AutoPostBack="true":
<div style="clear:left;">
<asp:TextBox TextMode="MultiLine" runat="server" AutoPostBack="true" ID="selectText" ReadOnly="true" Width="560px" Height="50px"></asp:TextBox>
</div>
but it didn't help
Although it's news to me, it seems that the ReadOnly property doesn't keep track of changes from the client. If you want the "readonly" functionality but still get the value on the server, put the following in your Page_Load method:
selectText.Attributes.Add("readonly", "readonly");
And remove the ReadOnly (and AutoPostBack) property in the <asp:TextBox> tag.
( From: http://aspadvice.com/blogs/joteke/archive/2006/04/12/16409.aspx and http://forums.asp.net/t/1467081.aspx - it was a fairly quick find with Google)
Maybe a problems of ViewState. Try add the check of Page.IsPostBack in the page load event like this:
If(!Page.IsPostBack)
{
// Data binding for the first call
}
I believe this is due to ReadOnly: ASP.Net registers which controls are readonly when sending you the page.
The value of these controls is discarded when posting back, and it is regotten (from ViewState I believe).
A workaround for this would be not setting readonly="true" on the aspx page, but setting it with $(document).ready(your_function_here();) (if you're using jQuery) or with the body onLoad event.
Related
I have a method being used on a button to redirect to a different page. There are several variables that are inserted into the URL to help navigate to what the user wants to see. It works well, except for the fact that the variables do not show up in the address bar.
Upon button click and redirect to the next page the url looks like: /Beta.aspx/?year=&track=&event=&car=27&session
How can I get my variables to show up in the address bar? Below is the code being used for the button click.
protected void btnConfirm_Click(object sender, EventArgs e)
{
string url = string.Format("Beta.aspx/?year={0}&track={1}&event={2}&car=27&session{3}",hidYear.Value, hidTrack.Value, hidEvent.Value, hidSession.Value);
Response.Redirect(url);
}
Button Setup
<telerik:RadImageButton ID="RadImageButton2" runat="server" Skin="Material" Text="27" OnClick="btnConfirm_Click">
</telerik:RadImageButton>
Form Tag
<form id="form1" runat="server" class="SmallFont">
Hidden Fields
<asp:HiddenField runat="server" ID="hidYear" />
<asp:HiddenField runat="server" ID="hidTrack" />
<asp:HiddenField runat="server" ID="hidEvent" />
<asp:HiddenField runat="server" ID="hidSession" />
When RadImageButton2 is clicked, the page is posted back to the server for processing. This process is called ASP.NET postback mechanism and IsPostback is normally used on page_load event to detect if the page is getting generated due to postback requested by a control on the page, or if the page is getting loaded for the first time. This is important for the case when values of the controls are set programmatically and should not be overwritten when page was posted back.
See this snippet:
protected void Page_Load(object sender, EventArgs e)
{
hidYear.Value = "";
hidTrack.Value = "";
hidEvent.Value = "";
hidSession.Value = "";
}
protected void Init_Click(object sender, EventArgs e)
{
hidYear.Value = "2020";
hidTrack.Value = "1";
hidEvent.Value = "2";
hidSession.Value = "0123456789";
}
protected void btnConfirm_Click(object sender, EventArgs e)
{
string url = string.Format("Beta.aspx/?year={0}&track={1}&event={2}&car=27&session{3}",
hidYear.Value, hidTrack.Value, hidEvent.Value, hidSession.Value);
Response.Redirect(url);
}
It all will run well, but values on the redirect will be always "" because Page_Load() is called with every postback. However, with the following little change the values on redirect will be not changed and populated to the state before form submit:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
hidYear.Value = "";
hidTrack.Value = "";
hidEvent.Value = "";
hidSession.Value = "";
}
}
Note, actual values of controls can be found by looking at the source of the page
Bottom line here: hidden fields should have values when looking at the source before clicking on RadImageButton2 and Page_Load() should not call any code that changes those values, or should check for if (!IsPostBack).
P.S.
Simple redirect does not required server code and can be done with client script, example:
<script type="text/javascript">
function PageRedirect() {
window.location.href = "Beta.aspx/?year="
+ document.getElementById('<%=hidYear.ClientID%>').value
+ "&track=" + document.getElementById('<%=hidTrack.ClientID%>').value
+ "&event=" + document.getElementById('<%=hidEvent.ClientID%>').value
+ "&car=27&session" + document.getElementById('<%=hidSession.ClientID%>').value;
}
</script>
<asp:Button ID="Button1" runat="server" Text="Client Redirect"
OnClientClick="PageRedirect();return false;" />
You're saying that it does work. That means that the variables are being passed.
There is a chance that the solution is really, really simple.
Variables don't show up in the address bar until you click on it. Try clicking on the URL in your address bar, it will select the URL and the variables will show. If not, only then it has to do something with the code.
Ahh, there's the mistake Bro. there isn't any value for these hidden controls
<asp:HiddenField runat="server" ID="hidYear" />
<asp:HiddenField runat="server" ID="hidTrack" />
<asp:HiddenField runat="server" ID="hidEvent" />
<asp:HiddenField runat="server" ID="hidSession" />
either you can add value in the ASPX page as
<asp:HiddenField runat="server" ID="hidYear" Value="1234"/>
<asp:HiddenField runat="server" ID="hidTrack" Value="4321" />
<asp:HiddenField runat="server" ID="hidEvent" Value="1234" />
<asp:HiddenField runat="server" ID="hidSession" Value="2405"/>
or as mentioned by user https://stackoverflow.com/users/2316116/user2316116 you can use
hidYear.Value = "2020";
hidTrack.Value = "1";
hidEvent.Value = "2";
hidSession.Value = "0123456789";
the reason the value is not being displayed in the URL is simply that there isn't a value that can be displayed.
make sure to check for empty values if you're taking inputs from the user in future applications. 😀
You should not have '/' between 'beta.aspx' and '?'. Try removing that extra slash and see if that resolves your issue.
I have a simple page with Jquery datepicker, UpdateProgress, and GridView inside of UpdatePanel.
Here is a fragment from the page:
...
Select From Date: <input type="text" id="datepickerfrom" name="datepickerfrom"/>
Select To Date: <input type="text" id="datepickerto" name="datepickerto"/>
<asp:Button ID="btnGetData" runat="server" OnClick="BtnGetData_Click" Text="Get Error List" />
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
<ProgressTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl="~/Images/ajax-loader.gif" />
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
...MyGrid...
</ContentTemplate>
</asp:UpdatePanel>
...
This is the code behind method invoked when clicking on the button:
protected void BtnGetData_Click(object sender, EventArgs e)
{
string dateFrom = HttpUtility.HtmlEncode(Request.Form["datepickerfrom"]);
string dateTo = HttpUtility.HtmlEncode(Request.Form["datepickerto"]);
InputData data = new InputData(dateFrom, dateTo);
Session["inputData"] = data;
gvErrorLog.PageIndex = 0;
LoadLogErrorData(data);
}
When I first load the page and click on one of the Date's text boxes, jQuery datepicker is poped up. When I refresh the page, it pops up as well.
However, after clicking on the button and populating the GridView with the data, it is not displayed anymore.
What can be the reason?
Your tag is
<input type="text" id="datepickerfrom" name="datepickerfrom"/>
This is really the regular html tag. Microsoft ASP.NET does NOT keep the state (ie in ViewState) of regular html tag. After postback, the page life cycle effectively creates a new instance of Page (System.Web.UI.Page) object before sending response back to browser as html.
On the other hand, once you change to
<asp:TextBox ID="datepickerfrom" runat="server" />
You will see it in postback. Also the way you capture those 2 dates in code behind is obsolete (only seen in ASP 1.1).
The namespace for your text tag is
System.Web.UI.HtmlControls.HtmlInputText and the namespace for the server tag is System.Web.UI.WebControls.TextBox. They belong to different namespaces. Any controls in the HtmlControls are for legacy purpose.
You may change to asp:TextBox and access them from code behind as follows:
protected void BtnGetData_Click(object sender, EventArgs e)
{
string dateFrom = datepickerfrom.Text; // -- updated
string dateTo = datepickerto.Text; // -- updated
InputData data = new InputData(dateFrom, dateTo);
Session["inputData"] = data;
gvErrorLog.PageIndex = 0;
LoadLogErrorData(data);
}
If you insist on your tags, you can add a hidden variable and update those hidden variable on change event of your textboxes.
I assume your textboxes are set up like the following
$(function () {
$("#<%=datepickerfrom.ClientID%>").datepicker();
$("#<%=datepickerto.ClientID%>").datepicker();
});
I finally found the answer to my problem here:
http://www.jquerybyexample.net/2010/08/jquery-datepicker-does-not-work-after.html
I have a requirement where i have to update a textbox if any of the value in my grid view changes.. I have a gridview with 2 rows ..
one a template field with label and another template field with a textbox...
my Grid view looks like
name value
a (empty textbox)
b (empty textbox)
c (empty textbox)
now when the user enters a value in teh text box it should automatically update another textbox which is linked to this.
Here my questions is when someone enters a value in the textbox an event should be fired!
(I am getting the names a,b,c, from database). i dont want to have an edit link or update link because all the values to be entered are mandatory!
i tried Grid_SelectedIndexChanged1 but this not firing.. is there something i am missing or i need to change so that the evant is fired and i can update the other textbox??
I am new to ASP.NET so please help!
Thanks in advance!
If the updates are supposed to be triggered when the text changes, you should use the OnTextChanged event of the TextBox, and set AutoPostBack to true.
EDIT
To avoid duplicating efforts here, using the above approach you can find the row index using the technique that Pankaj Garg outlined in his answer:
int rowIndex = ((GridViewRow)((TextBox)sender).NamingContainer).RowIndex;
The biggest caveat to this approach is that it's not forgiving of changes in the markup. If you were to wrap the TextBox in another control that implements INamingContainer, the example above would break. For example:
<asp:TemplateField>
<asp:Panel ID="Panel1" runat="server"> <!-- becomes the naming container -->
<asp:TextBox ID="TextBox1" runat="server" onchange='valueChanged(<%# Container.ItemIndex %>);' />
</asp:Panel>
</asp:TemplateField>
That being said, you would want to notate your markup accordingly so other developers know to be careful when making changes.
EDIT
As an alternative, you could also trigger the postback in JavaScript using the onchange event of the TextBox:
<script type="text/javascript">
valueChanged = function(rowIndex){
__doPostBack("<%= GridView1.ClientID %>", rowIndex);
}
</script>
<asp:GridView ID="GridView1" runat="server" DataKeyNames="ID" ...>
<Columns>
<asp:TemplateField>
<asp:TextBox ID="TextBox1" runat="server" onchange='valueChanged(<%# Container.ItemIndex %>);' />
</asp:TemplateField>
</Columns>
</asp:GridView>
In the code-behind, override the RaisePostBackEvent method, and put your update logic there:
protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
{
base.RaisePostBackEvent(source, eventArgument);
if (source == GridView1)
{
int rowIndex = int.Parse(eventArgument);
TextBox txt = GridView1.Rows[rowIndex].FindControl("TextBox1") as TextBox;
if (txt != null)
{
var id = (int)GridView1.DataKeys[rowIndex]["ID"];
var text = txt.Text.Trim();
//update the database
}
}
}
You can check the Current Row Index like below...
((GridViewRow)((TextBox)sender).NamingContainer).RowIndex
Create a handler for OnTextChanged event and set the AutoPostBack Property True.
protected void TextBox_TextChanged(object sender, EventArgs e)
{
int CurrentGridIndex = ((GridViewRow)((TextBox)sender).NamingContainer).RowIndex
}
I have a repeater that will present a set of titles and checkboxes (some checked some not). Each is wrapped in a div with a background colour. All I want to do is change the background colour for the checkboxes that are already checked so they are easily identified on the page.
Here's the repeater:
<asp:Repeater ID="rptCartridges" runat="server" OnItemDataBound="rp_ItemDataBound">
<ItemTemplate>
<div class="cartridgebox">
<span class="cartridgeboxl"><%#Eval("cartName") %></span>
<span class="cartridgeboxr">
<asp:CheckBox ID="chkCart" name="chkbox" Checked = '<%#Convert.ToBoolean(DataBinder.Eval(Container.DataItem, "cartChecked"))%>' runat="server" />
<asp:HiddenField ID="hfCartID" runat="server" Value='<%#DataBinder.Eval(Container.DataItem, "cartID")%>' />
</span>
</div>
</ItemTemplate>
</asp:Repeater>
All I really want to do is change the class cartridgebox to cartridgeboxchecked if the checkbox is returned as checked.
I have tried manipulating rp_ItemDataBound. Where it goes wrong is the actual changing of the class inline. I've tried using if statements, add runat="server" to the div and populating a variable and then using Response.Write inside the class statement. But nothing seems to work.
What seems the neatest way would be to use rp_ItemDataBound like so:
protected void rp_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
string chkboxClass = "cartridgebox";
CheckBox chk = (CheckBox)e.Item.FindControl("chkCart");
HiddenField hfCartID = (HiddenField)e.Item.FindControl("hfCartID");
// Adding the hide.Value Attribute to the chk.Text field.
chk.Attributes.Add("Text", hfCartID.Value);
if (chk.Checked == true)
{
chkboxClass = "cartridgeboxchecked";
}
else
{
chkboxClass = "cartridgebox";
}
}
But I lack the understanding to pass the variable chkboxClass to the div's class dynamically. Of course I am probably looking at this completely wrong so any guidance would be appreciated.
Use following markup for div in ItemTemplate : <div class='<%# ((bool)Eval("cartChecked"))? "cartridgeboxchecked" : "cartridgeboxl" %>' >
If you need to change div's class on checkbox change immediatelly, consider to add onclick client-side event handler to checkbox in ItemDataBound Repeater's event handler
this seemed simple at first but I can't get it to work.
I have the following scenario:
<asp:ListView ID="CommentsListView" runat="server">
<LayoutTemplate>
<asp:PlaceHolder ID="itemPlaceholder" runat="server" />
</LayoutTemplate>
<ItemTemplate>
<UC:Comment runat="server" CommentItem="<%# CurrentComment %>" />
<br />
</ItemTemplate>
</asp:ListView>
<asp:TextBox ID="NewComment" runat="server" />
<asp:ImageButton ImageUrl="/images/ball.png" runat="server"
OnClick="SubmitComment" />
Code:
protected void Page_Load(object sender, EventArgs e)
{
RenderListView();
}
protected void RenderListView()
{
CommentsListView.DataSource = //Get the data source objects
CommentsListView.DataBind();
}
protected CommentObject CurrentComment
{
get { return (CommentObject)Page.GetDataItem(); }
}
protected void SubmitComment(object sender, ImageClickEventArgs e)
{
//code to submit comment
RenderListView();
}
basically, when I submit a comment, I want to see it in the ListView, but I don't. "MyControl" gets a null comment in the post-back, for all of the items (not just the new one).
Only after I refresh the page, I can see the new comment that I'v submitted. I can't however refresh the page every submit because this code is inside an UpdatePanel (the issue occurs without the UpdatePanel as well).
Any idea how to solve this?
I can't find any specifics on this, but I have a hunch the user control in your ItemTemplate is causing the issue. Can you remove it and see if it works?
I notice that you are calling RenderListView in both SubmitComment and PageLoad which I believe will cause it to fire twice when the button is clicked (with PageLoad firing first). It looks like the code you posted is simplified. Is it possible that there is something happening in the PageLoad which is sabotaging your SubmitComment steps?
I finally solved it, if anyone else may encounter this -
The solution was to avoid "<%#" and instead use the ItemDataBound event:
<asp:ListView ID="Comments" runat="server"
OnItemDataBound="CommentsItemDataBound">
and the method itself:
protected void CommentsItemDataBound(object sender, ListViewItemEventArgs e)
{
var commentItem = (Comment)(((ListViewDataItem)e.Item).DataItem);
var commentControl = (Comment)e.Item.FindControl("CommentControl");
commentControl.CommentItem = commentItem;
}
This way, the binding of each control works as expected.