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;
}
}
Related
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:
:
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>
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
filldropdown(dllselection.SelectedValue);
Code.Enabled = true;
if(dllselection.SelectedValue=="")
{
Code.Enabled = false;
}
}
}
i think there something wrong with the page load,my 2nd dropdownlist is depend on 1st dropdownlist selection.
<div class="form-group">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label" style="color:black" >Main Category</label>
<div class="col-sm-3">
<asp:DropDownList ID="dllselection" runat="server" CssClass="form-control" AutoPostBack="true" required>
<asp:ListItem Text="Please Select" Value=""></asp:ListItem>
<asp:ListItem Text="HR" Value="M_1"></asp:ListItem>
<asp:ListItem Text="IT" Value="M_2"></asp:ListItem>
<asp:ListItem Text="Maintenance" Value="M_3"></asp:ListItem>
</asp:DropDownList>
</div>
</div>
<div class="form-group">
<label for="Training" style="color:black" class="col-sm-2 control-label">Sub Category</label>
<div class="col-sm-3">
<asp:DropDownList ID="Code" Enabled="false" onchange="javascript:return dropdown(this);" runat="server" CssClass="form-control" ValidationGroup="G1" required></asp:DropDownList>
</div>
</div>
everytime i submit pass data to database,the value for the 2nd dropdownlist always the 1st value.
public void filldropdown(string item)
{
int loggedUserID = Convert.ToInt32(Session["loggedUserID"]);
List<BOL.UserInfo> userslist = new UserInfos().List();
BOL.UserInfo loggeduser = userslist.Where(x => x.UserID == loggedUserID).FirstOrDefault();
// int ID = 10;
List<e_request> role = new e_requests().dropdownlistG(loggeduser.SUBSIDIARY_CD, item);
Code.DataSource = role;
Code.DataTextField = "CAT_DESC";
Code.DataValueField = "SUB_CAT";
Code.DataBind();
}
You can filling drop down on postback which you should not if you want to keep selection. use !Page.IsPostBack instead of Page.IsPostBack
Change
if (Page.IsPostBack)
{
To
if (!Page.IsPostBack)
{
On more thing you may need to put condition out side !Page.IsPostBack as you would need it to be executed on postback
if (!Page.IsPostBack)
{
filldropdown(dllselection.SelectedValue);
}
Code.Enabled = true;
if(dllselection.SelectedValue=="")
{
Code.Enabled = false;
}
Also note you may need to fill the second dropdown on SelectedIndexChange of dllselection and need to set AutoPostBack of dllselection true.
Try this:
if (!IsPostBack)
{
if (dllselection.SelectedValue == "")
{
Code.Enabled = false;
}
else
{
Code.Enabled = true;
filldropdown(dllselection.SelectedValue);
}
}
Try to Load Method in
if (!Page.IsPostBack)
{
filldropdown(dllselection.SelectedValue);
Code.Enabled = true;
if(dllselection.SelectedValue=="")
{
Code.Enabled = false;
}
}
Update:
you need to fill the second dropdown on SelectedIndexChange of dllselection and need to set AutoPostBack = true of dllselection .
<asp:DropDownList ID="logList" runat="server" AutoPostBack="True"
onselectedindexchanged="itemSelected">
</asp:DropDownList>
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack){
filldropdown(dllselection.SelectedValue);
Code.Enabled = true;
if(dllselection.SelectedValue=="")
{
Code.Enabled = false;
}
}
}
add OnSelectedIndexChanged="dllselection_SelectedIndexChanged" to my 1st dropdownlist.
protected void dllselection_SelectedIndexChanged(object sender, EventArgs e)
{
if (dllselection.SelectedIndex == 0)
{
Code.Enabled = false;
}
else
{
Code.Enabled = true;
//fill Code
filldropdown(dllselection.SelectedValue);
}
}
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
I am making a menu for a cafe. It shows the food and rinks items, the price and then I want a textbox, where people can write how much of each they want to buy, shown in a textbox. Then I want each textbox to have a unique ID based on the menu items ID.
This is my repeater:
<asp:Repeater ID="ParentRepeater" runat="server" OnItemDataBound="ParentRepeater_ItemDataBound">
<ItemTemplate>
<h2>
<%#DataBinder.Eval(Container.DataItem, "typenavn") %></h2>
<asp:HiddenField ID="HiddenField1" Value='<%# Eval("id") %>' runat="server" />
<asp:Repeater ID="ChildRepeater" runat="server">
<ItemTemplate>
<table>
<tr>
<td style="width: 400px">
<%#DataBinder.Eval(Container.DataItem, "productName") %>
</td>
<td style="width: 400px">
<%#DataBinder.Eval(Container.DataItem, "pris") %>
</td>
<td>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
And this is my code behind:
protected void ParentRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
RepeaterItem item = e.Item;
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
Repeater ChildRepeater = (Repeater)item.FindControl("ChildRepeater");
HiddenField hide = e.Item.FindControl("HiddenField1") as HiddenField;
int id = Convert.ToInt32(hide.Value);
var query = from es in gr.products
where es.typeID == id
select es;
List<product> list = new List<product>();
foreach (product pro in query)
{
list.Add(pro);
}
ChildRepeater.DataSource = list;
ChildRepeater.DataBind();
int h = 0;
foreach (RepeaterItem item1 in ChildRepeater.Items)
{
if (item1.ItemType == ListItemType.Item || item1.ItemType == ListItemType.AlternatingItem)
{
TextBox txt = (TextBox)item1.FindControl("TextBox1") as TextBox;
HiddenField hf = (HiddenField)item1.FindControl("HiddenField2") as HiddenField;
for (int i = 0; i < list.Count; i++)
{
txt.ID = "HB" + list[h].id.ToString();
hf.Value = list[h].id.ToString();
h++;
break;
}
}
}
}
}
Anybody got any ideas about how to find the textbox??
You have to search for the TextBox in the RepeaterItem. So you either handle the inner Repeater's ItemDataBound event or you simply iterate all RepeaterItems:
foreach(RepeaterItem item in ChildRepeater.Items){
if(item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem){
var txt = (TextBox)item.FindControl("TextBox1");
}
}