Reaching to control bychanged value in Asp.net repeater? - c#

I have an interesting question. I have a repeater on my page:
<asp:Repeater runat="server" ID="rpt" OnItemDataBound="rpt_ItemDataBound">
<ItemTemplate>
<asp:Label runat="server" ID="lblRptKey" Text='<%#Eval("ID")%>' Visible="false"></asp:Label>
<asp:HiddenField runat="server" ID="Hidden1" ClientIDMode="Static" />
<div class="form-group">
<label class="control-label col-md-3"><%# DataBinder.Eval(Container.DataItem, "Name") %></label>
<div class="col-md-9">
<div class="media">
<asp:Label runat="server" ID="ex1SliderVal" CssClass="pull-right" Font-Bold="true">5</asp:Label>
<div class="media-body">
<asp:TextBox runat="server" ID="ex1" type="text" data-slider-min="0" data-slider-max="10" data-slider-step="1" data-slider-value="5" data-slider-handle="square" />
</div>
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
and I am changing IDs of some controls in ItemDataBound event of repeater, which is necessary for my javascript functions. They should be different from eachother.
protected void rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var input = e.Item.FindControl("ex1");
input.ClientIDMode = ClientIDMode.Static;
input.ID = "ex" + (e.Item.ItemIndex + 1).ToString();
var label = e.Item.FindControl("ex1SliderVal");
label.ClientIDMode = ClientIDMode.Static;
label.ID = "ex" + (e.Item.ItemIndex + 1).ToString() + "SliderVal";
var hidden = e.Item.FindControl("Hidden1");
hidden.ID = "Hidden" + (e.Item.ItemIndex + 1).ToString();
}
Here is the question part. I cant reach the HiddenFields' values by IDs which I changed before.
protected void btnSave_Click(object sender, EventArgs e)
{
NHibernateDaoFactory DaoFactory=new NHibernateDaoFactory();
SportType_User stu = new SportType_User();
stu.User = loginUser;
stu.SportType=DaoFactory.GetSportTypeDao().GetById(Convert.ToInt32(lblKey.Text),false);
foreach (RepeaterItem item in rpt.Items)
{
Label lblRptKey = (Label)item.FindControl("lblRptKey");
int ProfessionId=Convert.ToInt32(lblRptKey.Text);
Profession profession = DaoFactory.GetProfessionDao().GetById(ProfessionId,false);
HiddenField hidden = (HiddenField)item.FindControl("Hidden"+(item.ItemIndex+1).ToString());//This is returning right for first. But then it is returning null
int val = Convert.ToInt32(hidden.Value);
val = val > 10 ? 10 : (val < 0 ? 0 : val);
ProfessionValue pv = new ProfessionValue();
pv.Profession = profession;
pv.Value = val;
stu.ProfessionValues.Add(pv);
}
stu.SelfValued = true;
DaoFactory.GetSportType_UserDao().Save(stu);
Response.Redirect("EditSports.aspx");
}
Hidden field in the method above is returning right for first item but then it is returning null

Related

Show all the values of selected items in a Text Box and find the Average of these values

Yes I tried using this operator technique, but On selecting 2 items from list box its giving me the sum of 3 or more items, Please let me know if the picture is visible to you..
Label1.Text = "";
foreach (int i in ListBox2.GetSelectedIndices()) {
Label1.Text += ListBox2.Items[i].Text + ",";
TextBox2.Text += ListBox2.Items[i] + "+";
}
Ok, I don't have your data, but lets just do this with say "id", and the Hotelname.
So, say this markup
<div style="float:left">
<asp:Listbox ID="LBHotels" runat="server"
Width="200px"
AutoPostBack="True"
OnSelectedIndexChanged="LBHotels_SelectedIndexChanged"
DataValueField="ID"
DataTextField="HotelName" Height="182px" SelectionMode="Multiple" >
</asp:Listbox>
</div>
<div style="float: left;margin-left:20px">
<h3>Occurance</h3>
<asp:TextBox ID="txtOccr" runat="server" Width="220px"></asp:TextBox>
</div>
<div style="float:left;margin-left:20px">
<h3>Results</h3>
<div style="text-align:right">
Total: <asp:TextBox ID="txtTotal" runat="server" TextMode="Number"></asp:TextBox><br />
Avg: <asp:TextBox ID="txtAvg" runat="server" TextMode="Number"></asp:TextBox>
</div>
</div>
(used div's, just float them left against each other - a nice easy way to place things around on a web form).
Ok, then this code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string strSQL =
"SELECT ID, HotelName FROM tblHotelsA ORDER BY HotelName";
SqlCommand cmdSQL = new SqlCommand(strSQL);
LBHotels.DataSource = MyRstP(cmdSQL);
LBHotels.DataBind();
}
}
And I did set auto-postback for the list box.
So, this code:
protected void LBHotels_SelectedIndexChanged(object sender, EventArgs e)
{
string sValues = ""; // string list of values for display into text box
int intTotal = 0; // total value
int[] Choices = LBHotels.GetSelectedIndices();
for (int i = 0; i < Choices.Length;i++)
{
ListItem MyChoice = LBHotels.Items[Choices[i]];
if (sValues != "")
sValues += "+";
sValues += MyChoice.Value;
intTotal += Convert.ToInt32(MyChoice.Value);
}
txtOccr.Text = sValues;
txtTotal.Text = intTotal.ToString();
txtAvg.Text = "0";
if (intTotal > 0)
txtAvg.Text =
String.Format("{0:0.####}", (decimal)intTotal / Choices.Length);
}
And the result is now this:
:

Dynamic TextBox TextChanged is not firing in UpdatePanel

My dynamic textboxes TextChanged event is working properly without using UpdatePanel, but when i use UpdatePanel it stops working. it works only when Button is clicked and when the LinkButton is clicked.
How can i set TextChanged event of dynamic textboxes as trigger for the UpdatePanel. I hope this is clear for you.
This is my aspx
<form id="form1" runat="server" enctype="multipart/form-data">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Name :"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:Label ID="Label2" runat="server" Text="Age :"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<asp:Label ID="Label3" runat="server" Text="Phones :"></asp:Label>
<br />
<asp:Panel ID="pnlTextBox" runat="server">
</asp:Panel>
<asp:LinkButton ID="btnAddTxt" runat="server" OnClick="btnAddTxt_Click">Add TextBox</asp:LinkButton>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="save" OnClick="Button1_Click" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="Button1" />
</Triggers>
</asp:UpdatePanel>
</form>
and this is code behind
protected void Page_PreInit(object sender, EventArgs e)
{
//Recreate Controls
RecreateControls("txtDynamic", "TextBox");
}
protected void btnAddTxt_Click(object sender, EventArgs e)
{
int cnt = FindOccurence("txtDynamic");
CreateTextBox("txtDynamic-" + Convert.ToString(cnt + 1));
}
private int FindOccurence(string substr)
{
string reqstr = Request.Form.ToString();
return ((reqstr.Length - reqstr.Replace(substr, "").Length) / substr.Length);
}
private void RecreateControls(string ctrlPrefix, string ctrlType)
{
string[] ctrls = Request.Form.ToString().Split('&');
int cnt = FindOccurence(ctrlPrefix);
if (cnt > 0)
{
for (int k = 1; k <= cnt; k++)
{
for (int i = 0; i < ctrls.Length; i++)
{
if (ctrls[i].Contains(ctrlPrefix + "-" + k.ToString()) && !ctrls[i].Contains("EVENTTARGET"))
{
string ctrlID = ctrls[i].Split('=')[0];
if (ctrlType == "TextBox")
{
CreateTextBox(ctrlID);
}
break;
}
}
}
}
}
private void CreateTextBox(string ID)
{
TextBox txt = new TextBox();
txt.ID = ID;
txt.AutoPostBack = true;
txt.TextChanged += new EventHandler(OnTextChanged);
pnlTextBox.Controls.Add(txt);
Literal lt = new Literal();
lt.Text = "<br /><br />";
pnlTextBox.Controls.Add(lt);
}
protected void OnTextChanged(object sender, EventArgs e)
{
TextBox txt = (TextBox)sender;
string ID = txt.ID;
//Place the functionality here
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('" + ID + " fired OnTextChanged event')", true);
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox txtDynamic1 = (TextBox)this.form1.FindControl("txtDynamic-1");
TextBox txtDynamic2 = (TextBox)this.form1.FindControl("txtDynamic-2");
Response.Write(txtDynamic1.Text + " & " + txtDynamic2.Text);
}
You can refer to this URL and add the postback trigger from the code behind instead of the aspx. https://forums.asp.net/t/1124967.aspx?Adding+a+Trigger+to+an+UpdatePanel+in+code+behind

How to set 3 radiobutton with its groupname in a repeater

I need to set 3 different groups of radio button in a repeater. Using groupname property for it wasn't enough. So, after researching, I use a bit of JS and it works. My problem is when I want to implement more than one group of radiobuttons. Can anyone help me?
My best approach is:
CSHTML
<asp:Repeater runat="server" ID="repeaterImages" OnItemDataBound="repeaterImages_ItemDataBound">
<ItemTemplate>
<span>
<asp:RadioButton runat="server" ID="rbLogoSeleccionado" Text='Logo 0' GroupName="nombreLogo" /><br />
<asp:RadioButton runat="server" ID="rbLogoSeleccionadoApp" Text='Logo 1' GroupName="nombreLogoApp" /><br />
<asp:RadioButton runat="server" ID="rbLogoSeleccionadoAppBlanco" Text='Logo 2' GroupName="nombreLogoAppBlanco" />
</span>
</ItemTemplate>
</asp:Repeater>
JS
<script>
function SetUniqueRadioButton(nameregex, current) {
for (i = 0; i < document.forms[0].elements.length; i++) {
elm = document.forms[0].elements[i]
if (elm.type == 'radio') {
elm.checked = false;
}
}
current.checked = true;
}
</script>
CS
protected void repeaterImages_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
try
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
RadioButton rbLogoSeleccionado = (RadioButton)e.Item.FindControl("rbLogoSeleccionado");
RadioButton rbLogoSeleccionadoApp = (RadioButton)e.Item.FindControl("rbLogoSeleccionadoApp");
RadioButton rbLogoSeleccionadoAppBlanco = (RadioButton)e.Item.FindControl("rbLogoSeleccionadoAppBlanco");
string script = "SetUniqueRadioButton('repeaterImages.*nombreLogo',this)";
string scriptApp = "SetUniqueRadioButton('repeaterImages.*nombreLogoApp',this)";
string scriptAppBlanco = "SetUniqueRadioButton('repeaterImages.*nombreLogoAppBlanco',this)";
rbLogoSeleccionado.Attributes.Add("onclick", script);
rbLogoSeleccionadoApp.Attributes.Add("onclick", scriptApp);
rbLogoSeleccionadoAppBlanco.Attributes.Add("onclick", scriptAppBlanco);
}
}
catch (Exception ex)
{
PIPEvo.Log.Log.RegistrarError(ex);
throw;
}
}
With this code just getting 3 rows of radiobutton, sharing groupname behavior for all of them... (I want groupname behavior per row...)
Piece of cake. Prove how newie I am in JS. I am posting the solution because is a recurrent issue in asp programming and this bug is known. Beside I cant find the solution for some radio button.
JS.
<script>
function SetUniqueRadioButton(text, current) {
for (i = 0; i < document.forms[0].elements.length; i++) {
elm = document.forms[0].elements[i]
if ((elm.type == 'radio') && (elm.value == text)) {
elm.checked = false;
}
}
current.checked = true;
}
</script>
CS
protected void repeaterImages_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
try
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
RadioButton rbLogoSeleccionado = (RadioButton)e.Item.FindControl("rbLogoSeleccionado");
RadioButton rbLogoSeleccionadoApp = (RadioButton)e.Item.FindControl("rbLogoSeleccionadoApp");
RadioButton rbLogoSeleccionadoAppBlanco = (RadioButton)e.Item.FindControl("rbLogoSeleccionadoAppBlanco");
string script = "SetUniqueRadioButton('rbLogoSeleccionado',this)";
string scriptApp = "SetUniqueRadioButton('rbLogoSeleccionadoApp',this)";
string scriptAppBlanco = "SetUniqueRadioButton('rbLogoSeleccionadoAppBlanco',this)";
rbLogoSeleccionado.Attributes.Add("onclick", script);
rbLogoSeleccionadoApp.Attributes.Add("onclick", scriptApp);
rbLogoSeleccionadoAppBlanco.Attributes.Add("onclick", scriptAppBlanco);
}
}
catch (Exception ex)
{
PIPEvo.Log.Log.RegistrarError(ex);
throw;
}
}
CSHTML
<asp:Repeater runat="server" ID="repeaterImages" OnItemDataBound="repeaterImages_ItemDataBound">
<ItemTemplate>
<span>
<asp:RadioButton runat="server" ID="rbLogoSeleccionado" Text='Logo 0' GroupName="nombreLogo" /><br />
<asp:RadioButton runat="server" ID="rbLogoSeleccionadoApp" Text='Logo 1' GroupName="nombreLogoApp" /><br />
<asp:RadioButton runat="server" ID="rbLogoSeleccionadoAppBlanco" Text='Logo 2' GroupName="nombreLogoAppBlanco" />
</span>
</ItemTemplate>
</asp:Repeater>

Looping through repeater items

I have a repeater which is built like the following:
<asp:Repeater runat="server" ID="rptItems" OnItemDataBound="rptItems_ItemDataBound">
<ItemTemplate>
<div class="span12 grey-box">
<div class="hero-block3">
<div class="row show-grid">
<div class="span9">
<div class="hero-content-3">
<h2><asp:Literal ID="ltrName" runat="server"></asp:Literal></h2>
<p><asp:Literal ID="ltrDescription" runat="server"></asp:Literal></p>
</div>
</div>
<div class="span3">
<asp:Panel ID="pnlAmount" runat="server">
<div class="tour-btn" id="divAmount" runat="server">
<small>How Many?<br /></small>
<asp:TextBox runat="server" ID="tbox" Width="40"></asp:TextBox>
</div>
</asp:Panel>
</div>
</div>
</div>
</div>
<div class="clear-both"></div>
<br />
</ItemTemplate>
</asp:Repeater>
It's bound using:
ListProducts = db.GetDataTable("select * from Products where Id in (" + selectedValues + ")");
rptItems.DataSource = ListProducts;
rptItems.DataBind();
And then extra stuff is done with:
protected void rptItems_ItemDataBound(object sender,
System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
DataRowView nRow = null;
switch (e.Item.ItemType)
{
case ListItemType.Item:
case ListItemType.AlternatingItem:
nRow = (DataRowView)e.Item.DataItem;
((Literal)e.Item.FindControl("ltrDescription")).Text = "" + nRow["Description"];
((Literal)e.Item.FindControl("ltrName")).Text = "" + nRow["Name"];
if ("" + nRow["HasAmount"] == "False")
{
((Panel)e.Item.FindControl("pnlAmount")).Visible = false;
}
break;
}
}
However, now on an onclick event for the page, i'm trying to save the information stored - This is what i've done so far, but it always all seems to be null, and I can't add a .text etc to the end of the (TextBox)item.FindControl("tbSelected");
Heres my loop i'm trying on click:
protected void doStageThree(object sender, EventArgs e)
{
foreach (RepeaterItem item in rptItems.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
var tbSelected = (TextBox)item.FindControl("tbSelected");
var lblDescription = (Literal)item.FindControl("ltrDescription");
var lblName = (Literal)item.FindControl("ltrName");
}
}
}
It is always null because there is no TextBox with id tbSelected
<asp:TextBox runat="server" ID="tbox" Width="40"></asp:TextBox>
change it to:
var tbSelected = (TextBox)item.FindControl("tbox");
To protect your code from null use keyword as:
var tbSelected = item.FindControl("tbox") as TextBox;
if (tbSelected != null)
{
//textbox with id tbox exists
tbSelected.Text = "your text";
}
Try replacing
foreach (RepeaterItem item in rptItems.Items)
with
foreach (Control c in rptItems.Items)
{
if(c.FindControl("tbSelected") != null)
{
var selectedText = ((TextBox)c.FindControl("tbSelected")).Text;
}
}

Request.Form giving extra values from Dynamic Textboxes

i am working with dynamic TextBoxes and then Getting their Values in code behind file. I am creating these boxes using Javascript. my asp.net page code is
<script type="text/javascript">
$(document).ready(function () {
var counter = 1;
$("#addButton").click(function () {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.html('<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
return false;
});
});
</script>
</head>
<body>
<form id="form2" runat="server">
<h1>jQuery add / remove textbox example</h1>
<asp:TextBox runat="server" ID="txt1" type='text' name="textname" />
<asp:Panel runat="server" ID='TextBoxesGroup'>
</asp:Panel>
<asp:LinkButton ID="addButton" runat="server">Add TextBox</asp:LinkButton>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</body>
i have one Textbox shown on the page, which should shows only one values when no dynamic Textbox is created. My C# code is
protected void Button1_Click(object sender, EventArgs e)
{
string name = txt1.Text + ",";
if (TextBoxesGroup.Controls.Count > 0)
{
for (int i = 1; i <= TextBoxesGroup.Controls.Count; i++)
{
name += Request.Form["textbox" + i] + ",";
}
}
Label1.Text = name;
}
on asp:button click it should display all the values separated by (,). but it is only showing top 2 values, one of which is asp:Textbox and second is dynamic Textbox,, i want the values of all the Textboxes created dynamically, and when no dynamic textbox is added it should only show the value from asp:textBox... Thanks in Advance
Html input elements created through javascript on the client, are not going to be in TextBoxesGroup.Controls on the server.
Changes in the client DOM structure have no effect on the Page's Control tree. The only thing affected will be the content of HttpRequest during postback. One way to know how many dynamically created input elements contributed to Request.Form data is to pass this information as part of the request. This is why you will have to go with the hidden field suggestion. The hidden field value will bring back the count of client-side inputs. You have to set it in javascript every time you create a new input, read it in server-side code, convert to integer and use in your for loop.
Add
<asp:HiddenField runat="server" ID="txtDynamicCount" value="0" />
to the the markup inside form tag.
In javascript click event after counter++; line add
$("#txtDynamicCount").val(counter);
In Button1_Click:
int count;
if (!int.TryParse(txtDynamicCount.Value, out count))
count = 0;
for (int i = 1; i <= count; i++)
{
...
}
The important difference from the other answer is that textboxes (input elements) will not persist between form submits.
You cannot populate server controls in client side. Instead, you want to populate them from server. Here is the sample -
<asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>
<asp:LinkButton ID="addButton" runat="server" OnClick="btnAdd_Click">Add TextBox</asp:LinkButton>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /><br/>
Posted Results: <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
private List<int> _controlIds;
private List<int> ControlIds
{
get
{
if (_controlIds == null)
{
if (ViewState["ControlIds"] != null)
_controlIds = (List<int>)ViewState["ControlIds"];
else
_controlIds = new List<int>();
}
return _controlIds;
}
set { ViewState["ControlIds"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
foreach (int id in ControlIds)
{
var textbox = new TextBox();
textbox.ID = id.ToString();
PlaceHolder1.Controls.Add(textbox);
}
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
var reqs = ControlIds;
int id = ControlIds.Count + 1;
reqs.Add(id);
ControlIds = reqs;
var textbox = new TextBox();
textbox.ID = id.ToString();
PlaceHolder1.Controls.Add(textbox);
}
protected void Button1_Click(object sender, EventArgs e)
{
var ids = ControlIds;
foreach (var id in ids)
{
var textbox = (TextBox)PlaceHolder1.FindControl(id.ToString());
Label1.Text += textbox.Text + ", ";
}
}

Categories

Resources