I have a repeater with radiobuttons in it.
<script type="text/javascript">
$(document).ready(function ()
{
$("#test input:radio").attr("name", "yourGroupName");
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="test">
<asp:Repeater runat="server" ID="rep" onitemdatabound="rep_ItemDataBound"
onitemcommand="rep_ItemCommand">
<ItemTemplate>
<asp:RadioButton ID="n" runat="server" Text='<%# Eval("name") %>' AccessKey='<%# Eval("id")%>' />
</ItemTemplate>
</asp:Repeater>
</div>
I am using the javascript at the top to fix the radiobutton bug in .net.
i bind a list to the repeater at page load, with a if (!Page.IsPostback) around it.
edit:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
rep.DataSource = z.Table.ToList();
rep.DataBind();
}
}
then i have a button, that when clicked should do something with the radio button that's been selected, this is the problem now:
foreach (RepeaterItem i in rep.Items)
{
RadioButton erb = i.FindControl("n") as RadioButton;
if (erb.Checked)
{
//do stuff
}
}
no matter which radiobutton i select, when i click the button and i debug the entire loop, every checkbox == false. i'm doing more stuff with the code but i've simplified it, because this is the biggest problem.
i have seen countless of topics about this issue and i have looked through them all but i still can't seem to get this to work.
Please try adding OnCheckedChanged="RadioButton1_OnCheckedChanged" AutoPostBack="true" on you radio button this will trigger post back on click of the button and you will be able to find the Checked one
I think this is all down to the sequence of events in ASP.NET .
Try putting your DataBind code in the Page_Init procedure, that way the state of the radiobuttons will be set by the time it reaches the Page_Load procedure.
Related
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
It seems I am struggling with the order of the page life cycle. Based on the user selecting button 1 or 2, I need to have respective controls added dynamically during the Page_Load event. My problem is when a button is clicked the Page_Load event is executed before Button_Click event code is read. There for my variable "doWhat" is not assigned a value until after the Page_Load event. How can I have the "doWhat" variable assigned a value to be read during the Page_Load?
Below is asp.net form code for the two buttons:
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button 1" onclick="Button_Click" />
<asp:Button ID="Button2" runat="server" Text="Button 2" onclick="Button_Click" />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>
</form>
Below is the code behind:
int doWhat;
protected void Page_Load(object sender, EventArgs e)
{
doWhat = Convert.ToUInt16(ViewState["doWhat"]);
if (doWhat == 1)
{
// code to dynamically load group 1 controls
}
else
{
// code to dynamically load group 2 controls
}
Label1.Text = Convert.ToString(doWhat);
}
protected void Button_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
if (btn.ID == "Button1")
{
doWhat = 1;
}
else
{
doWhat = 2;
}
ViewState.Add("doWhat", doWhat);
}
If you are comfortable with javascript then you can achieve it by making following changes in your design and code. Add a hidden field in your aspx page. Your HTML code should be like this.
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button 1" OnClick="Button_Click" OnClientClick="return doWhatAction(1);" />
<asp:Button ID="Button2" runat="server" Text="Button 2" OnClick="Button_Click" OnClientClick="return doWhatAction(2);" />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
<asp:HiddenField ID="HiddenField1" Value="1" runat="server" />
<script type="text/javascript">
var doWhatAction = function (actionIndex) {
//alert(actionIndex);
document.getElementById("<%=HiddenField1.ClientID%>").value = actionIndex;
return true;
}
</script>
</div>
</form>
And your code will be something like...
int doWhat;
protected void Page_Load(object sender, EventArgs e)
{
//doWhat = Convert.ToUInt16(ViewState["doWhat"]);
doWhat = Convert.ToUInt16(HiddenField1.Value);
if (doWhat == 1)
{
// code to dynamically load group 1 controls
}
else
{
// code to dynamically load group 2 controls
}
Label1.Text = Convert.ToString(doWhat);
}
protected void Button_Click(object sender, EventArgs e)
{
//Do Nothing
//Button btn = sender as Button;
//if (btn.ID == "Button1")
//{
// doWhat = 1;
//}
//else
//{
// doWhat = 2;
//}
//ViewState.Add("doWhat", doWhat);
}
You can use jquery or javascript i this case.
Took on hidden variable in form
initialize it on click event of button in javascript
Read value of hidden variable in page load
<head >
<title>Hidden Variable</title>
<script type="text/javascript">
function SetHDNValue()
{
var hdnControlID = '<%= hdnControl.ClientID %>';
document.getElementById(hdnControlID).value=1;
}
</script>
</head>
<body >
<form id="form1" runat="server">
<div>
<input id="hdnControl" type="hidden" runat="server" />
<asp:Button ID="btnJSValue" Text="Click" runat="server" OnClientClick="SetHDNValue()"
/>
</div>
</form>
</body>
And in code behind file hdnControl.value
Since long ago I am not working with asp.net forms. And forgot doing things.But I found how you can do. As on stackoverflow link like answers is wrong. I copied main statements from the link which indicate how post-back events works and how you can use it for your purpose. For more http://aspsnippets.com/Articles/How-to-find-the-control-that-caused-PostBack-in-ASP.Net.aspx
All controls accept Button and ImageButton use JavaScript for causing a postback. To enable postback on these controls one has to set AutoPostBack property to true.
When you set this property to true, __doPostBack function is called on event which causes a postback.
The __doPostBack function is not visible in Source of the page until you place a LinkButton or set AutoPostBack to true for any of the above discussed controls.
Here is how generated __doPostBack looks:
<script type = "text/javascript">
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
</script>
The __doPostBack function simply stores the below two arguments in two hidden fields
eventTarget – The name of the control that caused the postback
eventArgument – The argument to be sent to server.
In two hidden fields which also appear only when AutoPostBack is set to true
Finally, here is how you can distinguish by getting control's ID that caused the postback :
if (IsPostBack)
{
string CtrlID = string.Empty;
if (Request.Form["__EVENTTARGET"] != null &&
Request.Form["__EVENTTARGET"] != string.Empty)
{
CtrlID = Request.Form["__EVENTTARGET"];
/****implement Your logic depending on control ID****/
}
}
I have the following markup / code block in the ASPX file.
The binding of the ddl is triggered after Page_Load event which is in the code behind file.
This results me not able to get the selected value of the dropdownlist if I were to use such flow.
However for some purpose I require it to work this way.
Any idea how I could get the dropdownlist selected value when a post back is being triggered (click of the button)?
Page URL: page.aspx?para1=0¶2=value
ASPX PAGE
<%
if (Convert.ToInt32(Request.QueryString["para1"]) == 0)
{
ddl.DataValueField = "value";
ddl.DataTextField = "text";
ddl.DataSource = ds; //ds is valid, exact code not shown
ddl.DataBind();
} else {
//write in this area
Response.Write("Not 0");
}
%>
<form runat="server" id="user_form" class="form-horizontal">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<asp:UpdatePanel ID="updPanel" runat="server">
<ContentTemplate>
<asp:DropDownList runat="server" ID="ddl">
</asp:DropDownList>
<%-- this button will call btnSave_Click to get the ddl's value--%>
<asp:Button runat="server" ID="btn" Text="Button" OnClick="btn_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
CODE BEHIND
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//do my stuff
}
}
protected void btn_Click(object sender, EventArgs e)
{
int intValue = Convert.ToInt32(ddl.SelectedValue);
//do my stuff
}
The ASPX Page code block will run after Page_Load / page's lifecycle, then will determine what to do base on the url parameters.
Thanks in advance!
You could always throw in a hidden object and use jquery to copy the value to the hidden value based on a certain action without a postback and would do it client side like it sounds like you want it to do
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
I'm new to this ASP.NET stuff. In my page I have a Datalist with a FooterTemplate. In the footer I have a couple panels that will be visible depending on the QueryString. The problem I am having is trying to find these panels on Page_Load to change the Visible Property. Is there a way to find this control in the Page_Load? For example this is part of the aspx page:
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:DataList ID="dlRecords" runat="server">
<FooterTemplate>
<asp:Panel ID="pnlArticleHeader" runat="server" Visible="false" >
</asp:Panel>
</FooterTemplate>
</asp:Datalist>
</asp:Content>
Here is something in the codebehind:
protected void Page_Load(object sender, EventArgs e)
{
location = Request.QueryString["location"];
if (location == "HERE")
{
Panel pnlAH = *Need to find control here*;
pnlAH.Visible=true;
}
}
Like I said I am new at this. Everything I have found doesn't seem to work so I decided to post a specific question. Thanks in advance
DataList has event OnItemCreated, overriding allows select type of row:
Panel _pnlArticleHeader;
void Item_Created(Object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Footer)
{
_pnlArticleHeader =(Panel)e.Item.FindControl("pnlArticleHeader");
}
}
After event invocation in the field: _pnlArticleHeader you will get desired panel. This way is safe since created only once. NOTE! same way for common DataList's row would return only last one.