I have a list view which is below.....
I am trying to read the Quantity and Available based on their ProductID
I want to read the data in the listview and then i will view the error if Quantity > Available
Now when ever i do so, the items are Null
here is ASPnet:
<asp:ListView ID="lvCart" runat="server" onitemcommand="lvCart_ItemCommand">
<ItemTemplate>
<tr>
<td>
<asp:Label ID="lbproductid" runat="server"
class="form-control" Width="50"
Text='<%# Eval("ProductID") %>' />
</td>
<td>
<%# Eval("Name") %>
<asp:Literal ID="ltRefNo" runat="server"
Text='<%# Eval("RefNo") %>' Visible="false" />
</td>
<td>
Php <%# Eval("Price", "{0: #,###.00}") %>
</td>
<td>
<asp:TextBox ID="txtQty" runat="server"
class="form-control" type="number"
min="1" max="99" MaxLength="2" Width="70"
Text='<%# Eval("Quantity") %>' required />
<asp:Label ID="avail" runat="server"
class="form-control" Width="50"
Text='<%# Eval("Available") %>' />
</td>
Code Behind 1:
(here is what i tried)
void getavail()
{
Label lbproductid = (Label)lvCart.FindControl("lbproductid");
Label avail = (Label)lvCart.FindControl("avail");
//ITemplate ID = (ITemplate)lvCart.FindControl("ProductID");
TextBox txtQty = (TextBox)lvCart.FindControl("txtQty");
if (int.Parse(txtQty.Text) > int.Parse(avail.Text))
{
error.Visible = true;
}
con.Close();
}
Code behind 2:
(Second trial)
foreach (ListViewDataItem dataitem in lvCart.Items)
{
Label lbproductid = (Label)lvCart.FindControl("lbproductid");
Label avail = (Label)lvCart.FindControl("avail");
//ITemplate ID = (ITemplate)lvCart.FindControl("ProductID");
TextBox txtQty = (TextBox)lvCart.FindControl("txtQty");
if (int.Parse(txtQty.Text) > int.Parse(avail.Text))
{
error.Visible = true;
}
con.Close();
}
When trying the second codes, it does not read codes after it. Starting at the line:
Label lbproductid = (Label)lvCart.FindControl("lbproductid");
and then it directs to last bracket and close();
I am putting this GetAvail in the page load event as i want it to show right away.
help this got me hours. thanks in advance
Related
I have a legacy web application that I'm needing to migrate to a new Windows Server (to 2019 from 2008r2) and have been running into some security issues. mainly with a rich text style textbox FCKeditor text box. this editor adds html tags and if somebody copies from a Word doc to fill out the field, the hidden Word doc structures (xml and style content) is also brought over and thus the 2019 security throws an error message about the text being potentially hazardous. I came up with a function to clean up the text content and bring it back to a plain text content. however the security still throws an error and never makes it to the function i created.
protected string GetCleanedText(string content)
{
const string tagWhiteSpace = #"(>|$)(\W|\n|\r)+<";
const string stripFormatting = #"<[^>]*(>|$)";
const string lineBreak = #"<(br|BR)\s{0,1}\/{0,1}>";
const string xmlformatting = #"<xml>[\s\S]*?<\/xml>";
const string styleformatting = #"<style>[\s\S]*?<\/style>";
Regex lineBreakRegex = new Regex(lineBreak, RegexOptions.Multiline);
Regex xmlformattingRegex = new Regex(xmlformatting, RegexOptions.Multiline);
Regex stripFormattingRegex = new Regex(stripFormatting, RegexOptions.Multiline);
Regex tagWhiteSpaceRegex = new Regex(tagWhiteSpace, RegexOptions.Multiline);
Regex styleformattingRegex = new Regex(styleformatting, RegexOptions.Multiline);
string text = content;
//xml formatting
text = xmlformattingRegex.Replace(text, string.Empty);
//style formatting
text = styleformattingRegex.Replace(text, string.Empty);
//Decode html specific characters
//text = System.Net.WebUtility.HtmlDecode(text);
//text = System.Net.WebUtility.HtmlDecode(text);
text = System.Web.HttpUtility.HtmlDecode(text);
//Remove tag whitespace/line breaks
text = tagWhiteSpaceRegex.Replace(text, "><");
//Replace <br /> with line breaks
text = lineBreakRegex.Replace(text, Environment.NewLine);
//Strip formatting
text = stripFormattingRegex.Replace(text, string.Empty);
return text;
}
The data on the aspx page is set up with two way binding via Bind(). I've tried replacing it with Eval() and calling theGetCleanedText() function to clean the text content, but the data continues to get wiped due to the FormView1_ItemCreated() function and either leaves the text box empty or doesn't allow the content to be updated. I've also tried to implement stuff in the ItemCreated, ItemUpdating, and FormView1_DataBound() functions and still either get an emtpy text box or one that when Editing the text field doesn't maintain the new text content.
here's the aspx page (I've removed most of the other content to focus on what I'm trying to fix):
<asp:FormView ID="FormView1" runat="server" DataKeyNames="id" DataSourceID="ObjectDataSource1"
OnItemCreated="FormView1_ItemCreated" OnDataBound="FormView1_DataBound" OnItemUpdating="FormView1_ItemUpdating"
OnItemDeleting="FormView1_ItemDeleting" BorderWidth="0px" CssClass="nospace"
Width="100%" OnItemInserting="FormView1_ItemInserting" AllowPaging="True" EmptyDataText="No records found.">
<EditItemTemplate>
<table width="100%" border="0" cellpadding="2">
<tr>
<td>
<b>Business Reason for the Purchase:</b><br />
<FCKeditorV2:FCKeditor ID="purchase_reasonTextBox" runat="server" BasePath="~/fckeditor/"
Height="150px" ToolbarSet="Request" Value='<%# Bind("purchase_reason") %>'>
</FCKeditorV2:FCKeditor>
</td>
<td>
</td>
<td>
<b>Description of Product or Service:</b><br />
<FCKeditorV2:FCKeditor ID="product_descriptionTextBox" runat="server" BasePath="~/fckeditor/"
Height="150px" ToolbarSet="Request" Value='<%# Bind("product_description") %>'>
</FCKeditorV2:FCKeditor>
</td>
</tr>
<tr>
<td>
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update"
CssClass="btn" OnClientClick="RemoveDisplayMessage()" TabIndex="40" Text="Update"
ValidationGroup="requestgroup" />
<asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False"
CommandName="Cancel" CssClass="btn" OnClientClick="RemoveDisplayMessage()" TabIndex="42"
Text="Cancel" />
<asp:ValidationSummary ID="ValidationSummary1" runat="server" HeaderText="Please complete fields:"
ShowMessageBox="True" ShowSummary="False" ValidationGroup="requestgroup" />
</td>
<td align="right">
</td>
<td align="right">
</td>
<td align="right">
</td>
</tr>
</table>
</EditItemTemplate>
<InsertItemTemplate>
<table width="100%" border="0" cellpadding="2">
<tr>
<td>
<b>Business Reason for the Purchase:</b><br />
<FCKeditorV2:FCKeditor ID="purchase_reasonTextBox" runat="server" BasePath="~/fckeditor/"
Height="150px" ToolbarSet="Request" Value='<%# Bind("purchase_reason") %>'>
</FCKeditorV2:FCKeditor>
</td>
<td>
</td>
<td>
<b>Description of Product or Service:</b><br />
<FCKeditorV2:FCKeditor ID="product_descriptionTextBox" runat="server" BasePath="~/fckeditor/"
Height="150px" ToolbarSet="Request" Value='<%# Bind("product_description") %>'>
</FCKeditorV2:FCKeditor>
</td>
</tr>
<tr>
<td>
<asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" CommandName="Insert"
CssClass="btn" OnClientClick="RemoveDisplayMessage()" TabIndex="42" Text="Insert"
ValidationGroup="requestgroup" />
<asp:LinkButton ID="InsertCancelButton" runat="server" CausesValidation="False"
CommandName="Cancel" CssClass="btn" OnClientClick="RemoveDisplayMessage()" TabIndex="44"
Text="Cancel" />
<asp:ValidationSummary ID="ValidationSummary1" runat="server" HeaderText="Please complete fields:"
ShowMessageBox="True" ShowSummary="False" ValidationGroup="requestgroup" />
</td>
<td align="right">
</td>
<td align="right">
</td>
<td align="right">
</td>
</tr>
</table>
</InsertItemTemplate>
<ItemTemplate>
<table width="100%" border="0" cellpadding="2">
<tr>
<td colspan="2" valign="top">
<b>Business Reason for the Purchase:</b><br />
<asp:Label ID="purchase_reasonLabel" runat="server" Text='<%# Bind("purchase_reason") %>'
BackColor="#EFF2F3" BorderWidth="0" CssClass="textBlock" />
</td>
</tr>
<tr>
<td colspan="2" valign="top">
<b>Description of Product or Service:</b><br />
<asp:Label ID="product_descriptionLabel" runat="server" Text='<%# Bind("product_description") %>'
BackColor="#EFF2F3" BorderWidth="0" CssClass="textBlock" />
</td>
</tr>
<tr>
<td>
<asp:LinkButton ID="EditButton" runat="server" CausesValidation="False" CommandName="Edit"
CssClass="btn" OnClientClick="RemoveDisplayMessage()" Text="Edit" />
<asp:LinkButton ID="DeleteButton" runat="server" CausesValidation="False" CommandName="Delete"
CssClass="btn" OnClientClick="RemoveDisplayMessage(); return confirm('Do you really want to delete this item?');"
Text="Delete" />
<asp:LinkButton ID="NewButton" runat="server" CausesValidation="False" CommandName="New"
CssClass="btn" OnClientClick="RemoveDisplayMessage()" Text="New" />
</td>
<td align="right">
<asp:LinkButton ID="ApproveButton" runat="server" CausesValidation="False" CommandArgument='<%# Eval("id") %>'
CommandName="Approve" CssClass="btn" OnCommand="StatusButton_Command" Text="Approve" />
<asp:LinkButton ID="DenyButton" runat="server" CausesValidation="False" CommandArgument='<%# Eval("id") %>'
CommandName="Deny" CssClass="btn" OnCommand="StatusButton_Command" Text="Deny" />
<asp:LinkButton ID="ReturnButton" runat="server" CausesValidation="False" CommandArgument='<%# Eval("id") %>'
CommandName="more info" CssClass="btn" OnCommand="StatusButton_Command" Text="Require more info" />
</td>
</tr>
</table>
</ItemTemplate>
and here's the C# code behind page:
protected void FormView1_DataBound(object sender, EventArgs e)
{
// databinding for things that weren't set up with Bind()
// does not have any content for the purchase_reasonTextBox or product_descriptionTextBox
}
protected void FormView1_ItemCreated(object sender, EventArgs e)
{
FormViewRow row = FormView1.Row;
if (FormView1.CurrentMode == FormViewMode.Edit || FormView1.CurrentMode == FormViewMode.Insert)
{
//initialize
if (FormView1.CurrentMode == FormViewMode.Insert)
{
// nothing relevant
}
else if (FormView1.CurrentMode == FormViewMode.Edit)
{
//nothing relevant
}
FredCK.FCKeditorV2.FCKeditor purchase_reasonTextBox = (FredCK.FCKeditorV2.FCKeditor)row.FindControl("purchase_reasonTextBox");
if (purchase_reasonTextBox != null)
{
purchase_reasonTextBox.CustomConfigurationsPath = Request.ApplicationPath + "/include/fckconfig.js";
purchase_reasonTextBox.EditorAreaCSS = Request.ApplicationPath + "/App_Themes/FrontTheme/Style.css";
purchase_reasonTextBox.StylesXmlPath = Request.ApplicationPath + "/include/fckstyles.xml";
}
FredCK.FCKeditorV2.FCKeditor product_descriptionTextBox = (FredCK.FCKeditorV2.FCKeditor)row.FindControl("product_descriptionTextBox");
if (product_descriptionTextBox != null)
{
product_descriptionTextBox.CustomConfigurationsPath = Request.ApplicationPath + "/include/fckconfig.js";
product_descriptionTextBox.EditorAreaCSS = Request.ApplicationPath + "/App_Themes/FrontTheme/Style.css";
product_descriptionTextBox.StylesXmlPath = Request.ApplicationPath + "/include/fckstyles.xml";
}
}
}
protected void FormView1_ItemUpdating(object sender, FormViewUpdateEventArgs e)
{
FormViewRow row = FormView1.Row;
if (FormView1.CurrentMode == FormViewMode.Edit)
{
//nothing relevant
}
}
I'm running out of ideas for how to work around this issue. I Have to clean the content, and I'm not allowed to edit the database directly.
here's the last set of changes I tried:
protected void FormView1_DataBound(object sender, EventArgs e)
{
FredCK.FCKeditorV2.FCKeditor purchase_reasonTextBox = (FredCK.FCKeditorV2.FCKeditor)row.FindControl("purchase_reasonTextBox");
if (purchase_reasonTextBox != null)
{
purchase_reasonTextBox.CustomConfigurationsPath = Request.ApplicationPath + "/include/fckconfig.js";
purchase_reasonTextBox.EditorAreaCSS = Request.ApplicationPath + "/App_Themes/FrontTheme/Style.css";
purchase_reasonTextBox.StylesXmlPath = Request.ApplicationPath + "/include/fckstyles.xml";
}
purchase_reasonTextBox.Value = GetCleanedText(rowView["purchase_reason"].ToString());
FredCK.FCKeditorV2.FCKeditor product_descriptionTextBox = (FredCK.FCKeditorV2.FCKeditor)row.FindControl("product_descriptionTextBox");
if (product_descriptionTextBox != null)
{
product_descriptionTextBox.CustomConfigurationsPath = Request.ApplicationPath + "/include/fckconfig.js";
product_descriptionTextBox.EditorAreaCSS = Request.ApplicationPath + "/App_Themes/FrontTheme/Style.css";
product_descriptionTextBox.StylesXmlPath = Request.ApplicationPath + "/include/fckstyles.xml";
}
product_descriptionTextBox.Value = GetCleanedText(rowView["product_description"].ToString());
}
protected void FormView1_ItemUpdating(object sender, FormViewUpdateEventArgs e)
{
FormViewRow row = FormView1.Row;
if (FormView1.CurrentMode == FormViewMode.Edit)
{
FredCK.FCKeditorV2.FCKeditor purchase_reasonTextBox = (FredCK.FCKeditorV2.FCKeditor)row.FindControl("purchase_reasonTextBox");
e.NewValues["purchase_reason"] = purchase_reasonTextBox.Value; //GetCleanedText(purchase_reasonTextBox.Value);
FredCK.FCKeditorV2.FCKeditor product_descriptionTextBox = (FredCK.FCKeditorV2.FCKeditor)row.FindControl("product_descriptionTextBox");
e.NewValues["product_description"] = product_descriptionTextBox.Value; //GetCleanedText(product_descriptionTextBox.Value);
}
}
protected void FormView1_ItemInserting(object sender, FormViewInsertEventArgs e)
{
Response.Write(" -- Item Inserting -- ");
FormViewRow row = FormView1.Row;
if (FormView1.CurrentMode == FormViewMode.Insert)
{
FredCK.FCKeditorV2.FCKeditor purchase_reasonTextBox = (FredCK.FCKeditorV2.FCKeditor)row.FindControl("purchase_reasonTextBox");
e.Values["purchase_reason"] = GetCleanedText(purchase_reasonTextBox.Value);
FredCK.FCKeditorV2.FCKeditor product_descriptionTextBox = (FredCK.FCKeditorV2.FCKeditor)row.FindControl("product_descriptionTextBox");
e.Values["product_description"] = GetCleanedText(product_descriptionTextBox.Value);
}
}
I would appreciate any advice on how to get the text content inside of the text boxes returned to plain text
<FCKeditorV2:FCKeditor ID="purchase_reasonTextBox" runat="server" BasePath="~/fckeditor/" Height="150px" ToolbarSet="Request" Value='<%# Bind("purchase_reason") %>'>
</FCKeditorV2:FCKeditor>
<FCKeditorV2:FCKeditor ID="product_descriptionTextBox" runat="server" BasePath="~/fckeditor/" Height="150px" ToolbarSet="Request" Value='<%# Bind("product_description") %>'>
</FCKeditorV2:FCKeditor>
As you do not share the error message I'll give you an answer based on a common error that occurs with rich text plugins:
A potentially dangerous Request.Form value was detected from the client
This error occurs because your server do not allow html content in your requests and adding html in the request is exactly what a rich text plugin does. So you need to enable it on your server.
How?
1) Add ValidateRequest="false" on your .aspx file.
<%# Page Language="C#" ... ValidateRequest="false" %>
2) Set httpRuntime requestValidationMode value to 2.0 on your web.config.
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5"/>
<httpRuntime targetFramework="4.5" requestValidationMode="2.0"/>
</system.web>
</configuration>
3) This step should be already done on your legacy. But if not, you shoul add a custom validation to avoid script injection on the pages where you will show the HTML inputed by the user.
Steps 1 and 2 are enough to do not get this error anymore, step 3 is "just" a security tip.
Ok, so I have this challenge and I'm still learning how things work in ASP C#. I have a parent update panel and inside that is a parent repeater. Inside that is a child update panel (not sure how necessary that is) and a child repeater. The Child repeater is for search results. When the user clicks on the textbox for entry of the parent repeater, an Ajax pop up occurs that allows them to search for the person they need in our LDAP AD system in the child updatepanel and when they enter a Last Name, First Name (or both) or an email and click "Search", the code behind does it's work, finds the results, populates the repeater and gets databound. I have this all happening in the parent OnItemCommand and it works. Here's my challenge - how in the world to I take the child row selected via button onclick and insert the data into the parent row items?
Here's my aspx code section, I apologize for the formatting:
<table class="project_info">
<tr>
<td colspan="3">
<dl>
<dt>Project Stakeholders<br />
<asp:Label runat="server" ID="sh_SHHeader" Text="Stakeholder" Width="314"></asp:Label>
<asp:Label runat="server" ID="sh_SHInput" Text="Input Level" Width="168"></asp:Label>
</dt>
<asp:UpdatePanel runat="server" ID="udp_SubProjectsTeamList" UpdateMode="Conditional">
<ContentTemplate>
<asp:Repeater ID="AddStakeholder" runat="server" OnItemCommand="AddStakeholder_ItemCommand" OnItemDataBound="AddStakeholder_ItemDataBound">
<ItemTemplate>
<dd>
<asp:HiddenField ID="hdn_StakeholderId" runat="server" />
<asp:HiddenField ID="hdn_StakeholderGUID" runat="server" />
<asp:TextBox ID="txt_Stakeholder" runat="server" Width="304" onkeyup="hasPendingChanges()" placeholder="Last Name, First Name" Text='<%# DataBinder.Eval(Container.DataItem, "MSStakeholder") %>'></asp:TextBox>
<ajax:ModalPopupExtender runat="server" ID="aj_AddStakeholder" PopupControlID="pnl_AddStakeholderChild" TargetControlID="txt_Stakeholder" CancelControlID="PopCancelButton" DropShadow="true" Y="50"></ajax:ModalPopupExtender>
<asp:DropDownList ID="drp_SHInput" runat="server" AppendDataBoundItems="true" SelectedIndex='<%# Convert.ToInt32(DataBinder.Eval(Container.DataItem,"MSInput")) %>' Width="160" onchange="hasPendingChanges()">
<asp:ListItem Text="Select Input Level" Value="0" />
</asp:DropDownList>
<asp:Button ID="btnAddAnother" runat="server" CssClass="k-button k-button-icontext repeaterbutton" Font-Size="small" Text='<%# DataBinder.Eval(Container.DataItem, "Button") %>' CommandName='<%# DataBinder.Eval(Container.DataItem, "Button") %>' CausesValidation="false" UseSubmitBehavior="false"/>
<asp:Button ID="btnReset" runat="server" CssClass="k-button k-button-icontext repeaterbutton" Font-Size="small" Font-Bold="false" Text='Reset' ToolTip="Reset Entry" OnClick="clearSHRow" CausesValidation="false" UseSubmitBehavior="false"/>
<asp:Panel ID="pnl_AddStakeholderChild" runat="server" >
<div id="mainformdiv" class="k-widget k-window shPopup">
<div class="k-window-titlebar k-header">
<span class="k-window-title">Stakeholder Search<asp:Button ID="PopCancelButton" runat="server" CssClass="k-button k-button-icontext" Font-Size="small" CausesValidation="false" Text="X" style="float:right;" OnClientClick="this.form.reset();"/></span>
</div>
<div class="k-popup-edit-form k-window-content k-content shPopupHead">
<asp:UpdatePanel runat="server" ID="udp_StakeholderSearch">
<ContentTemplate>
<div style="text-align:center;">
<asp:Label ID="lbl_LastName" runat="server" CssClass="shLabel" Text="Last Name:"/><asp:TextBox ID="txt_LastName" runat="server" Width="200"/> <asp:Label ID="lbl_FirstName" runat="server" CssClass="shLabel" Text="First Name:"/><asp:TextBox ID="txt_FirstName" runat="server" Width="150"/> OR<asp:Label ID="lbl_Email" runat="server" CssClass="shLabel" Text="Email:"/><asp:TextBox ID="txt_Email" runat="server" Width="200"/>
<asp:Button ID="btn_Search" runat="server" CssClass="k-button k-button-icontext" Text="Search" CausesValidation="false" CommandName="Search"></asp:Button>
</div>
<asp:Repeater ID="rpt_SHSearchResults" runat="server">
<HeaderTemplate>
<div class="shPopupResults k-grid k-widget">
<table>
<thead class="k-grid-header">
<tr>
<th class="k-header" rowspan="1">Stakeholder Name</th>
<th class="k-header" rowspan="1">Title</th>
<th class="k-header" rowspan="1">Organization</th>
<th class="k-header" rowspan="1">Email</th>
<th class="k-header" rowspan="1"></th>
</tr>
</thead>
<tbody>
</HeaderTemplate>
<ItemTemplate>
<asp:HiddenField ID="samaccountname" runat="server" Value='<%# Eval("userName") %>'/>
<asp:HiddenField ID="objectGUID" runat="server" Value='<%# Eval("userGUID") %>'/>
<tr class="k-alt">
<td><asp:Label runat="server" ID="name" Text='<%# Eval("FullName") %>' /></td>
<td><asp:Label runat="server" ID="title" Text='<%# Eval("Title") %>' /></td>
<td><asp:Label runat="server" ID="company" Text='<%# Eval("Company") %>' /></td>
<td><asp:Label runat="server" ID="email" Text='<%# Eval("Email") %>' /></td>
<td style="text-align: center;width:auto"><asp:Button runat="server" ID="btn_SHSelect" CssClass="k-button k-button-icontext" Text="Select" CausesValidation="false" UseSubmitBehavior="false"/></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</tbody>
</table>
</div>
</FooterTemplate>
</asp:Repeater>
<asp:Panel ID="pnl_EmptyList" runat="server" Visible="false">
<div class="shEmptyResults k-grid k-widget">
<table>
<tr class="k-alt">
<td colspan="5">
<asp:Label ID="lbl_EmptyList" runat="server" BorderWidth="0"></asp:Label>
</td>
</tr>
</table>
</div>
</asp:Panel>
<asp:Panel ID="pnl_Results" runat="server" Visible="false">
<div class="shPopupHead">
<span class="k-window-title"><asp:Label runat="server" ID="resultCount" style="float:left;" /></span>
</div>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID="udp_SearchProgress" runat="server" AssociatedUpdatePanelID="udp_StakeholderSearch">
<ProgressTemplate>
<div class="shEmptyResults k-grid k-widget">
<table>
<tr class="k-alt">
<td colspan="5" style="background:#fff"><img src="env/images/searching.gif" />
</td>
</tr>
</table>
</div>
</ProgressTemplate>
</asp:UpdateProgress>
</div>
</div>
</asp:Panel>
</dd>
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
</dl>
</td>
</tr>
</table>
And the .cs code behind:
protected void AddStakeholder_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Search")
{
string last_name = ((TextBox)e.Item.FindControl("txt_LastName")).Text;
string first_name = ((TextBox)e.Item.FindControl("txt_FirstName")).Text;
string email = ((TextBox)e.Item.FindControl("txt_Email")).Text;
TextBox test = ((TextBox)e.Item.FindControl("txt_Email"));
string searchFilter = "";
if (!string.IsNullOrWhiteSpace(last_name) && string.IsNullOrWhiteSpace(first_name) && string.IsNullOrWhiteSpace(email))
{
searchFilter = "(&(objectCategory=person)(objectClass=user)(company=*)(sn=" + last_name + ")(!(UserAccountControl:1.2.840.113556.1.4.803:=2)))";
}
else if (!string.IsNullOrWhiteSpace(last_name) && !string.IsNullOrWhiteSpace(first_name) && string.IsNullOrWhiteSpace(email))
{
searchFilter = "(&(objectCategory=person)(objectClass=user)(company=*)(sn=" + last_name + ")(givenName=" + first_name + ")(!(UserAccountControl:1.2.840.113556.1.4.803:=2)))";
}
else if (!string.IsNullOrWhiteSpace(email))
{
searchFilter = "(&(objectCategory=person)(objectClass=user)(company=*)(userPrincipalName=" + email + ")(!(UserAccountControl:1.2.840.113556.1.4.803:=2)))";
}
//output.Text = "(&(objectCategory=person)(objectClass=user)" + searchFilter + ")";
DirectoryEntry domain = new DirectoryEntry("my company's LDAP server information");
DirectorySearcher dsLookFor = new DirectorySearcher(domain)
{
SearchScope = SearchScope.Subtree,
Filter = searchFilter
};
//dsLookFor.Filter = searchFilter;
dsLookFor.PropertiesToLoad.Add("sAMAccountName");
dsLookFor.PropertiesToLoad.Add("objectGUID");
dsLookFor.PropertiesToLoad.Add("name");
dsLookFor.PropertiesToLoad.Add("title");
dsLookFor.PropertiesToLoad.Add("company");
dsLookFor.PropertiesToLoad.Add("userPrincipalName");
dsLookFor.Sort.Direction = System.DirectoryServices.SortDirection.Ascending;
dsLookFor.Sort.PropertyName = "name";
SearchResultCollection result = dsLookFor.FindAll();
int totalCount = result.Count;
var users = result.Cast<SearchResult>().Select(sr => sr.GetDirectoryEntry()).Select(de => new
{
userName = de.Properties["sAMAccountName"].Value != null ? protectSpecialChar((string)de.Properties["sAMAccountName"].Value) : "",
userGUID = de.Properties["objectGUID"].Value != null ? new Guid((byte[])de.Properties["objectGUID"].Value).ToString() : "",
FullName = de.Properties["name"].Value != null ? protectSpecialChar((string)de.Properties["name"].Value) : "",
Title = de.Properties["title"].Value != null ? protectSpecialChar((string)de.Properties["title"].Value) : "",
Company = de.Properties["company"].Value != null ? protectSpecialChar((string)de.Properties["company"].Value) : "",
Email = de.Properties["userPrincipalName"].Value != null ? protectSpecialChar((string)de.Properties["userPrincipalName"].Value) : "",
}).ToList();
if (totalCount == 0)
{
((Panel)e.Item.FindControl("pnl_EmptyList")).Visible = true;
((Label)e.Item.FindControl("lbl_EmptyList")).Text = "No results to display. Please check your entries and try again.";
}
else
{
rpt_SHSearchResults.DataSource = users;
rpt_SHSearchResults.DataBind();
rpt_SHSearchResults.Visible = true;
((Panel)e.Item.FindControl("pnl_Results")).Visible = true;
((Label)e.Item.FindControl("resultCount")).Text = "Result count: " + totalCount;
}
}
}
protected void AddStakeholder_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
HiddenField hdn_StakeholderId = e.Item.FindControl("hdn_StakeholderId") as HiddenField;
HiddenField hdn_StakeholderGUID = e.Item.FindControl("hdn_StakeholderGUID") as HiddenField;
TextBox txt_Stakeholder = e.Item.FindControl("txt_Stakeholder") as TextBox;
DropDownList drp_SHInput = e.Item.FindControl("drp_SHInput") as DropDownList;
DataSet shInputSet = new DataSet();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["webconfig entry"].ConnectionString))
{
con.Open();
//Contractor List dropdown
SqlDataAdapter shInput = new SqlDataAdapter("SELECT StakeholderInputId,InputName FROM StakeholderInput", con);
shInput.Fill(shInputSet);
drp_SHInput.DataSource = shInputSet;
drp_SHInput.DataTextField = "InputName";
drp_SHInput.DataValueField = "StakeholderInputId";
drp_SHInput.DataBind();
con.Close();
}
Repeater shSearchResults = e.Item.FindControl("rpt_SHSearchResults") as Repeater;
HiddenField userName = shSearchResults.FindControl("samaccountname") as HiddenField;
HiddenField userGUID = shSearchResults.FindControl("objectGUID") as HiddenField;
Label name = shSearchResults.FindControl("name") as Label;
Label title = shSearchResults.FindControl("title") as Label;
Label company = shSearchResults.FindControl("company") as Label;
Label email = shSearchResults.FindControl("email") as Label;
}
}
Should I have a OnClick="dosomethinghere" on the child repeater button "Select" and then take the child row information and attempt to inject it into the parent controls? How would that be accomplished?
I've tried everything I can think of to make this work, and I've done countless searches in Google and SO and elsewhere to see if anyone else has solved this issue. I'm about an intermediate level coder and this one has me stumped. How do I get the selected result row from the child repeater into the parent row?
Thank you for the help!
On my aspx page i have a repeater with 5 textboxes with 1 imagebutton to edit the row
these textboxes are readonly, to edit them I need them to not be readOnly..
In my behind code i am using :
protected void EditRecipeInfo(object sender, CommandEventArgs e)
{
ImageButton ib = sender as ImageButton;
TextBox titleTXT = (TextBox)ib.FindControl("titleRepeat");
TextBox qtyTXT = (TextBox)ib.FindControl("qtyRepeat");
TextBox uomTXT = (TextBox)ib.FindControl("uomRepeat");
TextBox prepTXT = (TextBox)ib.FindControl("prepRepeat");
TextBox orTXT = (TextBox)ib.FindControl("orRepeat");
titleTXT.ReadOnly = false;
qtyTXT.ReadOnly = false;
uomTXT.ReadOnly = false;
prepTXT.ReadOnly = false;
orTXT.ReadOnly = false;
////
}
But when I fire this event the break points show me that the property is being set to false, but when I click to delete any value in the textbox it still acts like a readonly
UPDATE:
<asp:Repeater ID="ingredRepeater" runat="server">
<HeaderTemplate>
<table style="width: 100%">
<tr>
<th></th>
<th></th>
<th><h2>Title</h2></th>
<th><h2>Qty.</h2></th>
<th><h2>UoM</h2></th>
<th><h2>Prep.</h2></th>
<th><h2>Alternate</h2></th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:ImageButton Style="height: 25px; width: 25px;" ImageUrl="/img/edit.png" Visible="true"
ID="editRecipeInfo" AutoPostBack="true" runat="server" OnCommand="EditRecipeInfo" CommandName='<%# DataBinder.Eval(Container, "DataItem.DetailID") %>' />
</td>
<td>
<asp:ImageButton ImageUrl="/img/RedX.png" ID="button2" runat="server" Height="20"
Width="20" CommandName='<%# DataBinder.Eval(Container, "DataItem.DetailID") %>'
OnCommand="deleteRecipeView" />
</td>
<td>
<asp:TextBox AutoPostBack="true" ReadOnly="true" ID="titleRepeat" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Name") %>'
size="45" />
</td>
<td>
<asp:TextBox AutoPostBack="true" ReadOnly='true' ID="qtyRepeat" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Quantity") %>'
size="10" />
</td>
<td>
<asp:TextBox AutoPostBack="true" ReadOnly='true' ID="uomRepeat" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.UnitsOfMeasure") %>'
size="10" />
</td>
<td>
<asp:TextBox AutoPostBack="true" ReadOnly='true' ID="prepRepeat" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Prep") %>'
size="10" />
</td>
<td>
<asp:TextBox AutoPostBack="true" ReadOnly='true' ID="orRepeat" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.AlternativeIngredients") %>'
size="20" />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
Make sure you're not re-binding the repeater after you set the ReadOnly property to true.
I agree with #Tariqulazam , the markup would help.
Assuming your code comes from an ItemCommand event handler, I am quite surprised to see the FindControl applied to the ImageButton.
I guess your code should be something like this :
void rpAcces_ItemCommand(object source, RepeaterCommandEventArgs e)
{
//...
ImageButton ib = sender as ImageButton;
TextBox titleTXT = (TextBox)e.Item.FindControl("titleRepeat");
TextBox qtyTXT = (TextBox)e.Item.FindControl("qtyRepeat");
TextBox uomTXT = (TextBox)e.Item.FindControl("uomRepeat");
TextBox prepTXT = (TextBox)e.Item.FindControl("prepRepeat");
TextBox orTXT = (TextBox)e.Item.FindControl("orRepeat");
titleTXT.ReadOnly = false;
qtyTXT.ReadOnly = false;
uomTXT.ReadOnly = false;
prepTXT.ReadOnly = false;
orTXT.ReadOnly = false;
//...
}
Also, be aware that you can not rebind your repeater later in the page life-cycle without losing these changes.
And watch out for any Enabled attribute set on your TextBoxes
Once again, difficult to answer without the whole code.
I am using C# asp.net 4.0 in my project where i need to display price in India curreny format.
eg. my number is 12550000.00 then i want to display it as 1,25,50,000.00
But i want this to be displayed in gridview when i bind the data to the gridview,
so it can be done in markup page. where we place Eval for each Item Data Bound.
However, i would also like to explain my senario for displaying comma sepearted values.
i have a set of textboxes above the gridview where user makes entries of values and click add.
this gets add in the viewstate and the viewstate is binded to gridview.
In gridview i also have Edit button on click of it the values in viewstate is passed back to textbox on RowCommand Event of gridview. and on update click the viewstate datatable is updated and Binded back to gridview.
FOR your reference:
protected void gvPropertyConfig_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "EditItem")
{
int index = Convert.ToInt32(e.CommandArgument);
hdnIndex.Value = index.ToString();
DataTable dt = (DataTable)ViewState["proeprtyConfig"];
DataRow dr = dt.Rows[index];
if (Request.QueryString["CMD"] == "Edit")
{
hdnPropertyConfigID.Value = dr["config_id"].ToString();
if (dr["is_active"].ToString().ToLower() == "true")
{
chkConfigVisible.Checked = true;
}
else
{
chkConfigVisible.Checked = false;
}
thIsActHed.Visible = true;
tdIsActchk.Visible = true;
tdbtnConfig.ColSpan = 2;
}
txtScalableArea.Text = dr["scalable_area"].ToString();
txtCarpetArea.Text = dr["carpet_area"].ToString();
txtPricePerSqFt.Text = dr["price_per_sq_ft"].ToString();
txtCCPricePerSqFt.Text = dr["cc_price_per_sq_ft"].ToString();
txtTotalPrice.Text = dr["total_price"].ToString();
ddlNoOfBedrooms.SelectedValue = dr["room_id"].ToString();
btnUpdateConfig.Visible = true;
btnConfigSubmit.Visible = false;
}
if (e.CommandName == "DeleteItem")
{
int index = Convert.ToInt32(e.CommandArgument);
DataTable dt = (DataTable)ViewState["proeprtyConfig"];
DataRow dr = dt.Rows[index];
if (Request.QueryString["CMD"].ToString() == "Edit")
{
int PropertyConfigID = Convert.ToInt32(dr[0].ToString());
prConfigObj.deletePropertyConfig(PropertyConfigID);
fillData();
}
else
{
dr.Delete();
gvPropertyConfig.DataSource = (DataTable)ViewState["proeprtyConfig"];
gvPropertyConfig.DataBind();
}
clearConfigTextBoxes();
btnConfigSubmit.Visible = true;
btnUpdateConfig.Visible = false;
}
setChecklistAttr();
}
catch (Exception ex)
{
throw ex;
}
}
Below is the markup for Gridview,
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="tabBord">
<table>
<tr>
<td colspan="4" class="middle">
<h4>
Property Config Information</h4>
</td>
</tr>
<tr>
<td colspan="4">
<p>
Note: Enter total prices in lacs only. Eg. If 1 Crore than enter 1,00,00,000
</p>
<p>
</p>
</td>
</tr>
<tr>
<td>
<div id="divconfigstr" runat="server">
Configuration<span style="color: Red">*</span></div>
<%--class="displaynon"--%>
</td>
<td>
<div id="divnoofbedrooms" runat="server">
<asp:DropDownList Enabled="false" ID="ddlNoOfBedrooms" runat="server">
</asp:DropDownList>
<p>
</p>
</div>
</td>
<td>
Scalable Area <span style="color: Red">*</span>
</td>
<td>
<asp:TextBox ID="txtScalableArea" runat="server" autocomplete="off" MaxLength="10"></asp:TextBox><p>
</p>
</td>
</tr>
<tr>
<td>
Carpet Area <span style="color: Red">*</span>
</td>
<td>
<asp:TextBox ID="txtCarpetArea" runat="server" autocomplete="off" MaxLength="10"></asp:TextBox><p>
</p>
</td>
<td>
Price/Sq.Ft.<span style="color: Red">*</span>
</td>
<td>
<asp:TextBox ID="txtPricePerSqFt" runat="server" autocomplete="off" MaxLength="10"></asp:TextBox><p>
</p>
</td>
</tr>
<tr>
<td>
CC Price/Sq.Ft.<span style="color: Red">*</span>
</td>
<td>
<asp:TextBox ID="txtCCPricePerSqFt" runat="server" autocomplete="off" MaxLength="10"></asp:TextBox><p>
</p>
</td>
<td>
Total Price (in lacs)<span style="color: Red">*</span>
</td>
<td>
<asp:TextBox ID="txtTotalPrice" runat="server" autocomplete="off" MaxLength="10"></asp:TextBox><p>
</p>
</td>
</tr>
<tr>
<td id="thIsActHed" runat="server">
Active
<asp:HiddenField ID="hdnPropertyConfigID" runat="server" />
<asp:HiddenField ID="hdnIndex" runat="server" />
</td>
<td id="tdIsActchk" runat="server">
<asp:CheckBox ID="chkConfigVisible" runat="server" CssClass="checklist" /><p>
</p>
</td>
<td id="tdbtnConfig" runat="server" colspan="2">
<div class="btnHold">
<asp:Button ID="btnConfigSubmit" runat="server" Text="Add" OnClientClick="return ValidatePropertyConfig();"
CssClass="sendBtn" OnClick="btnConfigSubmit_Click" />
<asp:Button ID="btnUpdateConfig" runat="server" OnClick="btnUpdateConfig_Click" OnClientClick="return ValidatePropertyConfig();"
CssClass="sendBtn" Text="Update" Visible="False" />
<asp:Label ID="lblerrconfig" CssClass="errormsg" runat="server"></asp:Label>
</div>
</td>
</tr>
<tr>
<td colspan="4">
<div class="pHold">
<div class="gridH">
<asp:GridView ID="gvPropertyConfig" runat="server" AutoGenerateColumns="False" OnRowCommand="gvPropertyConfig_RowCommand"
OnRowDataBound="gvPropertyConfig_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="No Of Bedrooms" ItemStyle-CssClass="txtLT">
<ItemTemplate>
<asp:Label ID="lblno_of_bedrooms" runat="server" Text='<%# Eval("room_no") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Scalable Area" ItemStyle-CssClass="txtRT">
<EditItemTemplate>
<asp:TextBox ID="txtscalable_area" runat="server" Text='<%# Eval("scalable_area") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblscalable_area" runat="server" Text='<%# Eval("scalable_area") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Carpet Area" ItemStyle-CssClass="txtRT">
<EditItemTemplate>
<asp:TextBox ID="txtcarpet_area" runat="server" Text='<%# Eval("carpet_area") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblcarpet_area" runat="server" Text='<%# Eval("carpet_area") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price/SqFt." ItemStyle-CssClass="txtRT">
<EditItemTemplate>
<asp:TextBox ID="txtprice_per_sq_ft" runat="server" Text='<%# Eval("price_per_sq_ft") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblprice_per_sq_ft" runat="server" Text='<%# Eval("price_per_sq_ft") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CC Price/SqFt." ItemStyle-CssClass="txtRT">
<EditItemTemplate>
<asp:TextBox ID="txtcc_price_per_sq_ft" runat="server" Text='<%# Eval("cc_price_per_sq_ft") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblcc_price_per_sq_ft" runat="server" Text='<%# Eval("cc_price_per_sq_ft") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total Price (in lacs)" ItemStyle-CssClass="txtRT">
<EditItemTemplate>
<asp:TextBox ID="txttotal_price" runat="server" Text='<%# Eval("total_price") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbltotal_price" runat="server" Text='<%# Eval("total_price") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="" ItemStyle-CssClass="txtLT">
<ItemTemplate>
<asp:ImageButton runat="server" ID="btnEditItem" CssClass="edBtn" ImageUrl="~/Admin/Includes/Images/edit.png"
ToolTip="Edit Item" CommandName="EditItem" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
<asp:ImageButton runat="server" ID="btnDeletetem" CssClass="edBtn" ImageUrl="~/Admin/Includes/Images/delete.png"
CommandName="DeleteItem" ToolTip="Delete Item" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</div>
</td>
</tr>
</table>
</div>
</ContentTemplate>
</asp:UpdatePanel>
Use the "C" parameter in the ToString function, and make sure you set the globalaztion attributes.
string parseValueIntoCurrency(double number) {
// set currency format
string curCulture = Thread.CurrentThread.CurrentCulture.ToString();
System.Globalization.NumberFormatInfo currencyFormat = new
System.Globalization.CultureInfo(curCulture).NumberFormat;
currencyFormat.CurrencyNegativePattern = 1;
return number.ToString("c", currencyFormat);
}
If you want to use a different Culture (say you're in USA, and you want the Indian format) then just use the appropriate CultureInfo element rather than getting it out of the current thread.
EXTRA INFO DUE TO OP EDIT
All right, what you're wanting to do to get this into your grid, is to create a PROTECTED function which takes in the number to be converted, and returns the converted string (this is basically the code above.
Now, on the ASPX side, you need to use that function in your grid view.
So, instead of this:
<asp:TemplateField HeaderText="Total Price (in lacs)" >
<EditItemTemplate>
<asp:TextBox ID="txttotal_price" runat="server"
Text='<%# Eval("total_price") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbltotal_price" runat="server"
Text='<%# Eval("total_price") %>'> />
</ItemTemplate>
</asp:TemplateField>
you'll use this templatefield:
<asp:TemplateField HeaderText="Total Price (in lacs)" >
<EditItemTemplate>
<asp:TextBox ID="txttotal_price" runat="server"
Text='<%# Eval("total_price") %>' />
</EditItemTemplate>
<ItemTemplate>
<%# parseValueIntoCurrency(Eval("total_price")) %>'>
</ItemTemplate>
</asp:TemplateField>
Note, two things. The first is that I'm still passing the UNFORMATTED value into the EDIT TEMPLATE, and that I'm not instantiating an extra LABEL in the ITEM TEMPLATE.
The reason I'm not doing the extra label, is because we just don't need it in there. That's just a bit more processor/memory overhead that you just don't need to incur.
As for passing the unformatted value to the text field, that's because it'll ultimately be easier to validate without having to parse out the commas and other string elements.
I have the following databound DataList inside an UpdatePanel which updates whenever a selection is made from a DropDown menu.
However, if nothing is retrieved from the db table, I get a blank section.
What I would like to do is display the same table which is inside the ItemTemplate along with text - i.e. 'Admin Not Found', 'Email Not Found'....etc for the EmptyDataTempate...
I've noticed that the EmptyDataTemplate doesn't exist for a DataList, but I don't want to use a different control.
Is there a way to do this? Sample code appreciated. Thanks!
<asp:DataList ID="DataList" runat="server">
<ItemTemplate>
<table>
<tr>
<td class="style1">
Company Admin:
</td>
<td>
<asp:TextBox Text='<%# Eval("CompanyAdmin") %>' CssClass="input input1" ID="co_admin"
Width="150" runat="server" ReadOnly="True" />
</td>
</tr>
<tr>
<td>
Admin Email:
</td>
<td>
<asp:TextBox Text='<%# Eval("AdminEmail") %>' CssClass="input input1" ID="ad_email"
Width="150" runat="server" ReadOnly="True" />
</td>
</tr>
<tr>
<td>
Company Email:
</td>
<td>
<asp:TextBox Text='<%# Eval("CompanyEmail") %>' CssClass="input input1" ID="co_email"
Width="150" runat="server" ReadOnly="True" />
</td>
</tr>
<tr>
<td>
Telephone:
</td>
<td>
<asp:TextBox Text='<%# Eval("Telephone") %>' CssClass="input input1" ID="telephone"
Width="150" runat="server" ReadOnly="True" />
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
You can add a simple function that return a msg if the field is null.
You call a function like
<%#GetWithMsg(Container.DataItem, "CompanyEmail", "e-mail n/a")%>
for example
<asp:TextBox Text='<%# GetWithMsg(Container.DataItem, "CompanyEmail", "e-mail n/a") %>' CssClass="input input1" ID="co_email"
Width="150" runat="server" ReadOnly="True" />
and the code behind.
protected string GetWithMsg(object oItem, string cField, string TheMsg)
{
var TheData = DataBinder.Eval(oItem, cField);
if(TheData == null)
return TheMsg;
else
return TheData.ToString();
}
not tested but mybe you can try
'<%# !string.IsNullOrEmpty(Eval("CompanyEmail").ToString()) ? Eval("CompanyEmail") : "Email Not Found" %>'
explicit casting might be better in terms of performance than eval though
e.g.
'<%# !string.IsNullOrEmpty(((System.Data.DataRowView)Container.DataItem)["CompanyEmail"].ToString()) ? ((System.Data.DataRowView)Container.DataItem)["CompanyEmail"].ToString() : "Email Not Found" %>'
hope itll help
Sample Edit:
protected void BindData()
{
DataTable dt = DAL.GetData(...
if(dt.Rows.Count == 0)
{
dt.Rows.Add(dt.NewRow());
}
DataList.DataSource = dt;
DataList.DataBind();
}