I have the following label with ids:
<asp:Label ID="FromName0" runat="server" Visible="true"></asp:Label>
<asp:Label ID="FromName1" runat="server" Visible="true"></asp:Label>
<asp:Label ID="FromName2" runat="server" Visible="true"></asp:Label>
<asp:Label ID="FromName3" runat="server" Visible="true"></asp:Label>
<asp:Label ID="FromName4" runat="server" Visible="true"></asp:Label>
I want to assign the values to the label ids using for loop.
I am using the following tags in c#:
for (int i = 0; i < count; i++)
{
var label = this.Controls.Find("FromName " + i, true) as Label;
label.Text = Session["DeliverAddress" + i].ToString();
}
But ‘Find’ shows error like below:
System.Web.UI.ControlCollections does not have the definition for ‘Find’. But I have already added ‘System.Web.UI’ dll file. Can anyone help me?
I am using dotnet framework 4.0.
Thanks in Advance.
You can do this like this
public Control[] FlattenHierachy(Control root)
{
List<Control> list = new List<Control>();
list.Add(root);
if (root.HasControls())
{
foreach (Control control in root.Controls)
{
list.AddRange(FlattenHierachy(control));
}
}
return list.ToArray();
}
and
protected void Page_Load(object sender, EventArgs e)
{
Control[] allControls = FlattenHierachy(Page);
foreach (Control control in allControls)
{
Label lbl = control as Label;
if (lbl != null && lbl.ID == "FromName0")
{
lbl.ID = "myid";//Do your like stuff
}
}
}
Just use : Here MSDN article about FindControl
//
// Summary:
// Searches the page naming container for a server control with the specified identifier.
//
// Parameters:
// id:
// The identifier for the control to be found.
//
// Returns:
// The specified control, or null if the specified control does not exist.
public override Control FindControl(string id);
Here how your code should look like. Just as advice check if the control is null or the session variable is null, this can give you an exception.
for (int i = 0; i < count; i++)
{
var label = FindControl("FromName " + i) as Label;
if(label == null || Session["DeliverAddress" + i] == null)
continue;
label.Text = Session["DeliverAddress" + i].ToString();
}
Related
Essentially trying to capture information when a checkbox is checked off, if it is then capture the quantity inputted. Attached is the code.
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="TextboxQuantity" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Here is my aspx.cs code.
//check to see if a check box is checked
for (int row = 0; row < gv_Input.Rows.Count; row++)
{
CheckBox Cbox = (CheckBox)gv_Input.Rows[row].FindControl("CheckboxSelect");
TextBox Tbox = (TextBox)gv_Input.Rows[row].FindControl("TextboxQuantity");
int quantity = Convert.ToInt32(Tbox.Text);
if (Cbox.Checked)
{
if (Tbox == null)
{
Response.Write("<script>alert('Fill in textbox')</script>");
}
else
{
Response.Write(
"<script>alert('Something was inputted into the textbox')</script>");
}
}
}
The line that gives the error is this line
int quantity = Convert.ToInt32(Tbox.Text);
Error:
Input string was not in the correct format
Even if the text box is left blank, the test if (Tbox == null) is never going to be true because you are checking the reference to the text box, not its content. I believe that your test should be:
if(Tbox == null || string.IsNullOrWhitespace(Tbox.Text) == true) {
Through further testing. I attempted using a foreach loop and it seemed to work. Thank you for you help here is my solution
foreach (GridViewRow row in gv_Input.Rows)
{
CheckBox Cbox = (CheckBox)row.FindControl("CheckboxSelect");
TextBox Tbox = (TextBox)row.FindControl("TextboxQuantity");
if (Cbox.Checked)
{
if (Tbox.Text == null || string.IsNullOrEmpty(Tbox.Text) == true)
{
Response.Write("<script>alert('Fill in textbox')</script>");
}
else {
Response.Write("<script>alert('Successful find')</script>");
}
I have a variable prix that returns 5998 7510 8144 9458 10916 13214 and this list must be changed to 59,98 75,10 81,44 94,58 109,16 132,14
How can I do it. That is, add a , before the last 2 digits (from right) of each number ?
This is the C# code I've tried so far :
XDocument docxx = XDocument.Parse(Session["xmlrs" + z + ""].ToString());
//This now holds the set of all elements named field
try
{
XNamespace foobar = "http://www.april-technologies.com";
var prix = docxx.Descendants(foobar + "CotisationMensuelle").Select(x => new { CotisationMensuelle =(string)x}).ToList();
rpMyRepeater1.DataSource = prix;
rpMyRepeater1.DataBind();
}
catch(Exception ex) {}
and the C# Code is :
<asp:Repeater ID="rpMyRepeater1" ItemType="" runat="server">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "CotisationMensuelle").ToString() %>
<br />
</ItemTemplate>
</asp:Repeater>
Not quite clear what you are asking as you code sample is unrelated to the list you have given as an eample. If you need to add a comma two letters from the end, try this,
string val = "7958";
string newVal = val.Insert(val.Length-2,",");
Console.WriteLine(newVal);
Try following:
XNamespace foobar = "http://www.april-technologies.com";
var prix = docxx.Descendants(foobar + "CotisationMensuelle").Select(x => new { CotisationMensuelle =(string)x}).ToList();
var newPrix = new List<string>();
foreach (var s in prix)
{
var s1 = s.CotisationMensuelle.Substring(0, s.CotisationMensuelle.Length - 2);
var s2 = s.CotisationMensuelle.Substring(s.CotisationMensuelle.Length - 2);
//add a comma before the last 2 digits (from right)
var s_total = s1 +","+ s2;
newPrix.Add(s_total);
}
rpMyRepeater1.DataSource = newPrix.Select(x => new {CotisationMensuelle = x}).ToList();
rpMyRepeater1.DataBind();
You could use DataBound event, for sample, in your page:
<asp:Repeater ID="rpMyRepeater1" ItemType="" runat="server" OnItemDataBound="rpMyRepeater1_ItemDataBound">
<ItemTemplate>
<asp:Literal ID="ltl" runat="server"></asp:Literal>
</ItemTemplate>
</asp:Repeater>
in your code behine:
int i = 0;
protected void rpMyRepeater1_ItemDataBound(object Sender, RepeaterItemEventArgs e)
{
// if the item on repeater is a item of data
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
// get value
string value = DataBinder.Eval(e.Item.DataItem, "CotisationMensuelle").ToString();
// find literal
Literal ltl = (Literal)e.Item.FindControl("ltl");
// check if i < 2
if (i < 2)
{
// write value
ltl.Text = value;
//increase i
i++;
}
else
{
// write value and <br/>
ltl.Text = string.Format("{0}<br />", value);
// zero i
i = 0;
}
}
}
how about:
string data = "5998 7510 8144 9458 10916 13214";
string newValue = string.Join(" ",
from s in data.Split(' ')
select (double.Parse(s) / 100).ToString("0.00"));
//59,98 75,10 81,44 94,58 109,16 132,14
I have a user control (.ascx) added to my application:
<uc1:pomedsrow runat="server" id="POMedsRow" />
And here is html and logic
<asp:Panel ID="Panel1" runat="server">
How many PO Meds do you wish to order?
<asp:TextBox ID="txtReqPONum" runat="server" />
<asp:LinkButton ID="lbnAddPOMeds" runat="server" Text="Go"
OnClick="lbnAddPOMeds_Click"/>
</asp:Panel>
<asp:Panel ID="pnlPOMeds" Visible="false" runat="server">
<table border="1">
<tr>
<td><p>PO Meds</p></td>
<td><p>Min/Max</p></td>
<td><p>Amount to Order</p></td>
</tr>
<uc1:pomedsrow runat="server" id="POMedsRow" />
</table>
<br />
</asp:Panel>
protected void lbnAddPOMeds_Click(object sender, EventArgs e)
{
int ReqPO = Convert.ToInt32(txtReqPONum.Text);
int n = ReqPO;
for (int i = 0; i < n; i++)
{
Control pomedsrow = new Control();
//Assigning the textbox ID name
pomedsrow.ID = "txtPOAmount" + "" + ViewState["num"] + i;
this.Form.Controls.Add(pomedsrow);
}
}
But when I click the link button nothing happens. Am I not calling the custom control correctly?
You are not adding your control properly. Try this:
protected void lbnAddPOMeds_Click(object sender, EventArgs e)
{
TextBox txtReqPONum = (TextBox) Panel1.FindControl("txtReqPONum");
int ReqPO = 0;
if (txtReqPONum != null && int.TryParse(txtReqPONum.Text, out ReqPO) )
{
int n = ReqPO;
for (int i = 0; i < n; i++)
{
UserControl myControl = (UserControl)Page.LoadControl("~/pomedsrow.ascx");//(UserControl)Page.LoadControl("Your control path/pomedsrow.ascx");
//Assigning the textbox ID name
myControl.ID = "txtPOAmount" + "" + ViewState["num"] + i;
Panel1.Controls.Add(myControl);
}
}
}
Basically I want to implement a filtering option for a Grid view and I have a dropdown list containing the column names and a checkboxlist containing the available filtering values for that column. Every time I select a different column, I have to load the filtering values for that column into the checkbox list.
The problem I have is that when I change the column in the dropdown list, the event for the checklist is fired and the application crashes.
My controls are defined like this:
<div class="LeftAligned">
<asp:Label ID="FilterLabel" runat="server" Text="Filter by:" />
<asp:DropDownList runat="server" ID="FilterReviewsDropDownList" AutoPostBack="true" OnSelectedIndexChanged="FilterReviewsDropDownList_SelectedIndexChanged" />
<asp:ImageButton ID="FilterReviewsButton" runat="server" ImageUrl="~/images/filter.png" AlternateText="VALUE" CssClass="filter_button" OnClick="FilterReviewsButton_Click" />
<div onmouseout="javascript:bMouseOver=false;" onmouseover="javascript:bMouseOver=true;" class="filter_div">
<asp:CheckBoxList AutoPostBack="true" ID="FilterReviewsCheckBoxList" ClientIDMode="Static" runat="server" CssClass="filter_checklist collapsed"
OnSelectedIndexChanged="FilterReviewsCheckBoxList_Selected">
</asp:CheckBoxList>
</div>
<%--asp:Button runat="server" ID="ApplyFilterButton" Text="Apply Filter" OnClick="ApplyFilterButton_Click"/>
<asp:Button runat="server" ID="ClearFilterButton" Text="Clear Filter" OnClick="ClearFilterButton_Click"/--%>
</div>
In the CodeBehind file I have the following code:
protected void FilterReviewsButton_Click(object sender, EventArgs e)
{
FilterReviewsCheckBoxList.CssClass = "filter_checklist";
}
protected void FilterReviewsDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
LoadFilterCheckboxes(FilterReviewsDropDownList.SelectedIndex);
}
private void LoadFilterCheckboxes(int iColumn)
{
SortedSet<string> oItems = new SortedSet<string>();
for (int i = 0; i < ReviewsGridView.Rows.Count; i++)
{
IEnumerable<Label> oLabels = ReviewsGridView.Rows[i].Cells[iColumn].Controls.OfType<Label>();
string sValue = "";
if (oLabels != null && oLabels.Count() > 0)
{
sValue = oLabels.First().Text;
}
else
{
sValue = ReviewsGridView.Rows[i].Cells[iColumn].Text;
}
if (!oItems.Contains(sValue))
oItems.Add(sValue);
}
FilterReviewsCheckBoxList.Items.Clear();
FilterReviewsCheckBoxList.Items.Add("All");
FilterReviewsCheckBoxList.Items[0].Selected = true;
foreach (string sItem in oItems)
{
FilterReviewsCheckBoxList.Items.Add(sItem);
FilterReviewsCheckBoxList.Items[FilterReviewsCheckBoxList.Items.Count - 1].Selected = true;
}
}
protected void FilterReviewsCheckBoxList_Selected(object sender, EventArgs e)
{
string sResult = Request.Form["__EVENTTARGET"];
if (string.IsNullOrEmpty(sResult))
{
FilterReviewsCheckBoxList.Items[0].Selected = true; //weird bug fix...
return;
}
string[] sCheckedBox = sResult.Split('$');
//get the index of the item that was checked/unchecked
int i = int.Parse(sCheckedBox[sCheckedBox.Length - 1].Split('_')[1]);
if (i == 0)
{
if (FilterReviewsCheckBoxList.Items[i].Selected == true)
{
for (int j = 1; j < FilterReviewsCheckBoxList.Items.Count; j++)
FilterReviewsCheckBoxList.Items[j].Selected = true;
}
else
{
for (int j = 1; j < FilterReviewsCheckBoxList.Items.Count; j++)
FilterReviewsCheckBoxList.Items[j].Selected = false;
}
}
else
{
if (FilterReviewsCheckBoxList.Items[i].Selected == false)
{
FilterReviewsCheckBoxList.Items[0].Selected = false;
}
else
{
//if (oFirstTable != null)
//{
// oTable = oFirstTable;
// oView = oTable.DefaultView;
//}
bool bAllChecked = true;
for (int j = 1; j < FilterReviewsCheckBoxList.Items.Count; j++)
{
if (FilterReviewsCheckBoxList.Items[j].Selected == false)
{
bAllChecked = false;
break;
}
}
if (bAllChecked)
FilterReviewsCheckBoxList.Items[0].Selected = true;
}
}
}
Any idea of why FilterReviewsCheckBoxList_Selected is called (with the dropdownlist as the sender argument) when changing the dropdown list?
For anyone who may encounter the same problem, the fix is to avoid static binding of the grid view to entity data source. Instead, bind the grid dynamically in the page load event.
I have a DataList on ym web page, from which a user can choose a certain option within the DataList row.
I use the ItemCommand of DataList for this. Actually, I want to highlight the selected row when the user clicks on the item in the row.
<ItemTemplate>
<tr>
<td style="text-align:center"><asp:LinkButton ID="Item" Text='<%#Eval("Item")%>' CommandName="select" runat="server" /> <br /></td>
<td style="text-align:center"><asp:Label ID="lbQuery" Text='<%#Eval("Query")%>' runat="server" /><br /> </td>
</tr>
</ItemTemplate>
As shown above, the user can click on the LinkButton to choose an item. How do I highlight the corresponding row or only the cell?
Use following Method for Datalist to highlight selected row:
protected void DataList1_ItemDataBound(object sender,
DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
//Add eventhandlers for highlighting
//a DataListItem when the mouse hovers over it.
e.Item.Attributes.Add("onmouseover",
"this.oldClass = this.className;" +
" this.className = 'EntryLineHover'");
e.Item.Attributes.Add("onmouseout",
"this.className = this.oldClass;");
//Add eventhandler for simulating
//a click on the 'SelectButton'
e.Item.Attributes.Add("onclick",
this.Page.ClientScript.GetPostBackEventReference(
e.Item.Controls[1], string.Empty));
}
}
in your RowDataBound event add like this.
// Get the linklabel object and check for non nullity
LinkLabel lblItem = e.Item.FindControl("Item") as LinkLabel
if(lblitem !=null)
{
// add properties to it
lblItem.Attributes.Add("onclick", "this.style.background='#eeff00'");
}
on Item command
string[] str = e.CommandArgument.ToString().Split(';');
int index = Convert.ToInt32(str[2]); // ur item selected index
DataListItemCollection xx = DataList1.Items;
int count = 0;
foreach (DataListItem x in xx)
{
if (count == index)
{
(x.FindControl("Item") as LinkButton).BorderColor = System.Drawing.Color.Red;
(x.FindControl("Item") as LinkButton).BorderWidth = 1;
}
else
{
(x.FindControl("Item") as LinkButton).BorderColor = System.Drawing.Color.White;
(x.FindControl("Item") as LinkButton).BorderWidth = 0;
}
count = count + 1;
}