Radio button to select one box only....ERROR - asp.net

Something is wrong with the following code cause I can select more than one radiobutton at the same time.... How can I make the following code select only one radiobutton? Please help.
<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource_BGlist">
<ItemTemplate>
<asp:RadioButton ID="Radio1" GroupName="BG_name" runat="server" Text='<%# Eval("BG_fileName") %>' />
<asp:Label ID="BG_fileNameLabel" runat="server" Text='<%# Eval("BG_fileName") %>' />
</ItemTemplate>
</asp:ListView>

The easiest way to accomplish this is to just wrap your listview in an ASP.NET Panel or GroupBox, and ASP will implement the grouping you want.
Adding a panel doesn't group radio buttons together if they are contained in some sort of repeater. Probably the best solution is to use a RadioButtonList as suggested in Grebets' Answer.
If that doesn't suit your needs you can use javascript to alter the radio buttons after they have been created. The following code will work when added to the bottom of your page:
<script type="text/javascript">
var inputElements = document.getElementsByTagName("input");
for (var inputName in inputElements) {
var input = inputElements[inputName];
if (input.type === "radio") {
input.name = "Group1";
}
}
</script>
The script can be simplified if you are using jQuery.

I think the most effective way will be use RadioButtonList:
<asp:RadioButtonList ID="RadioButtonList1" runat="server" DataTextField="BG_fileName" DataValueField="BG_fileName" DataSourceID="SqlDataSource_BGlist">
</asp:RadioButtonList>
And if you preffer to use datasources in codebehind (like I do):
public class MyClass
{
public string BG_fileName { get; set; }
public MyClass(string bgFileName)
{
BG_fileName = bgFileName;
}
}
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
RadioButtonList1.DataSource = new List<MyClass>
{
new MyClass("test string 1"),
new MyClass("test string 2"),
new MyClass("test string 3")
};
RadioButtonList1.DataBind();
}
}

Related

User Control inside Repeater - Values lost on PostBack - RadRating

I have a UserControl Inside a repeater, coded in the following way:
ParentPage.aspx:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<uc1:MovieDetailPanel runat="server" myMovieID='<%# Eval("movieID") %>' myMovieName='<%# Eval("movieName") %>'
myMovieDescription='<%#Eval("movieDescription") %>' myMovieImagePath='<%# Eval("posterImage") %>'
myMovieYear ='<%# Eval("movieYear") %>' myMovieGenre ='<%# Eval("movieGenre") %>' myMovieAverageRating ='<%# Eval("movieRating") %>'
myMovieCountry ='<%# Eval("movieCountry") %>' myMovieLanguage ='<%# Eval("movieLanguage") %>'
id="MovieDetailPanel1" />
</ContentTemplate>
</ItemTemplate>
</asp:Repeater>
ParentPage.cs:
private void LoadMyControls()
{
Repeater1.DataSource = new Common().getMoviesList(selectedGenre, selectedYear, selectedPopularity, selectedLanguage, selectedCountry);
Repeater1.DataBind();
}
UserControl.cs:
public int myMovieID { get; set; }
public string myMovieName { get; set; }
public double myMovieAverageRating { get; set; }
//some more properties
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
MovieRatingControl.Value = myMovieAverageRating ;
}
}
I have a Telerik RadRating (ID# MovieRatingControl) in my UserControl. On page load of the UserControl I am setting the value of the rating control, as passed by repeater from Database (wrapped it inside if(!Page.IsPostBack) as shown above. So each movie gets its own rating as present in the database.
However, on postback (when I click the rate button), the RadRating Control loses its value and becomes 0. This happens on all the UserControls inside the repeater and not just the UserControl in which I clicked the Rate button. Can someone please let me know how I am supposed to retain this rating value ? I need to get that and update my DB Tables.
P.S: If im not using if (!Page.IsPostBack), I retain values from DB but not the rating set by the user. The issue is, the rating set by user is not maintained.

Ajax autocomplete extender and get ID of selected item?

I am using the autocomplete extender to suggest names when a user types. How to get the select value after the user selects an item? I guess I can use onclientitemselected but I am not familiar on how to write this? I need to populate a textbox based on the selection in the autocompleteextender textbox. Thank you
<asp:TextBox ID="TextBox1" runat="server" Height="27px" Width="570px"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender" runat="server"
DelimiterCharacters="" Enabled="True" ServicePath="AutoComplete.asmx"
ServiceMethod="GetCompletionList" TargetControlID="TextBox1"
MinimumPrefixLength="2" UseContextKey="true" ContextKey="StateDropDown"
CompletionListElementID="autocompleteDropDownPanel">
</asp:AutoCompleteExtender>
For this you need to return the list from web service method with ID and Text
Here "lst" is the actual list with data from your data source.
List<string> items = new List<string>(count);
for (int i = 0; i < lst.Count; i++)
{
string str =AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(lst[i].Text,Convert.ToString(lst[i].IDValue));
items.Add(str);
}
return items.ToArray();
Then simple javascript
function GetID(source, eventArgs )
{
var HdnKey = eventArgs.get_value();
document.getElementById('<%=hdnID.ClientID %>').value = HdnKey;
}
and dont forget to set the attribute in auto complete extender
OnClientItemSelected="GetID"
The AutoCompleteExtender merely extends the ASP.NET TextBox control, so if you want to know when the text changed, then just raise the TextChanged event on the TextBox control, like this:
Markup:
<asp:TextBox ID="TextBox1" runat="server" Height="27px" Width="570px" OnTextChanged="TextBox1_TextChanged" AutoPostBack="true"></asp:TextBox>
Code-Behind:
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
// Do something here with textbox value
}

Webforms : Simplest way to allow a user to add/remove textboxes?

I don't want to use a gridview because the rest of the form isn't.
I simply need to be able to create a control to dynamically add/remove textboxes and get the value back either as a list of objects or a comma separated string.. It's proving to be much more difficult than it should.
I tried using Jquery + a regular asp.net textbox, but that only works nicely when they're starting from scratch--prepopulating the DOM with their information becomes a pain.
Is there something painfully simple that I'm missing?
It sounds like you could benefit from creating a CompositeControl.
I recently answered a similar question based on dynamically creating textboxes in which I provided a fairly detailed example.
See: Dynamically add a new text box on button click
Hope this helps.
You can add/remove the input[type=text] elements with jquery, and then use Request.Form in your code behind to get the values by element name.
javascript:
var itemCount = 0;
$("#list .add").click(function(){
itemCount++;
$(this).append("<input type='text' name='item"+itemCount+"'/><button class='remove'>Remove</button>");
});
$("#list .remove").click(function(){
$(this).prev().remove();
});
code behind:
string value1 = Request.Form["item1"];
string value2 = Request.Form["item2"];
There are two ways. The following is made using pure WebForm capabilities. Never do it in the production. It uses too much viewstate and too much updatepanel
this is a code behind
public List<String> ValueContainer {
get {
return (List<String>)ViewState["ValueContainer"];
}
set {
ViewState["ValueContainer"] = value;
}
}
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
ValueContainer = new List<string>();
}
}
private void PopulateRepeater() {
rp1.DataSource = ValueContainer;
rp1.DataBind();
}
protected void lbAdd_Click(object sender, EventArgs e) {
ValueContainer.Add("");
rp1.DataSource = ValueContainer;
rp1.DataBind();
}
protected void rp1_ItemCommand(Object Sender, RepeaterCommandEventArgs e) {
ValueContainer.RemoveAt(e.Item.ItemIndex);
rp1.DataSource = ValueContainer;
rp1.DataBind();
}
Here is the markup
<asp:ScriptManager runat="server" ID="sm1" />
<asp:UpdatePanel runat="server" ID="up1">
<ContentTemplate>
<asp:Repeater runat="server" OnItemCommand="rp1_ItemCommand" ID="rp1">
<ItemTemplate>
<asp:TextBox runat="server" ID="myTextBox" /> <asp:LinkButton Text="Remove" runat="server" ID="lbRemove" />
</ItemTemplate>
</asp:Repeater>
<asp:LinkButton runat="server" ID="lbAdd" onclick="lbAdd_Click" Text="Add" />
</ContentTemplate>
</asp:UpdatePanel>
This is more lightweight version
<asp:HiddenField runat="server" ID="hfMyField" ClientIDMode="Static" />
<script type="text/javascript">
//<![CDATA[
function addTextBox() {
$("#myTextboxesContainer").append($("<input type='text' />").keyup(function () {
var Data = "";
$("#myTextboxesContainer input").each(function () {
Data += $(this).val() + ",";
});
$("#hfMyField").val(Data);
}));
}
//]]>
</script>
<div id="myTextboxesContainer">
</div>
Add textbox
The idea here is doing all dom manipulations using client script and storing everything in a hidden field. When the data is posted back you can retrive the value of the hidden field in a standard way i.e. hfMyField.Value. In this example it is CSV.

Is there any way to declaratively pass code-behind property values to server controls?

Can anyone explain why you can’t use inline code blocks within server control declarations in ASP.Net?
The following is a simple example...
....
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Text="<%= SomeProperty %>"></asp:Label>
</form>
....
The code block is rendered literally to the page...
<span id="Label1"><%= SomeProperty %></span>
My initial thoughts are it has to do with the order that these things are processed in the page life-cycle. The <%=...%> blocks are, as I understand it, equivalent to a Response.Write(...) in code-behind. And since the server control is not actually rendered as declared in the markup, I suppose it may not be possible to process an embedded code block before this rendering takes place.
I would be very grateful of anyone could explain that a little better.
However, the data binding code block <%#...%> is obviously different in the way it behaves, but can anyone tell me why it is possible to embed these within a server control...
....
<asp:Repeater id=Repeater1 runat="server">
....
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval(“SomeProperty”) %>'></asp:Label>
</ItemTemplate>
....
</asp:Repeater>
....
This works fine.
You're mostly right about the <%=...%> syntax.
Here is an example of what happens under the hood:
<script runat="server">
public string SomeProperty { get { return "Hello World!"; } }
</script>
<form id="form1" runat="server">
<%= SomeProperty %>
<div>
<asp:Label ID="Label1" runat="server" Text="<%= SomeProperty %>"></asp:Label>
</div>
</form>
This is parsed and the following C# code is created (I've simplified it a bit):
private Label #__BuildControlLabel1()
{
Label #__ctrl = new Label();
this.Label1 = #__ctrl;
#__ctrl.ApplyStyleSheetSkin(this);
#__ctrl.ID = "Label1";
#__ctrl.Text = "<%= SomeProperty %>";
return #__ctrl;
}
private void #__Renderform1(HtmlTextWriter #__w, Control parameterContainer)
{
#__w.Write( SomeProperty );
#__w.Write("\r\n <div>\r\n ");
parameterContainer.Controls[0].RenderControl(#__w);
#__w.Write("\r\n </div>\r\n ");
}
Here is an example of what happens under the hood for the <%#...%> syntax:
<script runat="server">
public string SomeProperty { get { return "Hello World!"; } }
protected void Page_Load(object sender, EventArgs e) { Label1.DataBind(); }
</script>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="<%# SomeProperty %>"></asp:Label>
</div>
</form>
Generates this code:
private Label #__BuildControlLabel1()
{
Label #__ctrl = new Label();
this.Label1 = #__ctrl;
#__ctrl.ApplyStyleSheetSkin(this);
#__ctrl.ID = "Label1";
#__ctrl.DataBinding += new System.EventHandler(this.#__DataBindingLabel1);
return #__ctrl;
}
public void #__DataBindingLabel1(object sender, EventArgs e)
{
Label dataBindingExpressionBuilderTarget = ((Label)(sender));
Page Container = ((Page)(dataBindingExpressionBuilderTarget.BindingContainer));
dataBindingExpressionBuilderTarget.Text = System.Convert.ToString( SomeProperty , System.Globalization.CultureInfo.CurrentCulture);
}
As you can see the <%=...%> syntax can be used outside of a server control's properties to directly render the returned value. On the other hand the <%#...%> syntax generates a event handler for the DataBinding event of the label. This event sets the value of the label's property to the value of SomeProperty. The DataBinding event fires whenever the DataBind method is called which is why I added that call to the Page_Load event.
Hopefully this will help you understand the difference between them.
You could create a custom ExpressionBuilder so you use something like <%$ Code: SomeProperty %>
You can create a custom databound control, e.g.
namespace FooBar.WebControls
{
public class DataBoundPlaceHolder:PlaceHolder
{
private bool hasDataBound = false;
protected override void CreateChildControls()
{
if (!hasDataBound)
{
this.DataBind();
hasDataBound = true;
}
base.CreateChildControls();
}
}
}
Then wrap your code in this new control, and use the <%# %> syntax, e.g.
<%# Register TagPrefix="WebControls" Namespace="FooBar.WebControls" Assembly="FooBar" %>
<form id="form1" runat="server">
<WebControls:DataBoundPlaceHolder runat="server">
<asp:Label ID="Label1" runat="server" Text='<%# SomeProperty %>'></asp:Label>
</WebControls:DataBoundPlaceHolder>
</form>

Get GridView selected row DataKey in Javascript

I have GridView which I can select a row. I then have a button above the grid called Edit which the user can click to popup a window and edit the selected row. So the button will have Javascript code behind it along the lines of
function editRecord()
{
var gridView = document.getElementById("<%= GridView.ClientID %>");
var id = // somehow get the id here ???
window.open("edit.aspx?id=" + id);
}
The question is how do I retrieve the selected records ID in javascript?
I worked it out based on JasonS response. What I did was create a hidden field in the Grid View like this:
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:HiddenField ID="hdID" runat="server" Value='<%# Eval("JobID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible="False">
<ItemTemplate>
<asp:LinkButton ID="lnkSelect" runat="server" CommandName="select" Text="Select" />
</ItemTemplate>
</asp:TemplateField>
Then on the OnRowDataBind have code to set the selected row
protected virtual void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Click to highlight row
Control lnkSelect = e.Row.FindControl("lnkSelect");
if (lnkSelect != null)
{
StringBuilder click = new StringBuilder();
click.AppendLine(m_View.Page.ClientScript.GetPostBackClientHyperlink(lnkSelect, String.Empty));
click.AppendLine(String.Format("onGridViewRowSelected('{0}')", e.Row.RowIndex));
e.Row.Attributes.Add("onclick", click.ToString());
}
}
}
And then in the Javascript I have code like this
<script type="text/javascript">
var selectedRowIndex = null;
function onGridViewRowSelected(rowIndex)
{
selectedRowIndex = rowIndex;
}
function editItem()
{
if (selectedRowIndex == null) return;
var gridView = document.getElementById('<%= GridView1.ClientID %>');
var cell = gridView.rows[parseInt(selectedRowIndex)+1].cells[0];
var hidID = cell.childNodes[0];
window.open('JobTypeEdit.aspx?id=' + hidID.value);
}
</script>
Works a treat :-)
1) change your javascript function to use a parameter
function editRecord(clientId)
{ ....
2) output the call in your editRecord button... if you want to avoid dealing with the .net generated ids, just use a simple
<input type="button" onclick="editRecord(your-rows-client-id-goes-here)" />
Based off of your comments to #DaveK's response, in javascript you can set the id of a hidden field to the clientId of the selected row when the user selects it. Then have your editRecord function use the value set on the hidden form field.
one could avoid javascript altogether, by setting anchor tags pre-populated with the query string for each row (although this will effect your table layout, it will need only one click rather than 2 from the user)
insert in the gridview template:
<asp:HyperLink runat="server" ID="editLink" Target="_blank"
NavigateURL='<%# Eval("JobID","edit.aspx?id={0}") %>'>
Edit..
</asp:HyperLink>

Resources