Datalist postback issue - c#

I have a Datalist on my asp.net page with an ImageButton in the <Item Template>. When an ImageButton is clicked, I use the ItemCommand event to set the border of the data item:
protected void dlProducts_ItemCommand(object source, DataListCommandEventArgs e)
{
e.Item.BorderColor = System.Drawing.ColorTranslator.FromHtml("#ff5800");
e.Item.BackColor = System.Drawing.ColorTranslator.FromHtml("#ffeee5");
}
That works fine, but the border disappears when a postback occurs. I've tried binding my datalist in the page load event like so:
if (!Page.IsPostBack)
{
dlProducts.DataSource = ObjectDataSource4;
dlProducts.DataKeyField = "Product_ID";
dlProducts.DataBind();
}
But the border is gone after a postback. What gives?
Here is the datalist markup:
<asp:DataList ID="dlProducts" runat="server" CellPadding="5" CellSpacing="5"
OnItemCommand="dlProducts_ItemCommand"
RepeatColumns="4" RepeatDirection="Horizontal"
ondatabinding="dlProducts_DataBinding"
onitemdatabound="dlProducts_ItemDataBound" >
<ItemTemplate>
<asp:ImageButton ID="img" ImageAlign="Middle" runat="server"
ImageUrl='<%# "~/uploads/profile/" + DataBinder.Eval(Container.DataItem,"ProfileImageName").ToString() %>'
onclick="img_Click" />
</ItemTemplate>
</asp:DataList><asp:ObjectDataSource ID="ObjectDataSource4" runat="server" SelectMethod="GetAllCompetitorProducts"
TypeName="DalProduct" OldValuesParameterFormatString="original_{0}">
<SelectParameters>
<asp:SessionParameter Name="producttype_id" SessionField="ProductType_id" Type="Int32" DefaultValue="13" />
<asp:SessionParameter DefaultValue="2009" Name="Year" SessionField="Year" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>

Try this:
<ItemTemplate>
<div id="divImg" runat="server">
<asp:ImageButton ID="img" ImageAlign="Middle" runat="server"
ImageUrl='<%# "~/uploads/profile/" + DataBinder.Eval(Container.DataItem,"ProfileImageName").ToString() %>'
onclick="img_Click" />
</div>
</ItemTemplate>
In ItemCommand
protected void dlProducts_ItemCommand(object source, DataListCommandEventArgs e)
{
var divImg = (HtmlGenericControl)e.Item.FindControl("divImg");
divImg.Style.Add("background-color", "#ffeee5");
}
As you can see, img control is now wrapped in a server div element so that when postback occurs it automatically restores its state from viewstate. Being said that, it works fine with postback but if you rebind your grid, it would lose its style. For it to persist after the re-bind, on itemcommand store the id's of the img in viewstate and apply the style according.
Also, I would suggest using class attribute for div element instead of applying colors in code-behind.
divImg.Attributes.Add("class", "classnamewhichhasgroundandbordercolor");

Related

How to add ASP.NET control for <i></i> tags in Html and assign them inside .FindControl() method on .cs?

Does anyone knows How to add ASP.NET control for <i></i> tags?
i am looking for ASP.NET Control that is equivalent with <i> Html tag
in my case, I also want to implement .FindControl() method for it inside the .cs file.
Here's the part of the code..
Example.axcs
<asp:Panel id="forDiv" CssClass="input-group colorpicker-component" runat="server">
<asp:TextBox ID="txtHeree" class="form-control" runat="server" Style="width: auto"></asp:TextBox>
<asp:Panel CssClass="input-group-append" runat="server">
<asp:Label CssClass="input-group-addon input-group-text" runat="server"><i></i></asp:Label>
</asp:Panel>
</asp:Panel>
from the code above,
the FindControl method that I have implemented goes like this,
Example.ascx.cs
TextBox txtVal = e.Row.FindControl("txtHeree") as TextBox;
Panel txtVal = e.Row.FindControl("forDiv") as Panel;
and, etc..
My current problem is, I still can't find both the equivalent ASP.NET Control for <i></i> tags and also for .FindControl() method for it.
sure, I have read the reference to another QnA forum from both Stackoverflow and Microsoft Docs:
ASP.NET Control to HTML tag equivalentandhttps://learn.microsoft.com/en-us/troubleshoot/developer/webapps/aspnet/development/server-controls
ANY suggestion, answer, or efficient code for the <i></i> tag control, will be very.. very helpful.
Thank You.
Sure, if you add a "id" tag, and runat=server, then that "i" thing becomes quite much a server side control.
And doing that allows use in listview, repeaters etc.
So, do this:
<i id="MyIguy" runat="server"></i>
<br />
<asp:Button ID="Button1" runat="server" Text="Button"
CssClass="btn" OnClick="Button1_Click" />
So, with code behind the button like this:
protected void Button1_Click(object sender, EventArgs e)
{
MyIguy.InnerText = "this is fun";
}
And we see this when run:
And say we use a gridview, repeater etc.?
say this markup, we just dropped in that (wiht id, and runat=server).
Quite much makes that control work, look, and feel like any other server side asp.net control.
Say, this markup and gridview (for the find control example).
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
DataKeyNames="ID" CssClass="table" >
<Columns>
<asp:TemplateField HeaderText="Hotel Name"> <ItemTemplate>
<asp:Label ID="txtHotel" runat="server" Text='<%# Eval("HotelName") %>' ></asp:Label>
</ItemTemplate> </asp:TemplateField>
<asp:TemplateField HeaderText="City"> <ItemTemplate>
<asp:Label ID="txtCity" runat="server" Text='<%# Eval("City") %>' ></asp:Label>
</ItemTemplate> </asp:TemplateField>
<asp:TemplateField HeaderText="Description"> <ItemTemplate>
<i id="Descript" runat="server"> <%# Eval("Description") %> </i>
</ItemTemplate> </asp:TemplateField>
<asp:TemplateField HeaderText="View"> <ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="View"
CssClass="btn" OnClick="Button1_Click" />
</ItemTemplate> </asp:TemplateField>
</Columns>
</asp:GridView>
Code to load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = General.MyRst("SELECT * FROM tblHotelsA ORDER BY HotelName");
GridView1.DataBind();
}
}
And we have this now:
And our view button click code, say this:
protected void Button1_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
GridViewRow gRow = btn.NamingContainer as GridViewRow;
int? PKID = GridView1.DataKeys[gRow.RowIndex]["ID"] as int?;
Debug.Print("pk data base row id = " + PKID.ToString());
Debug.Print("Row click index = " + gRow.RowIndex);
// get hotel name
Label txtHotel = gRow.FindControl("txtHotel") as Label;
Debug.Print("Hotel name = " + txtHotel.Text);
// get our <i> guy
HtmlGenericControl myIthing = gRow.FindControl("Descript") as HtmlGenericControl;
Debug.Print("Our i guy = " + myIthing.InnerText);
}
Output :
so, most such controls - adding a "id" and runat="server", and at that point, it quite much behaves like most other asp.net controls.

ListView inside an UpdatePanel not getting rebound

I have a ASP.NET ListView inside an UpdatePanel.
In the ItemTemplate there are 2 buttons with Commands "UpdateCart" & "RemoveCart".
In both the commands, the datasource of ListView (an SQL DataSource) gets rebound.
There is no InsertCommand/UpdateCommand/DeleteCommand on the SqlDataSource
My problem is :
Whenver these buttons are clicked : the datasource does not get refreshed.
however I can see from debug mode that values are indeed passed to the datasource selecting method correctly.
The relevant ASPX Page :
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdateProgress ID="UpdateProgress1" DisplayAfter="10" runat="server" AssociatedUpdatePanelID="UpnlMain">
<ProgressTemplate>
<div class="divWaiting">
<asp:Label ID="lblWait" runat="server" Text=" Please wait... " />
<asp:Image ID="imgWait" runat="server" ImageAlign="Middle" ImageUrl="~/Image/AjaxLoading.gif" />
</div>
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="UpnlMain" runat="server">
<ContentTemplate>
<asp:ListView ID="lvMain" runat="server" DataSourceID="sdsMain" DataKeyNames="Code"
OnItemCommand="lvMain_ItemCommand">
<EmptyDataTemplate>
<div class="col-xs-12">
<span>No Items in Cart.</span>
</div>
</EmptyDataTemplate>
<ItemTemplate>
<asp:Label ID="lblCode" runat="server" Text='<%# Eval("Code") %>' Visible="false" />
Product " <asp:Literal ID="ltrStyleNo" runat="server" Text='<%# Eval("StyleNo") %>' />
Qty : <asp:TextBox ID="txtQty" runat="server" type="number" CssClass="txtQty OnlyNumeric form-control text-center input-sm"
Text='<%# Eval("Qty") %>'></asp:TextBox>
<asp:ImageButton ID="btnUpdate" runat="server" ImageUrl="~/image/update.png" CssClass="btn btnUpdateCart"
CommandName="UpdateCart" AlternateText="Update Qty" />
<asp:ImageButton ID="btnDelete" runat="server" ImageUrl="~/image/delet.png" CssClass="btn"
CommandName="DeleteCart" AlternateText="Remove Item" />
</ItemTemplate>
<LayoutTemplate>
<asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>
</LayoutTemplate>
</asp:ListView>
<asp:SqlDataSource ID="sdsMain" runat="server" ConnectionString="<%$ ConnectionStrings:CurrentConnectionString %>"
SelectCommand="pGetItemsForCart" SelectCommandType="StoredProcedure" OnSelecting="sdsMain_Selecting"
UpdateCommand="NoUpdate" UpdateCommandType="StoredProcedure">
<UpdateParameters>
<asp:Parameter DefaultValue="-1" Name="WoSCodeCSV" Type="String" />
</UpdateParameters>
<SelectParameters>
<asp:Parameter DefaultValue="-1" Name="WoSCodeCSV" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
The Code Behind Code :
protected void sdsMain_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
e.Command.Parameters[0].Value = GetCartCodes(); //gives some values in csv from Session ..
}
protected void lvMain_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName.ToLower() == "UpdateCart".ToLower())
{
Label lblCode = e.Item.FindControl("lblCode") as Label;
TextBox txtQty = e.Item.FindControl("txtQty") as TextBox;
//Some update in a Session
BindListView();
}
else if (e.CommandName.ToLower() == "DeleteCart".ToLower())
{
Label lblCode = e.Item.FindControl("lblCode") as Label;
//Some update in a Session
BindListView();
}
else if (e.CommandName.ToLower() == "RefreshCart".ToLower())
{
Label lblCode = e.Item.FindControl("lblCode") as Label;
BL.StyleSearchHelper.PriceItem(Page, lblCode.Text);
BindListView();
}
}
void BindListView()
{
sdsMain.DataBind();
lvMain.DataBind();
}
Try replace your buttons outside the updatepanel. Page will not getting refresh when the buttons are in updatepanel. sorry i can't make comment so I post here as an answer.

Get Index Item from a ListView control

ASPX
<asp:SqlDataSource ID="SqlDataSource5" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [Themes] WHERE ([Theme] = #Theme) ORDER BY [Price]">
<SelectParameters>
<asp:Parameter DefaultValue="Dubai-and-Beyond" Name="Theme" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:ListView ID="theme5" runat="server" DataSourceID="SqlDataSource5">
<LayoutTemplate>
<div id="itemPlaceHolderContainer" runat="server">
<span id="itemPlaceHolder" runat="server"></span>
</div>
</LayoutTemplate>
<ItemTemplate>
<div>
<asp:Image ID="Destinationimage" runat="server"
ImageUrl='<%# Eval("ID", "~/CMS/ThemesHandler.ashx?ID={0}")+"&img=1"%>'
AlternateText="Destination_Image" Height="140px" Width="179px" />
<asp:Label ID="lblcountry" runat="server" Text='<%#Eval("Country") %>' />
</div>
<div class="hotel_name">
<asp:Label ID="lblcountry" runat="server" Text='<%#Eval("Country") %>' /></div>
<asp:ImageButton ID="imgbtn5" runat="server" ImageUrl="images/book_nw.png"
OnClick="imgbtn5_Click" AlternateText="get_quote"/></div>
</ItemTemplate>
</asp:ListView>
Code behind
protected void imgbtn5_Click(object sender, EventArgs e)
{
ListViewItem item = theme5.Items[0];
Label country = (Label)item.FindControl("lblcountry");
string con = country.Text.ToString();
Session["country"] = con.ToString();
Response.Redirect("Get_Quote.aspx");
}
Here, Theme5 is Listview. There is a Label and imgbutton in EACH listview item.
I want to transfer label value on imgbutton click event.
Problem here is i am not able to identify Row index of listview item.
You can make use of CommandName and CommandArgument of your ImageButton within your ListView. You may than access the according item from within your ItemCommand event.
<asp:ImageButton ID="imgbtn5" runat="server" ImageUrl="images/book_nw.png"
OnClick="imgbtn5_Click" AlternateText="get_quote"
CommandName="YOUR_COMMAND_NAME"
CommandArgument='<%#Eval("ANY_COLUMN_OF_SOURCE") %>' />
And within your codeBehind file
protected void theme5_OnItemCommand(object sender, ListViewCommandEventArgs e)
{
if (String.Equals(e.CommandName, "YOUR_COMMAND_NAME"))
{
string arg = e.CommandArgument; // do whatever you want
ListViewDataItem dataItem = (ListViewDataItem)e.Item;
}
}

How do I programmatically add new row to gridview on button click handler?

This is my markup:
<asp:Button runat="server" ID="btnabc" Text="Hello"
onclick="abc_Click" /> <br /> <br />
<asp:GridView runat="server" ID="test" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox runat="server" ID="txt" Text = "<%# Container.DataItem %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
This is my button click handler:
protected void abc_Click(object sender, EventArgs e)
{
}
I can't find any method like gridview.Rows.Add().
You don't. But you can simply and straightforwardly add a new item to your grid's DataSource and you are done.
Try adding a row to the datasource object, and then rebind the GridView.

Radiobuttonlist event not always firing

I have a radiobuttonlist with a selectedindexchanged event that updates a search function. One of the items is specified in the aspx, and the others are appended databound items. No matter what I set as the default, that item will not fire the event. All other items will fire the event. Also, it seems that after the "dead" item is selected, the event won't fire at all.
How can I track down the error and correct? Here is current code.
EDIT: Sorry if the short version was misleading. I wasn't sure what to include. Here is the whole page.
All aspx:
<%# Page Language="C#" MasterPageFile="~/MSDS/MSDS.master" EnableEventValidation="false"
AutoEventWireup="true" CodeFile="SearchMSDS.aspx.cs" Inherits="MSDS_ByDept" Title="NCLWeb - Search MSDS" %>
<%# Register Assembly="SqlWhereBuilder" Namespace="UNLV.IAP.WebControls" TagPrefix="cc1" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc2" %>
<asp:Content ID="Content1" ContentPlaceHolderID="PageContent" runat="Server">
<h2>
<asp:Label ID="lblTitle" runat="server">Search Active MSDS</asp:Label></h2>
<table class="style1">
<tr>
<td style="width: 435px" valign="top">
<asp:Panel runat="server" ID="pnlSearch" DefaultButton="btnSearch">
<asp:TextBox ID="txtSimpleSearch" runat="server" Width="262px"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" Width="96px" OnClick="btnSearch_Click" />
<br />
<asp:LinkButton ID="btnAdvSearch" runat="server" OnClick="btnAdvSearch_Click" Font-Size="Small">Show Advanced Search</asp:LinkButton>
</asp:Panel>
<asp:Panel ID="pnlAdvSearch" runat="server" Width="635px" DefaultButton="btnRunAdvSearch">
<asp:Button ID="btnRunAdvSearch" runat="server" OnClick="btnRunAdvSearch_Click" Text="Advanced Search" />
<cc1:SqlWhereBuilder ID="SqlWhereBuilder1" runat="server" ClientCodeLocation="../JavaScripts/SqlWhereBuilder.js"
FieldsFile="../ConfigFiles/SearchMSDS.config" OperatorListsFile="../ConfigFiles/SearchMSDS.config"
ValueEntryFile="../ConfigFiles/SearchMSDS.config">
</cc1:SqlWhereBuilder>
<br />
<br />
</asp:Panel>
<cc2:CollapsiblePanelExtender ID="pnlAdvSearch_CollapsiblePanelExtender" runat="server"
CollapseControlID="btnAdvSearch" Collapsed="True" Enabled="True" ExpandControlID="btnAdvSearch"
TargetControlID="pnlAdvSearch">
</cc2:CollapsiblePanelExtender>
</td>
<td valign="top">
<asp:Panel ID="pnlStatus" runat="server">
<asp:RadioButtonList ID="rblStatus" runat="server" AppendDataBoundItems="True"
AutoPostBack="True" DataSourceID="SqlDataSource1" DataTextField="DisplayValue"
DataValueField="Value" OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged"
RepeatDirection="Horizontal" CellPadding="3" CellSpacing="3"
CausesValidation="True" Visible="True">
<asp:ListItem Selected="True">All</asp:ListItem>
</asp:RadioButtonList>
</asp:Panel>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NCLWebConnectionString %>"
SelectCommand="getOptionList" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter DefaultValue="msds_Status" Name="ListName" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:UpdatePanel runat="server" ID="upd2">
<ContentTemplate>
<asp:Button ID="btnExport" runat="server" Text="Export Results"
OnClick="btnExport_Click1" UseSubmitBehavior="False" />
</ContentTemplate>
</asp:UpdatePanel>
</td>
</tr>
</table>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:UpdateProgress ID="UpdateProgress1" runat="server" DisplayAfter="100" DynamicLayout="False">
<ProgressTemplate>
<img src="../images/loading.gif" alt="Loading..." style="text-align: center" />
<asp:Label ID="lblProgress" runat="server"></asp:Label></ProgressTemplate>
</asp:UpdateProgress>
<asp:GridView ID="gridResults" runat="server" DataSourceID="sqlMSDS" OnRowDataBound="GridView1_RowDataBound"
AllowPaging="True" PageSize="25" AllowSorting="True" OnSelectedIndexChanged="gridResults_SelectedIndexChanged"
AutoGenerateColumns="False" EmptyDataText="No matching MSDS Sheets." OnSorted="gridResults_Sorted">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" Visible="false"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="ChemicalTitle" HeaderText="ChemicalTitle" SortExpression="ChemicalTitle" />
<asp:BoundField DataField="Manufacturer" HeaderText="Manufacturer" SortExpression="Manufacturer" />
<asp:BoundField DataField="UsageDept" HeaderText="UsageDept" SortExpression="UsageDept" />
<asp:BoundField DataField="Notes" HeaderText="Notes" SortExpression="Notes" />
<asp:BoundField DataField="Health" HeaderText="Health" visible="false" SortExpression="Health" />
<asp:BoundField DataField="Fire" HeaderText="Fire" visible="false" SortExpression="Fire" />
<asp:BoundField DataField="Reactivity" HeaderText="Reactivity" visible="false" SortExpression="Reactivity" />
<asp:BoundField DataField="DateUpdated" HeaderText="DateUpdated" SortExpression="DateUpdated" />
</Columns>
<SelectedRowStyle BackColor="Yellow" />
</asp:GridView>
<asp:SqlDataSource ID="sqlMSDS" OnSelected="sqlMSDS_OnSelected" runat="server" ConnectionString="<%$ ConnectionStrings:NCLWebConnectionString %>"
SelectCommand="SELECT [ID]
,[ChemicalTitle]
,[Manufacturer]
,[UsageDept]
,[Notes]
,[Health]
,[Fire]
,[Reactivity]
,[DateUpdated]
FROM [msds_Sheets]" OnSelecting="sqlMSDS_Selecting"></asp:SqlDataSource>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnSearch" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="btnRunAdvSearch" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="rblStatus" EventName="SelectedIndexChanged" />
<asp:AsyncPostBackTrigger ControlID="btnExport" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<br />
</asp:Content>
And code-behind:
List<String> safeWords = new List<String>();
protected void Page_Load(object sender, EventArgs e)
{
pnlStatus.Visible = User.IsInRole("msds_Admin");
gridResults.DataKeyNames = new String[] { "id" };
txtSimpleSearch.Focus();
if (!IsPostBack)
{
safeWords.Add("delete");
safeWords.Add("insert");
safeWords.Add("update");
safeWords.Add("set");
safeWords.Add("exec");
safeWords.Add("N'");
sqlMSDS.SelectCommand += " Where status = 0 ";
Session["Sql"] = sqlMSDS.SelectCommand;
try
{
Session["OriginalSQL"] = sqlMSDS.SelectCommand.Remove(sqlMSDS.SelectCommand.IndexOf("Where"));
}
catch (Exception)
{
Session["OriginalSQL"] = sqlMSDS.SelectCommand;
}
}
}
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
((Label)UpdateProgress1.FindControl("lblProgress")).Text = "Searching...";
if (btnSearch.Visible)
{
btnSearch_Click(null, null);
if (RadioButtonList1.SelectedValue != "All")
{
sqlMSDS.SelectCommand += " And Status = " + RadioButtonList1.SelectedValue;
}
else
{
//Somehow force the grid to research using no status parameter
sqlMSDS.SelectCommand = Session["Sql"].ToString();
}
}
else
{
btnRunAdvSearch_Click(null, null);
if (RadioButtonList1.SelectedValue != "All")
{
if (sqlMSDS.SelectCommand.Contains("Where"))
{
sqlMSDS.SelectCommand += " And Status = " + RadioButtonList1.SelectedValue;
}
else
{
sqlMSDS.SelectCommand += " Where Status = " + RadioButtonList1.SelectedValue;
}
}
else
{
//Somehow force the grid to research using no status parameter
sqlMSDS.SelectCommand = Session["Sql"].ToString();
}
}
}
Here is what was happening to me and the fix.
I had a radiobuttonlist that was not in an update panel, but defined as a trigger for an update panel. I had onselectedindexchanged defined as well. Radiobuttonlist had the first listitem attribute selected="true", so it would be selected by default on page load. Then selecting the second listitem worked fine, posting back and updating the update panel.
However, selecting the first item again was not firing onselectedindexchanged event. Using Firefox's awesome Inspect Element utility, I was able to determine that the server was generating the html element (checked only on the first, default list item). But since the radiobuttonlist was not in the update panel, the checked="checked" attribute for the second item was never getting written to the browser, even though client-side the second radio button visually appeared to be selected. Therefore, when selecting the original item the second time, the onselectedindexchanged was not firing server-side, because the newly selected index was already indicated as selected in the POST event.
You won't see this problem if the list is inside the panel you want to refresh, because the postback causes the browser to receive "new" elements with the checked="checked" on the newly selected item. The layout of my page made it inconvenient to have these in the same panel, so the fix for me was to put the radiobuttonlist in it's own little update panel. Whichever works for you, the answer is to make sure the radiobuttonlist is in SOME update panel, so the checked attribute can be sent to the browser for each item when selected.
Does this RadioButtonList specified as AsyncPostBackTrigger for another UpdatePanel? If so, check following link: CheckedChanged event not firing on a radio button within UpdatePanel
I have reproduce that behaviour and fix this with the following script:
$(function () {
$("input[type='radio']:first", $("#<%= RadioButtonList1.ClientID %>")).attr("checked", true);
});
if you can't use the jQuery try this javascript:
window.onload = function () {
window.document.getElementById("<%= RadioButtonList1.ClientID %>_0").checked = true;
};
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ClientScript.RegisterStartupScript(this.GetType(), "RadioButtonListDefaultValue", String.Format("window.document.getElementById('{0}_0').checked = true;", RadioButtonList1.ClientID), true);
}
}
As user user2965308 said, if the RadioButtonList is inside of the UpdatePanel this issue doesn't happen.
https://www.codeproject.com/Questions/118042/RadioButtonList-Postback-issue-when-selected-by-co
"Get it inside an update panel, with property "ChildrenAsTriggers" on true. This solve the issue for me."
<asp:ListItem Selected="True">All</asp:ListItem>
Clicking "All" doesn't change the selected index since that item was already selected, so the event does not fire. Picking any other option changes the selected option and causes the event to fire. I believe your goal is to display results for all statuses when you click on "All". You should do one of the following:
Display those results when the page initially loads since "All" is already selected.
Add a "Search" button that initiates the post-back instead of using the radio button's AutoPostBack.
Replace the RadioButtonList with a DropDownList, and give it two initial ListItems: "Pick a Status" - whose value is an empty string, and "All" whose value is "All". The "Pick a Status" dummy entry would look less out of place in a DropDownList than in a RadioButtonList.
Of the options listed above, I would personally prefer the "Search" button, because AutoPostBack annoys me as a user. I hate AutoPostBack DropDownLists that make the web page go bonkers when I accidentally use my mouse wheel when the list has focus.

Categories