Old Title: Prevent dynamically created control from retaining value
Old Info:
The reason I need to do this is because I am trying to create a work around for a required field validator for an Image control. The way my code works is I have a Image control beside a Button, a user clicks on the button and then is prompted to upload an image. I need to ensure that an image is uploaded before the user can move onto the next stage.
Since there is no required field validator for an image control, I created a textbox which is suppose to display the imageURL of the image control every time the image control is recreated on postbacks. However, the textbox always retains the value from the initial creation of the control.
* Note: all controls on the page are dynamically created.
The first thing I do is create the image control and add it to an HTML Table. This works fine. Right after that I find the table cell and add the textbox to the cell that has an image control:
HtmlTableCell tc = (HtmlTableCell)customProperties.FindControl("tcControl_" + (i + 1).ToString());
RadBinaryImage rbi = (RadBinaryImage)customProperties.FindControl("CustomControl" + (i + 1).ToString());
TextBox photoValue = new TextBox();
photoValue.ID = "CustomControl" + (i + 1).ToString() + "_txt";
photoValue.Text = rbi.imageUrl;
This occurs everytime I create all the controls. For all the controls they all retain their values, this is the only control which I don't want this to happen. Does anyone know of how this can be done? Or another way of validating an image control?
Thanks for your time,
All comments/answers are appreciated (:
SOLVED:
I created a modified version of a checkboxlist required field validator that I found here.
Here is the code: I replaced the namespace with ######## for security reasons.
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using Telerik.Web.UI;
namespace #######################################
{
public class RequiredFieldValidatorForImages :
System.Web.UI.WebControls.BaseValidator
{
private Control _ctrl;
public RequiredFieldValidatorForImages()
{
base.EnableClientScript = false;
}
protected override bool ControlPropertiesValid()
{
Control ctrl = FindControl(ControlToValidate);
if (ctrl != null)
{
_ctrl = (Control)ctrl;
return (_ctrl != null);
}
else
return false; // raise exception
}
protected override bool EvaluateIsValid()
{
try
{
Image rbi = (Image)_ctrl;
return rbi.ImageUrl != "~/images/noimages.jpg";
}
catch
{
RadBinaryImage rbi = (RadBinaryImage)_ctrl;
return rbi.ImageUrl != "~/images/noimages.jpg";
}
}
}
}
Solved:
I created a modified version of a checkboxlist required field validator that I found here.
Here is the code: I replaced the namespace with ######## for security reasons.
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using Telerik.Web.UI;
namespace #######################################
{
public class RequiredFieldValidatorForImages :
System.Web.UI.WebControls.BaseValidator
{
private Control _ctrl;
public RequiredFieldValidatorForImages()
{
base.EnableClientScript = false;
}
protected override bool ControlPropertiesValid()
{
Control ctrl = FindControl(ControlToValidate);
if (ctrl != null)
{
_ctrl = (Control)ctrl;
return (_ctrl != null);
}
else
return false; // raise exception
}
protected override bool EvaluateIsValid()
{
try
{
Image rbi = (Image)_ctrl;
return rbi.ImageUrl != "~/images/noimages.jpg";
}
catch
{
RadBinaryImage rbi = (RadBinaryImage)_ctrl;
return rbi.ImageUrl != "~/images/noimages.jpg";
}
}
}
}
Related
I am using below method to validate data within textbox in groupbox
so for improvement of user Feedback for example
message text Please enter First Name
where First Name is the label for textbox, so I used Textbox.Tag to store the name of textbox to achieve it since there is no link between the Textbox and it is Label
I search and found that I can use the Tag property to store anything but I wan to be sure of using it by the I told you about
Is there any problem with that ?
public int ValidateData()
{
foreach (Control cont in GB_PatientInfo.Controls)
{
if (cont is TextBox)
{
if (string.IsNullOrWhiteSpace(cont.Text.Trim()))
{
MessageBox.Show("enter data " + cont.Tag, "Message", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.RtlReading);
cont.BackColor = Color.Red;
cont.Focus();
return -1;
}
}
}
return 1;
}
Thanks
As you have read, you can store any type that derives from object (i.e. everything) in the Control.Tag property so storing the name of a label is fine.
The use of the Tag property does not influence your application. You can store whatever you want in there with no problem.
As it's already mentioned in other answers, it's OK to use Tag property to store any kind of additional information about the control, including a display name.
But have you ever noticed how ToolTip lets you to set ToolTip for your control at design-time?
A ToolTip, ErrorProvider or HelpProvider are examples of extender provider components. They add some properties to the controls at design-time. You also can create such component for DisplayName by implementing IExtenderProvider.
Example
The following code shows you how easily you can create a component called DisplayNameExtender. When you drop an instance of this component on the form, then a new property will be added to design-time of controls, you can set the value to the property
at design-time: DisplayName on diaplayNameExtender1.
Then at run-time, whenever you want to get the value of DisplayName for a control, it's enough to find it this way:
var displayName = displayNameExtender1.GetDisplayName(control);
Here is the code for DisplayNameExtender component:
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
[ProvideProperty("DisplayName", typeof(Control))]
public class DisplayNameExtender : Component, IExtenderProvider
{
private Hashtable displayNameValues = new Hashtable();
public bool CanExtend(object extendee)
{
return (extendee is Control && !(extendee is Form));
}
public string GetDisplayName(Control control)
{
if (displayNameValues.ContainsKey(control))
return (string)displayNameValues[control];
return null;
}
public void SetDisplayName(Control control, string value)
{
if (string.IsNullOrEmpty(value))
displayNameValues.Remove(control);
else
displayNameValues[control] = value;
}
}
Dear fellow programmers.
Currently my strings are loaded, and 5 buttons are created with these titles from the database.
Yet the buttons are not visible on the iOS app.
What am I missing.
I am using Xamarin.iOS and c#
Thanks in advance
using Foundation;
using UIKit;
using System.CodeDom.Compiler;
using System.Drawing;
using Ola.ServiceClients;
using System.Threading.Tasks;
using PortableRest;
using Ola.Shared.Models;
using System.Net.Http;
using System.Net.Http.Headers;
namespace Ola.iOS
{
partial class NavigationViewController : UIViewController
{
//private MenuItem[] menuItems;
private MenuItem[] drawerItems;
public string token = "";
public NavigationViewController(IntPtr handle)
: base(handle)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
LoadMenu();
}
public async void LoadMenu()
{
RestResponse<MenuItem[]> response = await NavigationClient.Current.GetMenu(token);
//HttpResponseHeaders responseHeaders = response.HttpResponseMessage.Headers;
//HttpRequestMessage requestMessage = response.HttpResponseMessage.RequestMessage;
if (response != null && response.Content != null && response.Content.Length > 0)
{
//menuItems = response.Content;
for (int i = 0; i < response.Content.Length; i++)
{
UIButton button = UIButton.FromType(UIButtonType.RoundedRect);
button.SetTitle(response.Content[i].Text, UIControlState.Normal);
this.Add(button);
System.Console.WriteLine("Button created");
}
System.Console.WriteLine();
}
}
}
}
Greetings
Dave
Add the following code to show your buttons:
this.View.AddSubview(button);
instead of:
this.Add(button);
Make sure you are setting button.Frame property, adding button to parent View and also you should try to set background color as by default its transparent.EditI'm not sure if that will make any difference but try to create buttons differently e.i var button = new UIButton(new RectangleF());And one more thing I'm thinking of may be transparency, make sure that parent View and buttons do not have alpha set to 0Edit 2One more thing ! Try wrap call where you adding buttons to view by calling it in InvokeOnMainThread(() =>
{
this.View.AddSubview(button);
});
method !
C# .Net fw 3.5, in winform in TabControl,
when the user tab out of the last control on a TabPage, then focus should moves to the next page, and focuses the first control in that page, how can i do it?
this is necessary for me because, in a master entry form, there is some compulsory questions which is placed out side of tabcontrol, and some controls which is not necessary all in tabcontrol,
if user visiting each control sequentially then focus should automatically move to next pages, if user want to fill only neccessory infos, then he can submit by clicking save button.
is any suggestion about this.
your question is not accurate
"C# .Net fw 3.5, in winform in TabControl, when the user tab out of the last control on a TabPage, then focus should moves to the next page, and focuses the first control in that page?"
is this a statement or question. I didnt understand. And what is the goal you need ?
If you want the user consequently visit the controls inside the consequent tabs by pressing tab key you can do it by keypressed event in tab control. In the keypressed event you can change the tab programatically.
hope it helps.
The code should be something like this.
Generate keypress event for your tabcontrol and monitor the press of TAB key.
private void tabControl1_KeyPress(object sender, KeyPressEventArgs e)
{
if(e.ToString().Equals("TAB") // I dont know what tab key returns. But is hould be something like this
{
tabControl1.SelectedTab = tabControl1.TabPages[1] ;
// now tabpage 2 has the focus
// You can also focus any control you want in here as follows:
tabControl1.TabPages[1].Control["control key"].Focus();
}
}
hope its clear enough
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel;
namespace CSBSSWControls
{
// Class inhertis TabControl
public class bssTabControl : TabControl
{
private bool AutoTab_;
[DefaultValue(false)]
public bool AutoTab { get { return AutoTab_; } set { AutoTab_ = value; } }
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
//property which determines auto change tabpages
if (AutoTab)
{
switch (keyData)
{
case Keys.Tab | Keys.Shift:
{
return SetNextTab(false);
}
case Keys.Tab:
{
return SetNextTab(true);
}
}
}
return base.ProcessCmdKey(ref msg, keyData);
}
private bool SetNextTab(bool Forward)
{
// getting cuurent active control
ContainerControl CC = this.FindForm();
Control ActC = null;
while (CC != null)
{
ActC = CC.ActiveControl;
CC = ActC as ContainerControl;
}
//checking, current control should not be tabcontrol or tabpage
if (ActC != null && !(ActC is TabPage) && !(ActC is bssTabControl))
{
//getting current controls next control if it is tab page then current control is surely that last control on that tab page
//if shift+tab pressed then checked its previous control, if it is tab page then current control is first control on the current tab page.
TabPage NC = ActC.FindForm().GetNextControl(ActC, Forward) as TabPage;
if (NC != null)
if (this.TabPages.Contains(NC))
if (Forward)
{
//selecting next tab page
this.SelectedTab = NC;
return true;
}
else
{
if (this.TabPages.IndexOf(NC) > 0)
{
//selecting pervious tab page
this.SelectedIndex = this.TabPages.IndexOf(NC) - 1;
return true;
}
}
}
return false;
}
}
}
I am using BuildManager Class to Load a dynamically generated ASPX File, please note that it does not have a corresponding .cs file.
Using Following code I am able to load the aspx file, I am even able to loop through the control collection of the dynamically created aspx file, but when I am assigning values to controls they are not showing it up. for example if I am binding the value "Dummy" to TextBox control of the aspx page, the textbox remains empty.
Here's the code that I am using
protected void Page_Load(object sender, EventArgs e)
{
LoadPage("~/Demo.aspx");
}
public static void LoadPage(string pagePath)
{
// get the compiled type of referenced path
Type type = BuildManager.GetCompiledType(pagePath);
// if type is null, could not determine page type
if (type == null)
throw new ApplicationException("Page " + pagePath + " not found");
// cast page object (could also cast an interface instance as well)
// in this example, ASP220Page is a custom base page
System.Web.UI.Page pageView = (System.Web.UI.Page)Activator.CreateInstance(type);
// call page title
pageView.Title = "Dynamically loaded page...";
// call custom property of ASP220Page
//pageView.InternalControls.Add(
// new LiteralControl("Served dynamically..."));
// process the request with updated object
((IHttpHandler)pageView).ProcessRequest(HttpContext.Current);
LoadDataInDynamicPage(pageView);
}
private static void LoadDataInDynamicPage(Page prvPage)
{
foreach (Control ctrl in prvPage.Controls)
{
//Find Form Control
if (ctrl.ID != null)
{
if (ctrl.ID.Equals("form1"))
{
AllFormsClass cls = new AllFormsClass();
DataSet ds = cls.GetConditionalData("1");
foreach (Control ctr in ctrl.Controls)
{
if (ctr is TextBox)
{
if (ctr.ID.Contains("_M"))
{
TextBox drpControl = (TextBox)ctr;
drpControl.Text = ds.Tables[0].Rows[0][ctr.ID].ToString();
}
else if (ctr.ID.Contains("_O"))
{
TextBox drpControl = (TextBox)ctr;
drpControl.Text = ds.Tables[1].Rows[0][ctr.ID].ToString();
}
}
}
}
}
}
}
I saw that you got part of your code from How To Dynamically Load A Page For Processing. Read the comments too as this one by Mike.
Invert this:
((IHttpHandler)pageView).ProcessRequest(HttpContext.Current);
LoadDataInDynamicPage(pageView);
To this:
LoadDataInDynamicPage(pageView);
((IHttpHandler)pageView).ProcessRequest(HttpContext.Current);
In this case changing the order of the calls does change the end result I think. The inverse of Commutativity property. :)
How can you create a C# Winforms control which goes out of the bounds of its region? Such as a drop down box. Kind of like if you had a DropDownBox in a Small Sized Panel.
Windows Forms doesn't support windows like that well, it is pretty fundamentally incompatible with the designer. Here's some code to get you started. You can't use this control in the designer, it must be created at run-time. You also must call its Dispose() method yourself.
using System;
using System.Drawing;
using System.ComponentModel;
using System.Windows.Forms;
public class MyListBox : ListBox {
private Control mParent;
private Point mPos;
private bool mInitialized;
public MyListBox(Control parent) {
mParent = parent;
mInitialized = true;
this.SetTopLevel(true);
parent.LocationChanged += new EventHandler(parent_LocationChanged);
mPos = mParent.Location;
}
public new Point Location {
get { return mParent.PointToClient(this.Location); }
set {
Point zero = mParent.PointToScreen(Point.Empty);
base.Location = new Point(zero.X + value.X, zero.Y + value.Y);
}
}
protected override Size DefaultSize {
get {
return mInitialized ? base.DefaultSize : Size.Empty;
}
}
protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) {
if (this.mInitialized)
base.SetBoundsCore(x, y, width, height, specified);
}
void parent_LocationChanged(object sender, EventArgs e) {
base.Location = new Point(base.Left + mParent.Left - mPos.X, base.Top + mParent.Top - mPos.Y);
mPos = mParent.Location;
}
protected override CreateParams CreateParams {
get {
CreateParams cp = base.CreateParams;
if (mParent != null && !DesignMode) {
cp.Style = (int)(((long)cp.Style & 0xffff) | 0x90200000);
cp.Parent = mParent.Handle;
Point pos = mParent.PointToScreen(Point.Empty);
cp.X = pos.X;
cp.Y = pos.Y;
cp.Width = base.DefaultSize.Width;
cp.Height = base.DefaultSize.Height;
}
return cp;
}
}
}
I did something similiar to that recently, and I used a ListBox. The cool think about a listbox, is that you can display it anywhere you want to, even out of bounds of your control. That way, when you detect via a button click or whatever, that you need to display the DropDown that you want, just populate the ListBox and display it anywhere you want. I got the idea from here:
http://msdn.microsoft.com/en-us/library/aa480727.aspx
They show how to build a Custom DataGridView with filtering, and to display the filter values, they place a ListBox under the header cell.
There is a good article here:
http://www.vbaccelerator.com/home/NET/Code/Controls/Popup_Windows/Popup_Windows/article.asp
This has a class which handles some of the tricky aspects of getting this to work correctly, such as keeping the application window titlebar active, handling Alt-Tab and cancelling with a mouse click.