ClientSideEvents on ASP:Net repeater control - c#

I'm creating a textbox control in a repeater. Here is .cs code:
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Est estimationItem = (Est)e.Item.DataItem;
TextBox txtWeekly = (TextBox)e.Item.FindControl("txtWeekly");
txtWeekly.Text = estimationItem.SMEst.ToString();
}
And here is .aspx code:
<asp:Repeater ID="WeeklyEst" OnItemDataBound="WeeklyEst_ItemDataBound" runat="server">
<HeaderTemplate>
<table>
<tr>
</HeaderTemplate>
<ItemTemplate>
<td>
<asp:TextBox ID="txtWeekly" runat="server">
<ClientSideEvents OnTextChanged="function(s, e) { alert('AlertIsHere!');}" />
</asp:TextBox>
</td>
</ItemTemplate>
<FooterTemplate>
<td>
</td>
</tr>
</table>
</FooterTemplate>
</asp:Repeater>
I want to do is firing an alert when text changed on text box. How can I do this? CliendSideEvent fire on another textbox but in repeater control, it doesn't work.

Use the ItemDataBound event of Repeater control, you can do this like..., if i understood you correctly
protected void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if(e.Item.ItemType == ListItemType.Item)
{
TextBox mytxt = e.Item.FindControl("txtWeekly") as TextBox;
// you can just pass "this" instead of "mytxt.ClientID" and get the ID from the DOM element
mytxt.Attributes.Add("onchange", "doStuff('" + mytxt.ClientID + "');");
}
}

if you donot want to do this in codebehind then you can use jquery ,it would be lot easier
$('.txtbox').change(function() {
alert($(this).val());
});
just give cssclass 'txtbox' to your textbox.

What about this unobtrusive approach
<head runat="server">
<title></title>
<script type="text/javascript" src="js/jquery-1.7.1.js" ></script>
<script type="text/javascript">
$(document).ready(function () {
// select all input text ending with txtWeekly as repeater control
// will create something like rptWeeklyEst$ctl00$txtWeekly
$('input[name$="txtWeekly"][type=text]').change(function () {
alert('textbox changed to ' + $(this).val());
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="rptWeeklyEst" runat="server">
<ItemTemplate>
<asp:TextBox ID="txtWeekly" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:Repeater>
<br />
Nope
<asp:TextBox ID="txtNope" runat="server"></asp:TextBox>
</div>
</form>
</body>

Related

Dropdownlist inside Updatepanel not passing selected item

I have a Gridview that has a hide/show panel. Inside the Panel there is a dropdown and a button. On button press I need the selected value of the dropdown, but I keep getting the first item, no matted what is selected.
I have been investigating the issue and it is to do with the panel control. If I place the dropdown outside the panel, everything works as intended. But dropdown only passes the first value when inside the panel.
Here is my code:
ASP Code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="DD.aspx.cs" Inherits="DD" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<title></title>
<script type="text/javascript">
$(document).on("click", '[src*=plus]', function () {
$(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
$(this).attr("src", "images/minus.png");
});
$(document).on("click", '[src*=minus]', function () {
$(this).attr("src", "images/plus.png");
$(this).closest("tr").next().remove();
})
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server"></asp:ScriptManager>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:constr %>" SelectCommand="SELECT * FROM [Requests]"></asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:constr %>" SelectCommand="SELECT [Name] FROM [Staff]"></asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="RequestID" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="RequestID" HeaderText="RequestID" InsertVisible="False" ReadOnly="True" SortExpression="RequestID" />
<asp:TemplateField>
<ItemTemplate>
<img runat="server" style="cursor: pointer" src="images/plus.png" />
<asp:UpdatePanel ID="pnlOrders" runat="server" Style="display: none" UpdateMode="Conditional">
<ContentTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource2" DataTextField="Name" DataValueField="Name" AutoPostBack="true">
</asp:DropDownList>
<asp:Button runat="server" ID="test" OnClick="test_Click" />
</ContentTemplate> </asp:UpdatePanel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
</body>
</html>
C# Code
protected void test_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
DropDownList referalDD = gvr.FindControl("DD1") as DropDownList;
string www = referalDD.SelectedItem.Text;
string qqq = referalDD.SelectedItem.Value;
}
Can anyone help me to solve this issue
Ok so I have found a work around / solution. Thanks to Niko for the placeholder suggestion. I got rid of this code:
<img runat="server" style="cursor: pointer" src="images/plus.png" />
and the related Jquery
$(document).on("click", '[src*=plus]', function () {
$(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
$(this).attr("src", "images/minus.png");
});
$(document).on("click", '[src*=minus]', function () {
$(this).attr("src", "images/plus.png");
$(this).closest("tr").next().remove();
})
Added a placeholder around the updatepanel and a Image button
<asp:ImageButton runat="server" ID="ShowHide" ImageUrl="~/images/plus.png" OnClick="ShowHide_Click" />
<asp:PlaceHolder ID="PlaceHolder1" runat="server" Visible="false">
And this code for the button click event.
protected void ShowHide_Click(object sender, EventArgs e)
{
ImageButton btn = (ImageButton)sender;
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
PlaceHolder ph = gvr.FindControl("PlaceHolder1") as PlaceHolder;
if (btn.ImageUrl.ToString() == "~/images/plus.png")
{
ph.Visible = true;
btn.ImageUrl = "~/images/minus.png";
}
else
{
ph.Visible = false;
btn.ImageUrl = "~/images/plus.png";
}
}
Note: After further testing the whole issue was to do with UpdatePanel having this code Style="display: none" As soon as I removed this, everything worked. But I added the placeholder for by show/Hide feature.

how to find checkbox where checked in repeater in asp.net?

i want when click btndelete , every checkbox where chechek in repeater1 to get value of column(titr) in same row, but i dont find which checkbox checked and dont access to value of column(titr)
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<table>
<tr>
<td> </td>
<td>subject</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:CheckBox ID="CheckBox1" runat="server" />
</td>
<td id="checkvalue" >
<%# Eval("titr") %>
</td>
</tr>
</ItemTemplate>
<FooterTemplate></table></FooterTemplate>
</asp:Repeater>
<asp:Button ID="btndelete" runat="server" Text="delete" OnClick="btndelete_Click" />
.cs code is :
protected void btndelete_Click(object sender, EventArgs e)
{
}
You could get a list of repeaterItems for each row in which the checkbox is checked using linq such that:
List<RepeaterItem> selectedItems = Repeater1.Items.Cast<RepeaterItem>().Where(x => ((CheckBox)x.FindControl("CheckBox1"))
.Checked).ToList();
You could then iterate through the list and get the value of titr for each of the selected rows, but you would have to set some server control equal to "titr" when you bind the control, like:
<asp:literal id="literal1" runat="server"><%# Eval("titr") %></asp:literal>
That way you could go find the value later when you iterate through the list, like this:
List<string> titrValues = selectedItems.Select(t => ((Literal)t.FindControl("literal1).Text));
You may have to do some tweaking, but that should get you the values of titr for each row with a selected value.
Aspx Code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:Repeater ID="Repeater1" runat="server" >
<ItemTemplate>
<div>
<asp:CheckBox ID="CategoryID" runat="server" Text='<%# Eval("val") %>' />
</div>
</ItemTemplate>
</asp:Repeater>
<asp:Button Text="Click" OnClick="Button2_Click" runat="server" />
</form>
</body>
</html>
CS Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add("val", typeof(string));
for (int i = 0; i < 10; i++)
dt.Rows.Add("testing" + i.ToString());
Repeater1.DataSource = dt;
Repeater1.DataBind();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
string Rpt = "Repeater Items Checked:<br />";
for (int i = 0; i < Repeater1.Items.Count; i++)
{
CheckBox chk = (CheckBox)Repeater1.Items[i].FindControl("CategoryID");
if (chk.Checked)
{
Rpt += (chk.Text + "<br />");
}
}
Response.Write(Rpt);
}
You can also use break point to check the get values....
Refrenced By: http://www.codeproject.com/Questions/534719/GetplusSelectedplusCheckboxesplusinplusASPplusRepe

Only allow one checkbox to be selected in gridview within modalpopup

I have a modal popup that has a gridview, this gridview has a number of rows, I only want the user to be able to select one row. So if they select another it will deselect the previous one.
I have tried a number of methods but can't get the oncheckedchanged event to fire.
Please can someone assist
Cheers
<asp:button id="btnShowPopupOW" style="display: none" runat="server" />
<asp:modalpopupextender id="mpeOW" behaviorid="mpeOW" runat="server" targetcontrolid="btnShowPopupOW"
popupcontrolid="pnlpopupOW" cancelcontrolid="imgOWCancel" backgroundcssclass="modalBackground" />
<asp:panel id="pnlpopupOW" runat="server" width="600px" style="display: none;" class="ModalPanel">
<div style="position: relative; min-height: 490px;">
<asp:UpdatePanel ID="upExisting" runat="server" ChildrenAsTriggers="true">
<ContentTemplate>
<table style="width: 600px;">
<tr height="25px">
<td>
<asp:Panel ID="pnlPrev" runat="server" Height="200px" ScrollBars="Auto" HorizontalAlign="Center">
<asp:GridView ID="grdPrevious" runat="server" ClientIDMode="Static" AutoGenerateColumns="false" Width="100%"
ShowFooter="false" ShowHeaderWhenEmpty="false" DataKeyNames="ID" >
<Columns>
<asp:BoundField DataField="dates" HeaderText="Dates" />
<asp:BoundField DataField="Prev" HeaderText="Previous" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="ChkSelect" runat="server" OnCheckedChanged="ChkSelect_OnCheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
</td>
</tr>
</table>
</ContentTemplate>
<Triggers>
</Triggers>
</asp:UpdatePanel>
</div>
</asp:panel>
with the following in the codebehind
protected void ChkSelect_OnCheckedChanged(object sender, EventArgs e)
{
CheckBox activeCheckBox = sender as CheckBox;
foreach (GridViewRow rw in grdPrevious.Rows)
{
CheckBox chkBx = (CheckBox)rw.FindControl("ChkSelect");
if (chkBx != activeCheckBox)
{
chkBx.Checked = false;
}
else
{
chkBx.Checked = true;
}
}
}
You can do it like this. With single check box selection using jquery....
<ItemTemplate>
<asp:CheckBox ID="ChkSelect" runat="server" onclick="CheckOne(this)" />
</ItemTemplate>
function CheckOne(obj) {
var grid = obj.parentNode.parentNode.parentNode;
var inputs = grid.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox") {
if (obj.checked && inputs[i] != obj && inputs[i].checked) {
inputs[i].checked = false;
}
}
}
}
you want to a single checked in check box . i think Using this you will be able to select only one check box at a time. Put the following java script code in the head section of the web page
<script type="text/javascript">
function SingleCheckboxCheck(ob)
{
var gridvalue = ob.parentNode.parentNode.parentNode;
var inputs = gridvalue.getElementsByTagName("input");
for(var i=0;i<inputs.length;i++)
{
if (inputs[i].type =="checkbox")
{
if(ob.checked && inputs[i] != ob && inputs[i].checked)
{
inputs[i].checked = false;
}
}
}
}
</script>
Here checkbox as a TemplateField of the GridView inside just call the above javascript function to make it single checkable.
onclick ="SingleCheckboxCheck(this)"
What you need is probably a (RadioButton)[http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.radiobutton(v=vs.110).aspx] instead of a CheckBox.
You can group the RadioButton's together which then allows the user to only select one item and automatically deselects the previous selected - or: exactly the behavior you want for your application.
This example code is taken from the linked MSDN Documentation. Note the GroupName attribute
<%# Page Language="C#" AutoEventWireup="True" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>RadioButton Example</title>
<script language="C#" runat="server">
void SubmitBtn_Click(Object Sender, EventArgs e) {
if (Radio1.Checked) {
Label1.Text = "You selected " + Radio1.Text;
}
else if (Radio2.Checked) {
Label1.Text = "You selected " + Radio2.Text;
}
else if (Radio3.Checked) {
Label1.Text = "You selected " + Radio3.Text;
}
}
</script>
</head>
<body>
<h3>RadioButton Example</h3>
<form id="form1" runat="server">
<h4>Select the type of installation you want to perform:</h4>
<asp:RadioButton id="Radio1" Text="Typical" Checked="True" GroupName="RadioGroup1" runat="server" />
<br />
This option installs the features most typically used. <i>Requires 1.2 MB disk space.</i><br />
<asp:RadioButton id="Radio2" Text="Compact" GroupName="RadioGroup1" runat="server"/>
<br />
This option installs the minimum files required to run the product. <i>Requires 350 KB disk space.</i>
<br />
<asp:RadioButton id="Radio3" runat="server" Text="Full" GroupName="RadioGroup1" />
<br />
This option installs all features for the product. <i>Requires 4.3 MB disk space.</i>
<br />
<asp:button text="Submit" OnClick="SubmitBtn_Click" runat="server"/>
<asp:Label id="Label1" font-bold="true" runat="server" />
</form>

Loading content around TextBoxes in ASP.NET

I'm trying to create a form in ASP.NET but I'd like to know if I can dynamically add HTML content around a TextBox.
Here is the code:
<%# Page Title="" Language="C#" MasterPageFile="~/MPpacientes.master" AutoEventWireup="true" CodeFile="CuestionarioGeneral.aspx.cs" Inherits="CuestionarioGeneral" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="navbar" Runat="Server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="headertitle" Runat="Server">
Cuestionario General
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="contentbox" Runat="Server">
<legend>Lorem ipsum dolor sia met etcetcetc</legend>
<%-- question1 --%>
<asp:Label ID="lbl1" runat="server" Text="1"></asp:Label>
<div class="input-control text" data-role="input-control">
<asp:TextBox ID="txt1" runat="server"></asp:TextBox>
<button class="btn-clear" tabindex="-1"></button>
</div>
<%-- question2 --%>
<asp:Label ID="lbl2" runat="server" Text="2"></asp:Label>
<div class="input-control text" data-role="input-control">
<asp:TextBox ID="txt2" runat="server"></asp:TextBox>
<button class="btn-clear" tabindex="-1"></button>
</div>
<%-- question3 --%>
<%-- etc --%>
As you can see in the code, the content of the < div > and the < button > tags don't change at all in each question, so I wanna know if there's some way to load them from a script so that when the page loads they wrap around each TextBox automatically.
Thanks in advance.
did the total question for each page different or the same?
if different, you can try to use asp:Repeater for that. You can dynamically change the question, and keep the button and div static for every question.
for example :
<asp:Repeater ID="rptQuestion" runat="server" OnItemDataBound="rptQuestion_ItemDataBound">
<ItemTemplate>
<asp:Label ID="lblQuestion"></asp:Label>
<div class="input-control text" data-role="input-control">
<asp:TextBox ID="txtAnswer" runat="server"></asp:TextBox>
<asp:Button CssClass="btn-clear" TabIndex="-1" ID="btnClear" runat="server"></button>
</div>
</ItemTemplate>
</asp:Repeater>
Edit :
to edit the Label text, you can first add all your question to List<String> then Bind it to the repeater, here's the example :
on PageLoad :
protected void Page_Load(object sender, EventArgs e)
{
List<String> listQuestion = new List<String>();
foreach(string question in ...)
{
listQuestion.Add(question);
}
rptQuestion.DataSource = listQuestion;
rptQuestion.DataBind();
}
then on the ItemDataBound event :
protected void rptQuestion_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
String question = (String)e.Item.DataItem;
Label lblQuestion = (Label)e.Item.FindControl("lblQuestion");
lblQuestion.Text = question;
}
}
you don't need to change the ID for the Label and TextBox, because it will always be different for each item in the repeater
If you just need to add a question, you can a <asp:label /> tag, or even a Html label tag and make it runat="server".
And then you can add the text to the label dynamically in the code behind

ItemCommand of Repeater is not fire with LinkButton

I have a Linkbutton inside a repeater and I want to delete the Item when the user clicks on the Linkbutton; in this case the LinkButton's ItemCommand event is not fired, my code is below:
<asp:Repeater ID="rptSubject" runat="server" OnItemCommand="rptSubject_OnItemCommand">
<ItemTemplate>
<tr>
<td><asp:CheckBox id="chkAll" runat="server"/></td>
<td><%#Eval("SubjectName") %></td>
<td>
<asp:ImageButton ID="imgbtnDelete" ImageUrl="~/assets/images/icons/delete.png" runat="server" CommandName="Delete" CommandArgument='<%#Eval("SubjectID") %>'/>
<asp:LinkButton ID="lnkEditCategory" runat="server" CommandName="EditCategory" CommandArgument='<%#Eval("SubjectID") %>' Text="Edit Category"></asp:LinkButton>
</td>
</tr>
</ItemTemplate>
my repeater's itemcommand event handler is:
protected void rptSubject_OnItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName.Equals("Delete"))
{
// some code
}
if (e.CommandName.Equals("EditCategory"))
{
// some code
}
}
when I click on the image button my item command event fires but when I click on the link button it doesn't.
The following code works for me:
<%# Page Language="C#" %>
<script type="text/c#" runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var data = new[]
{
new
{
SubjectID = "1",
SubjectName = "subject name 1"
},
new
{
SubjectID = "2",
SubjectName = "subject name 2"
},
};
rptSubject.DataSource = data;
rptSubject.DataBind();
}
}
protected void RptSubject_OnItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName.Equals("Delete"))
{
// some code
}
if (e.CommandName.Equals("EditCategory"))
{
// some code
}
}
</script>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form id="Form1" runat="server">
<asp:Repeater ID="rptSubject" runat="server" OnItemCommand="RptSubject_OnItemCommand">
<ItemTemplate>
<div>
<asp:CheckBox id="chkAll" runat="server"/>
<%#Eval("SubjectName") %>
<asp:LinkButton ID="imgbtnDelete" runat="server" CommandName="Delete" CommandArgument='<%#Eval("SubjectID") %>' Text="Delete" />
<asp:LinkButton ID="lnkEditCategory" runat="server" CommandName="EditCategory" CommandArgument='<%#Eval("SubjectID") %>' Text="Edit" />
</div>
</ItemTemplate>
</asp:Repeater>
</form>
</body>
</html>
You also need to make sure you bind to the repeater explicitly
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
AddHandler rptPages.ItemCommand, AddressOf rptPages_ItemCommand
End Sub

Categories

Resources