I know how to use a String variable from code to behind and say display that string on the web page. What I want to do is similar except that instead of displaying a string, I want to pass the boolean value from code behind, to the ASP.NET page so that its' true / false value can control the Print button (true / false) in the ReportViewer. My Diagnostic works in that it displays the string "True" or "False", which ever is correct. The "ShowPrintButton" and "ShowExportControls" just don't work though and the buttons are not enabled. What do I need to do here? I think the value is being passed but perhaps it's being passed as a string and I need to do something to make it pass as a Boolean....
Here's the code ...
Code Behind:
//Variables
public Boolean exportEnabled { get; set; }
public Boolean printEnabled { get; set; }
//Page Load
protected void Page_Load(object sender, EventArgs e)
{
// Add a handler for SubreportProcessing
reportViewerPrintAndExport.LocalReport.SubreportProcessing +=
new SubreportProcessingEventHandler(LocalReport_SubreportProcessing);
if (!IsPostBack)
{
// Display the report
DisplayReport(Session[SessionKeys.KEY_CERT_NO].ToString(), (CalibrationType)Session[SessionKeys.KEY_CERT_TYPE]);
}
DataBind();
}
private void DisplayReport(string certNo, CalibrationType calType)
{
string[] rolesList = Roles.GetRolesForUser();
//manage print and export buttons.
if ((rolesList.Contains("admin")) || (rolesList.Contains("Admin")))
{
exportEnabled = true;
printEnabled = true;
}
else if ((rolesList.Contains("Operator")) || (rolesList.Contains("operator")))
{
exportEnabled = false;
printEnabled = false;
}
}
aspx:
<!-- DIAGNOSTIC -->
<asp:label runat="server" text="-" /><asp:label runat="server" text="<%# printEnabled %>" /><asp:label runat="server" text="-" />
<asp:Panel ID="ReportPanelPrintAndExport" runat="server" HorizontalAlign="Left">
<!--Why does this not work? -->
<rsweb:ReportViewer ShowPrintButton="<%# printEnabled %>" ShowExportControls="<%# exportEnabled %>" ID="reportViewerPrintAndExport" runat="server" Height="100%" Width="100%"
ShowBackButton="False" ZoomMode="FullPage"
ShowRefreshButton="False" ProcessingMode="Local">
</rsweb:ReportViewer>
In your code behind simply set that property wherever you want to
if ((rolesList.Contains("admin")) || (rolesList.Contains("Admin")))
{
reportViewerPrintAndExport.ShowPrintButton = true;
reportViewerPrintAndExport.ShowExportControls = true;
}
else if ((rolesList.Contains("Operator")) || (rolesList.Contains("operator")))
{
reportViewerPrintAndExport.ShowPrintButton = false;
reportViewerPrintAndExport.ShowExportControls = false;
}
There is no need to try to do this on the client side.
Related
I have a Repeater with a certain DataSource (consisting of a list of images). The Repeater holds ImageButtons.
The aspx:
<asp:Panel ID="panSearch" runat="server" ScrollBars="Vertical" BorderColor="#333333" BorderStyle="Inset" Width="500" Height="200">
<asp:Repeater ID="Repeater" runat="server">
<ItemTemplate>
<asp:ImageButton OnClick="imgSearchResult_Click" BackColor="#333333" ID="imgSearchResult" height="32" width="32" runat="server" ImageUrl='<%# Eval("ImageUrl") %>'/>
</ItemTemplate>
</asp:Repeater>
</asp:Panel>
Additionally, I have a TextBox, which has a TextChanged-event in code-behind. I do a few things in there and at the end, my Repeater's DataSource will be overwritten with a new List of images (those images are put into the ImageButtons).
Repeater.DataSource = ImageList;
Repeater.DataBind();
My problem: Whenever my Repeater.DataSource is changed, it "clicks" the first ImageButton inside the Repeater. How do I prevent that from happening?
Full code:
My TextBox:
<asp:TextBox ID="textSearch" runat="server" Width="80" OnTextChanged="textSearch_TextChanged" ForeColor="Black" />
My TextChanged event:
protected void textSearch_TextChanged(object sender, EventArgs e)
{
string[] filesindirectory = Directory.GetFiles(Server.MapPath("~/Images/ORAS"));
List<System.Web.UI.WebControls.Image> ImageList = new List<System.Web.UI.WebControls.Image>(filesindirectory.Count());
foreach (string item in filesindirectory)
{
System.Web.UI.WebControls.Image myImage= new System.Web.UI.WebControls.Image();
myImage.ImageUrl = (String.Format("~/Images/ORAS/{0}", System.IO.Path.GetFileName(item)));
ImageList.Add(myImage);
}
Repeater.DataSource = ImageList;
Repeater.DataBind();
}
When I click on an ImageButton inside the Repeater (which is executed when the text in my TextBox is changed):
protected void imgSearchResult_Click(object sender, ImageClickEventArgs e)
{
var selectedImage = sender as ImageButton;
if (img1.ImageUrl == "~/Images/ORAS/Empty/000.png")
{
img1.ImageUrl = selectedImage.ImageUrl;
}
else if (img2.ImageUrl == "~/Images/ORAS/Empty/000.png")
{
img2.ImageUrl = selectedImage.ImageUrl;
}
else if (img3.ImageUrl == "~/Images/ORAS/Empty/000.png")
{
img3.ImageUrl = selectedImage.ImageUrl;
}
else if (img4.ImageUrl == "~/Images/ORAS/Empty/000.png")
{
img4.ImageUrl = selectedImage.ImageUrl;
}
else if (img5.ImageUrl == "~/Images/ORAS/Empty/000.png")
{
img5.ImageUrl = selectedImage.ImageUrl;
}
else if (img6.ImageUrl == "~/Images/ORAS/Empty/000.png")
{
img6.ImageUrl = selectedImage.ImageUrl;
}
else
{
ErrorMessage("Please remove one Image first!", true);
}
}
Pageload:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
img1.ImageUrl = "~/Images/ORAS/Empty/000.png";
img2.ImageUrl = "~/Images/ORAS/Empty/000.png";
img3.ImageUrl = "~/Images/ORAS/Empty/000.png";
img4.ImageUrl = "~/Images/ORAS/Empty/000.png";
img5.ImageUrl = "~/Images/ORAS/Empty/000.png";
img6.ImageUrl = "~/Images/ORAS/Empty/000.png";
LoadImages();
}
}
(LoadImages is almost 1:1 what's in my TextChanged function)
I really am not sure how (why) ASP.NET WebForms does it, but if you hit Enter and the form posts back, it will find the first control that implements IPostBackEventHandler and execute whatever event is bound to that. ImageButton implements it and so that's why it keeps firing the click event even though you didn't click on it. And, once again, only if you hit Enter.
I think that behaviour happens because the data posted back - __EVENTTARGET and __EVENTARGUMENT - are empty. Then ASP.NET goes bonkers.
You can solve it by putting a dummy button at the top of the page (or masterpage) and hide it using the style attribute. so:
<asp:Button ID="dummy" runat="server" style="display:none" />
Then in the init or load of your page (or masterpage) put
Form.DefaultButton = dummy.UniqueID;
That will force the button to capture the enter press instead of the arbitrary image button.
I have created custom web control textbox which is working fine and its code is as below:
public class ReqTextBox : TextBox
{
private RequiredFieldValidator req;
public string ErrMsg { get; set; }
protected override void OnInit(EventArgs e)
{
this.CssClass = "inp-form";
req = new RequiredFieldValidator();
req.ControlToValidate = this.ID;
req.ErrorMessage = string.IsNullOrEmpty(this.ErrMsg) ? "*" : this.ErrMsg;
req.Display = ValidatorDisplay.Dynamic;
//req.EnableClientScript = true;
if (!string.IsNullOrEmpty(this.ValidationGroup))
req.ValidationGroup = this.ValidationGroup;
Controls.Add(req);
//base.OnInit(e);
}
protected override void Render(HtmlTextWriter w)
{
base.Render(w);
req.RenderControl(w);
}
}
This is working fine with following code:
<Mas:ReqTextBox runat="server" ID="txtCustBankCode" Width="236px" ValidationGroup="vmas" ErrMsg="Enter BankName"></Mas:ReqTextBox>
<asp:ImageButton runat="server" ID="ibtnUpdate" OnClick="ibtnUpdate_Click" ToolTip="Update" AlternateText="Update" ImageUrl="../Resources/Images/Update2.gif" ValidationGroup="vmas" />
Here it works fine. Now if i add onclientclick event on button then it will not check if textbox is empty or not. In both return true and false in Valid() function it's not working.
<asp:ImageButton runat="server" ID="ibtnUpdate" OnClick="ibtnUpdate_Click" ToolTip="Update" AlternateText="Update" onClientClick="return Valid();" ImageUrl="../Resources/Images/Update2.gif" ValidationGroup="vmas" />
What am i missing...?
req.EnableclientScript = true/false;
did not help me.
Need Help.
Thanks.
EDIT: I need to use this Customcontrol, so that user need to enter some data and for those entered data, i need to validate with javascript function. Sorry for late EDIt.
Use customvalidator with custom clientvalidation function:
<script type="text/javascript">
function ClientValidate(source, arguments) {
if (arguments.Value === "foo") {
arguments.IsValid = true;
} else {
arguments.IsValid = false;
}
}
</script>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="Invalid entry" ControlToValidate="TextBox1"
ClientValidationFunction="ClientValidate"></asp:CustomValidator>
<asp:Button ID="Button1" runat="server" Text="Button" />
Read more from here .
I have validation as below but only like to triggered if the checkbox is ticked.
<!-- TextBox and its validator -->
Name: <asp:TextBox ID="TextBox1" runat="server" />
<asp:RequiredFieldValidator runat="server"
ID="RequiredFieldValidator1"
Text="*"
ErrorMessage="Name is required"
ControlToValidate="TextBox1" />
Can I get it done using asp:RequiredFieldValidator?
I only like to validate if a certain condition matched.
Currently it is validating every time the 'Save' button is clicked.
Use a custom validator instead:
<asp:CustomValidator ID="cv1" runat="server"
ErrorMessage="Name is required"
Text="*"
ControlToValidate="TextBox1"
ValidateEmptyText="True"
ClientValidationFunction="validate" />
and the script (just checking a checkbox and the textbox value as example; you can use custom logic):
<script type="text/javascript">
function validate(s,args){
if(document.getElementById("<%= checkboxId.ClientID %>").checked){
args.IsValid = args.Value != '';
}
else{
args.IsValid = true;
}
}
</script>
This will do the client-side validation. If you need server validation also, add the OnServerValidate attribute, and a handler on code behind. See here for details.
I solved this easily by adding the following javascript on Client side.
ValidatorEnable(document.getElementById("RequiredFieldValidator1"), true); or
ValidatorEnable(document.getElementById("RequiredFieldValidator2"), false);
You can also try this one
protected void CheckBox_CheckedChanged(object sender, EventArgs e)
{
if(CheckBox.Checked)
{
RequiredFieldValidator1.Enabled = true;
RequiredFieldValidator1.ValidationGroup = "anything";
Button1.ValidationGroup = "anything";// your save button
}
else
{
RequiredFieldValidator1.Enabled = false;
RequiredFieldValidator1.ValidationGroup = string.Empty;
Button1.ValidationGroup = string.Empty; // save button
}
}
Try this...
protected void RequiredFieldValidator1_Load(object sender, EventArgs e)
{
if (CheckBox1.Checked == true)
{
RequiredFieldValidator1.Enabled = true;
}
else if (CheckBox1.Checked == false)
{
RequiredFieldValidator1.Enabled = false;
}
}
You can enabled/Disabled the RequiredFieldValidator from the Javascript/jQuery.
For your condition, When Checkbox is checked :- Just call the javascript function to enabled the RequiredFieldValidator and when its Uncheck just disabled the RequiredFieldValidator.
For other Conditions like Dropdown index change, textbox value change and radio button selection change you can call its onchange, onblur, onclick respectively and
After executing the required condition you can Enabled/Disabled the RequiredFieldValidator.
Hope this help you.
I have a gridview. The gridview has a textbox multiline that keeps an text. After that I have a column with imagebutton named approved, and one named not approved. I want to force the user before click approved or not approved to read the text inside the multiline box. How can I achieve this programmatically? I know I should create a Rowdatabound Event, but what I should do with the code? I am using c# ASP.NET web application.
I know you can track the scroll bar of the browser using javascript but I've personally never come across similar functionality for a text box. I would suggest trying a slightly different approach, why don't you add an extra column to you grid view which has a check box control for - I've read and accepted the agreement. And the Approve button will only be enabledd when the checkbox is checked, here's an example:
ASPX:
<div>
<asp:ScriptManager ID="sm" runat="server" />
<asp:UpdatePanel ID="updatePanel" runat="server">
<ContentTemplate>
<asp:GridView ID="grid" runat="server" AutoGenerateColumns="false" OnRowDataBound="grid_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox TextMode="MultiLine" runat="server" ID="txtAgreement" Text='<%# Eval("Agreement") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
I have read and accepted the agreement
<asp:CheckBox ID="chkAgreement" AutoPostBack="true" runat="server" OnCheckedChanged="CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnAccept" runat="server" Text="Accept" OnClick="Accept" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
Code behind:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var items = new List<License> { new License { Agreement = "Agreement 1" }, new License { Agreement = "Agreement 2" } };
grid.DataSource = items;
grid.DataBind();
}
}
protected void Accept(object sender, EventArgs e)
{
}
protected void grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
(e.Row.FindControl("btnAccept") as Button).Enabled = false;
}
protected void CheckedChanged(object sender, EventArgs e)
{
var chkAgreement = sender as CheckBox;
Button btnAccept = null;
if (chkAgreement != null)
{
var row = chkAgreement.Parent.Parent as GridViewRow;
btnAccept = row.FindControl("btnAccept") as Button;
if (btnAccept != null)
if (chkAgreement.Checked)
btnAccept.Enabled = true;
else
btnAccept.Enabled = false;
}
}
}
public class License
{
public string Agreement { get; set; }
}
I have an ASP:Repeater Which I would like to display a list of check boxes in. These check boxes are related to a list of user preferences and the users resulting answer. See Code Bellow.
I would like to add do one of the following if possible
Option 1: It would be great if I could use the Event in the Repeater:OnItemCommand(...) to fire if any of the items change. It would seem to me that this event will only fire if there is a Button | LinkButton | ImageButton item in the list. IE it will not fire if I put in a check box with AutopostBack="True"
Option 2: Is there a way I could attach a method to an Event of CheckBox:CheckChanged I would need to pass this method a parameter saying which question/answer combo to change.
Option 3: Its your answer if you know an easier way that would be awesome.
The Code:
<asp:Repeater ID="RPTprefs" runat="server" DataSourceID="getAnswers" OnItemCommand="RPTprefs_ItemCommand">
<ItemTemplate>
<li><asp:CheckBox ID='questionID' runat="server"
Checked='<%# Eval("pr.up_is_selected") %>'
Text='<%# Eval("prp.prefs_question") %>'
AutoPostBack="true"
OnCheckedChanged="CheckChanged" /></li>
</ItemTemplate>
</asp:Repeater>
Thanks in advance
Here is what I came up with, which is basically your option #2.
In the ItemTemplate of the repeater, I use a Literal control (Visible set to false) which has the argument you wish to pass to the CheckedChanged function. The reason for using a control is because the control will retain its value in the ViewState after a post back, whereas the original data source for the Repeater will be lost.
In the OnItemCreated function, I bind the CheckChanged function for all of the check boxes to pass in the right argument. Here's my complete example. In this case, I want to pass the Id property of my data to the CheckChanged function.
Markup:
<asp:Repeater ID="Repeater1" runat="server" OnItemCreated="ItemCreated">
<ItemTemplate>
<asp:Literal ID="litArg" runat="server" Visible="false" Text='<%# Eval("Id") %>'>
</asp:Literal><%# Eval("Name") %>
<asp:CheckBox ID="chkCool" runat="server" AutoPostBack="true" Checked='<%# Eval("IsCool") %>' /><br />
</ItemTemplate>
</asp:Repeater>
Code behind:
public class SomeClass
{
public SomeClass(bool c, string n, int id)
{
IsCool = c;
Name = n;
Id = id;
}
public bool IsCool { get; set; }
public string Name { get; set; }
public int Id { get; set; }
}
.
.
.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<SomeClass> people = new List<SomeClass>();
people.Add(new SomeClass(true, "Will", 666));
people.Add(new SomeClass(true, "Dan", 2));
people.Add(new SomeClass(true, "Lea", 4));
people.Add(new SomeClass(false, "Someone", 123));
Repeater1.DataSource = people;
Repeater1.DataBind();
}
}
private void CheckChanged(int id)
{
Response.Write("CheckChanged called for item #" + id.ToString());
}
protected void ItemCreated(object sender, RepeaterItemEventArgs e)
{
//this needs to be set again on post back
CheckBox chk = (CheckBox)e.Item.FindControl("chkCool");
Literal arg = (Literal)e.Item.FindControl("litArg");
Action<object, EventArgs> handler = (s, args) => CheckChanged(Convert.ToInt32(arg.Text));
chk.CheckedChanged += new EventHandler(handler);
}
Hope that helps.