Clean Text in FCKeditor textbox - c#

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.

Related

How to delete a row from GridView without affecting the Database

I am populating a Gridview using a form with the help of AJAX.
I want to add a delete button to each row and whendelet button is clicked that row should be deleted from GridView (not hidden).
Here is my aspx code:
<asp:Content ID="Content2" ContentPlaceHolderID="Nav" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
<table>
<tr>
<td class="auto-style1">
<asp:Label ID="LabelFirstName" runat="server" Text="First Name"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBoxFirstName" runat="server" CssClass="auto-style2"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style1">
<asp:Label ID="LabelLastName" runat="server" Text="Last Name"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBoxLastName" runat="server"></asp:TextBox>
</td>
</tr>
</table>
<br /><br />
<asp:Button ID="ButtonSearch" runat="server" Text="Search" CssClass="auto-style3" Width="93px" OnClick="ButtonSearch_Click" />
<br /><br />
<asp:Label ID="LabelNoRows" runat="server" Text="Sorry, we couldn't find any data with this Name." Visible="false" ForeColor="Red"></asp:Label>
<asp:Panel ID="PanelAbsenceInfo" runat="server" Visible="false">
<table>
<tr>
<td class="auto-style4">
<asp:Label ID="LabelFname" runat="server" Text="First Name:"></asp:Label>
</td>
<td>
<asp:Label ID="LabelGetFirstName" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td class="auto-style4">
<asp:Label ID="LabelLname" runat="server" Text="Last Name"></asp:Label>
</td>
<td>
<asp:Label ID="LabelGetLname" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td class="auto-style4">
<asp:Label ID="LabelEmail" runat="server" Text="Email"></asp:Label>
</td>
<td>
<asp:Label ID="LabelGetEmail" runat="server"></asp:Label>
</td>
</tr>
<asp:UpdatePanel ID="UpdatePanelInfo" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<tr>
<td class="auto-style4">
<asp:Label ID="LabelPersonal" runat="server" Text="Personal Days Approved" ></asp:Label>
</td>
<td>
<asp:Label ID="LabelGetPersonal" runat="server" ></asp:Label>
</td>
</tr>
<tr>
<td class="auto-style4">
<asp:Label ID="LabelOther" runat="server" Text="Other Days Approved"></asp:Label>
</td>
<td>
<asp:Label ID="LabelGetOther" runat="server" ></asp:Label>
</td>
</tr>
<tr>
<td class="auto-style4">
<asp:Label ID="LabelTotalDays" runat="server" Text="Total Days Approved" ></asp:Label>
</td>
<td>
<asp:Label ID="LabelgetTotaldays" runat="server" ></asp:Label>
</td>
</tr>
</table>
<br /><br />
<asp:GridView ID="GridViewViewAllRequests" runat="server" AutoGenerateColumns="False" DataKeyNames="id"
OnRowCommand="GridViewViewAllRequests_RowCommand">
<Columns>
<asp:BoundField DataField="scrap" Visible ="false" />
<asp:BoundField DataField="isApproved" Visible="false" />
<asp:BoundField HeaderText="Date of Absence" DataField="requestedDate" DataFormatString="{0:MM/dd/yyyy}" />
<asp:BoundField HeaderText="Rotation Period" DataField="rotationPeriod" />
<asp:BoundField HeaderText="Reason" DataField="reason" />
<asp:BoundField HeaderText="Days Missed" DataField="daysMissed" />
<asp:BoundField HeaderText="Department" DataField="departmentName" />
<asp:BoundField HeaderText="Course" DataField="courseName" />
<asp:TemplateField HeaderText="Approved/Declined">
<ItemTemplate>
<asp:Label ID="LabelApproveorDecline" runat="server" Text='<%# Eval("isApproved") == null ? "Decision not yet made." : ((bool)Eval("isApproved") ? "Approved" : "Declined") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Scrap/Undo">
<ItemTemplate>
<asp:Button ID="ScrapButton" CommandArgument='<%# Eval("id") %>' runat="server" Text="Scrap" CommandName="Scrap" Visible='<%# !(bool)Eval("scrap") %>' />
<asp:Button ID="UndoButton" CommandArgument='<%# Eval("id") %>' runat="server" Text="Undo" CommandName="Undo" Visible='<%# (bool)Eval("scrap") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
<br /><br />
</asp:Content>
And here is my cs code:
public partial class AbsenceRequestMonitor : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ButtonSearch_Click(object sender, EventArgs e)
{
DoAction();
}
public Boolean ScraptheRequest(int id, bool action)
{
bool success = false;
success = DBOperation.ScrapAbsencedate(id, action);
return success;
}
protected void GridViewViewAllRequests_RowCommand(object sender, GridViewCommandEventArgs e)
{
//Determine the RowIndex of the Row whose Button was clicked.
int id = Convert.ToInt32(e.CommandArgument);
//Get the value of column from the DataKeys using the RowIndex.
// int id = Convert.ToInt32(GridViewViewAllRequests.DataKeys[rowIndex].Values[0]);
if(e.CommandName == "Scrap")
{
ScraptheRequest(id, true);
}
else if(e.CommandName == "Undo")
{
ScraptheRequest(id, false);
}
DoAction();
UpdatePanelInfo.Update();
}
public void DoAction()
{
string firstName = null;
string lastName = null;
firstName = TextBoxFirstName.Text.ToString();
lastName = TextBoxLastName.Text.ToString();
double PdCount = 0;
double OtherCount = 0;
if (firstName != null && lastName != null)
{
//gets student data from the Student Form
List<AbsenceMonitorData> l_studentAbsenceInfo = DBOperation.getStudentAbsenceInfo(firstName, lastName);
AbsenceMonitorData studentAbsenceInfo = l_studentAbsenceInfo.FirstOrDefault();
PdCount += l_studentAbsenceInfo.Where(x => x.reason == "Personal Day").Where(y => y.isApproved == true).Where(z => z.scrap == false).Select(a => a.daysMissed).Sum();
OtherCount += l_studentAbsenceInfo.Where(x => x.reason != "Personal Day").Where(y => y.isApproved == true).Where(z => z.scrap == false).Select(a => a.daysMissed).Sum();
GridViewViewAllRequests.DataSource = l_studentAbsenceInfo;
GridViewViewAllRequests.DataBind();
if (l_studentAbsenceInfo.Count > 0)
{
LabelGetPersonal.Text = PdCount.ToString();
LabelGetOther.Text = OtherCount.ToString();
LabelgetTotaldays.Text = (PdCount + OtherCount).ToString();
LabelGetFirstName.Text = studentAbsenceInfo.firstName.ToString();
LabelGetLname.Text = studentAbsenceInfo.lastname.ToString();
LabelGetEmail.Text = studentAbsenceInfo.studentEmail.ToString();
PanelAbsenceInfo.Visible = true;
LabelNoRows.Visible = false;
}
else
{
LabelNoRows.Visible = true;
}
}
}
}
Right now i was using the Scrap/Undo button which i want to replace it with a Delete button.
Also when i delete the row the count should be affected. (ie. Personal Days Approved, Other Days Approved and Total Days Approved)
The image shows that when i type the name and hit search, GridView is obtained.
I need to be able to delete rows from that gridview.
GridView

How do you get the text from a label and store it as a variable?

I have an asp ListView displaying the data of all users in a SQL table. I want to be able to click a button beside the users details to store their UserID in a variable for further use.
I have no idea how to get the label text from the selected user and store it as a variable in the C# code behind file.
Front End:
<ItemTemplate>
<tr style="">
<td>
<asp:Label Text='<%# Eval("User_Id") %>' runat="server" ID="User_IdLabel" />
</td>
<td>
<asp:Label Text='<%# Eval("User_Firstname") + " " + Eval("User_Surname") %>' runat="server" ID="User_NameLabel" />
</td>
<td>
<asp:Label Text='<%# Eval("User_Email") %>' runat="server" ID="User_EmailLabel" />
</td>
<td class="text-center">
<asp:CheckBox Checked='<%# Eval("User_ScrumMaster") %>' runat="server" ID="User_ScrumMasterCheckBox" Enabled="false" />
</td>
<td class="text-center">
<asp:CheckBox Checked='<%# Eval("User_Developer") %>' runat="server" ID="User_DeveloperCheckBox" Enabled="false" />
</td>
<td class="text-center">
<asp:CheckBox Checked='<%# Eval("User_ProductOwner") %>' runat="server" ID="User_ProductOwnerCheckBox" Enabled="false" />
</td>
<td>
<asp:Button ID="AddUserButton" CssClass="btn btn-danger btn-block" runat="server" Text="Add User" onclick="AddUserButton_Click"/>
</td>
</tr>
</ItemTemplate>
Code Behind:
protected void AddUserButton_Click(object sender, EventArgs e)
{
String projectId = Request.QueryString["Project_id"];
String userId = this.User_NameLabel.Text;
// INSERT INTO ProjectTeam WHERE Project_Id = projectId AND User_Id = userId etc.;
}
I'm really at a loss here all the solutions I've looked up involve only static data and I'm really not sure what to do. Thanks in advance for any help you can provide.
In your ASPX add a CommandArgumand attribute to your button that will hold the user id:
<asp:Button ID="AddUserButton" CssClass="btn btn-danger btn-block"
runat="server" Text="Add User" onclick="AddUserButton_Click"
Commandargument="<%# Eval("User_Id") %>"/>
In your code behind, use the value passed in the CommandArgument:
protected void AddUserButton_Click(object sender, EventArgs e)
{
String projectId = Request.QueryString["Project_id"];
String userId = e.CommandArgument;
}
I think you are missing Button button = (sender as Button) and String userId = button.CommandArgument in your code.
you can try following to make it working.
<asp:Button ID="AddUserButton" CssClass="btn btn-danger btn-block"
runat="server" Text="Add User" onclick="AddUserButton_Click"
Commandargument="<%# Eval("User_Id") %>"/>
protected void AddUserButton_Click(object sender, EventArgs e)
{
String projectId = Request.QueryString["Project_id"];
Button button = (sender as Button);
String userId = button.CommandArgument;
}

listview item said to be "Null"

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

Literal Control in ASP.NET HTML Table

I have a HTML table like following in my aspx markup file.
<table runat="server" id="tblSubstantialOwners">
<tr id="tr_header" runat="server">
<td>
<asp:Label ID="lblOnwerName" Text="Name" runat="server"></asp:Label>
</td>
<td>
<asp:Label ID="lblOwnerAddress" Text="Address" runat="server"></asp:Label>
</td>
<td>
<asp:Label ID="lblOwnerTIN" Text="TIN" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtOwnerName1" Width="80px" runat="server" AutoCompleteType="Disabled"
MaxLength="20" />
</td>
<td>
<asp:TextBox ID="txtOwnerAddress1" Width="80px" runat="server" AutoCompleteType="Disabled"
MaxLength="20" />
</td>
<td>
<asp:TextBox ID="txtOwnerTIN1" Width="80px" runat="server" AutoCompleteType="Disabled"
MaxLength="20" />
</td>
</tr>
</table>
but when I parse through c# asp.net code, I get literal control in each cell of html table row along with my asp.net control i.e. TextBox. Why is that?
foreach (HtmlTableRow row in htmlTable.Rows)
{
if (row.ID != "tr_header")
{
for (int count = 0; count < row.Cells.Count; count++)
{
string value = string.Empty;
HtmlTableCell cell = row.Cells[count];
foreach (Control conrol in cell.Controls)
{
if (conrol.GetType() != typeof(LiteralControl))
{
if (conrol.GetType() != typeof(Label))
{
if (conrol.GetType() == typeof(TextBox))
{
datarow[count] = ((TextBox)conrol).Text;
}
}
}
}
}
}
}
it appears that you are mixing Html Tables and ASP.NET.
If you change your Html Table to:
<asp:Table runat="server" ID="tblSubstantialOwners">
<asp:TableHeaderRow ID="tr_header" runat="server">
<asp:TableHeaderCell>
<asp:Label ID="lblOnwerName" Text="Name" runat="server"></asp:Label>
</asp:TableHeaderCell>
<asp:TableHeaderCell>
<asp:Label ID="lblOwnerAddress" Text="Address" runat="server"></asp:Label>
</asp:TableHeaderCell>
<asp:TableHeaderCell>
<asp:Label ID="lblOwnerTIN" Text="TIN" runat="server"></asp:Label>
</asp:TableHeaderCell>
</asp:TableHeaderRow>
<asp:TableRow>
<asp:TableCell>
<asp:TextBox ID="txtOwnerName1" Width="80px" runat="server" AutoCompleteType="Disabled"
MaxLength="20" />
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtOwnerAddress1" Width="80px" runat="server" AutoCompleteType="Disabled"
MaxLength="20" />
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtOwnerTIN1" Width="80px" runat="server" AutoCompleteType="Disabled"
MaxLength="20" />
</asp:TableCell>
</asp:TableRow>
</asp:Table>
And your code to:
protected void btnSubmit_Click(object sender, EventArgs e)
{
foreach (System.Web.UI.WebControls.TableRow row in tblSubstantialOwners.Rows)
{
if (row.GetType() == typeof(TableRow))
{
for (int count = 0; count < row.Cells.Count; count++)
{
TableCell cell = row.Cells[count];
datarow[count] = cell.Controls.OfType<TextBox>().FirstOrDefault().Text;
}
}
}
}
You can get to the controls you have in your table cells directly, either by name, ordinality, or type...

Changing Readonly attribute of Textbox within a repeater

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.

Categories