Can't dynamically add controlvalidation to textbox - asp.net

After several searches on the Internet finally decided to drop a question.
At runtime I want the following to happen.
If you push a button a textbox will be added to the controls and a custom validator must be attached to the textbox and fire.
It does not fire. Why?
Here is my code
Thank you for looking into this.
public partial class WebUserControl1 : System.Web.UI.UserControl
{
CustomValidator rv2 = new CustomValidator();
protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
rv2.ID = "rev2";
rv2.ErrorMessage = "Not numeric input";
rv2.ClientValidationFunction = "";
rv2.ServerValidate += new ServerValidateEventHandler(GetalValidator);
Controls.Add(rv2);
}
}
protected void ButtonClick(object sender, EventArgs args)
{
TextBox tb1 = new TextBox();
tb1.ID = "tb2";
tb1.Visible = true;
tb1.Width = 30;
this.Controls.Add(tb1);`enter code here`
rv2.EnableClientScript = false;
rv2.ControlToValidate = "tb2";
}
private bool IsNumber(string someText)
{
int number;
bool result = Int32.TryParse(someText, out number);
return result;
}
protected void GetalValidator(object source, ServerValidateEventArgs args)
{
args.IsValid = IsNumber(args.Value);
}
}

here is part of code thorugh which you can add validation on your dynamically created control.
TextBox tb1 = new TextBox();
tb1.ID = "tb2";
tb1.Visible = true;
tb1.Width = 30;
RequiredFieldValidator regfv = new RequiredFieldValidator();
regfv.ID = "regfv";
regfv.ControlToValidate = tb1.ID;
regfv.ErrorMessage = "My Error";
this.Controls.Add(tb1);
this.Controls.Add(regfv);

Related

DevExpress XtraReport HtmlItemCreated event not raised

I'm using DevExpress 2012 Vol 2.4 ASP.NET WebForms controls. I've created a new object of XtraReport class and subscribed to its HtmlItemCreated event. When I'm calling the ExportToHtml method of the XtraReport object the event is not getting raised.
I've not posted the markup but there is just a button. When I click the button the event is not triggered. I've put a breakpoint and tested that.
public partial class WebForm1 : System.Web.UI.Page
{
XtraReport rep = null;
protected void Page_Load(object sender, EventArgs e)
{
rep = new XtraReport();
rep.CreateDocument();
rep.HtmlItemCreated += rep_HtmlItemCreated;
PageHeaderBand h = new PageHeaderBand();
XRLabel l = new XRLabel();
l.Text = "asdasd";
h.Controls.Add(l);
rep.Bands.Add(h);
}
protected void rep_HtmlItemCreated(object sender, HtmlEventArgs e)
{
if (e.ScriptContainer != null)
{
string x = "asdasd";
}
}
protected void btnTest_Click(object sender, EventArgs e)
{
string sPDFFilePath = System.IO.Path.GetTempPath() + "Test.html";
HtmlExportOptions objPDFExpOpt = rep.ExportOptions.Html;
objPDFExpOpt.EmbedImagesInHTML = true;
objPDFExpOpt.ExportMode = HtmlExportMode.DifferentFiles;
if (!string.IsNullOrEmpty("Test"))
objPDFExpOpt.Title = "Test";
rep.ExportToHtml(sPDFFilePath, objPDFExpOpt);
}
}

ASP NET: Is it possible to set control property dynamically?

On my aspx page has a button. I want to change its property dynamically.
For example:
A button which ID is Button1 and I want to change its property Visible to false.
On code behind have three variables hidefield = "Button1", property = "Visible" and value = false.
Is it possible to set the property Visible using the variables?
aspx:
<asp:Button ID="Button1" runat="server" Text="Button1" />
code behind:
protected void Page_Load(object sender, EventArgs e)
{
string hidefield = "Button1";
string property = "Visible";
bool value = false;
if (!IsPostBack)
{
Control myControl1 = FindControl(hidefield);
if (myControl1 != null)
{
myControl1.property = value; // <- I know this statement has error. Is there any way to set the property like this?
}
}
}
Using reflection, based on Set object property using reflection
using System.Reflection;
protected void Page_Load(object sender, EventArgs e)
{
string hidefield = "Button1";
string property = "Visible";
bool value = false;
if (!IsPostBack)
{
Control myControl1 = FindControl(hidefield);
if (myControl1 != null)
{
myControl.GetType().InvokeMember(hidefield ,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
Type.DefaultBinder, myControl, value);
}
}
}
It's pretty messy and not very human readable so therefore could have maintainablility issues.
how about this:
Button myControl1 = FindControl(hidefield) as Button;
if (myControl1 != null)
{
myControl1.Visible= value;
}
protected void Page_Load(object sender, EventArgs e)
{
string hidefield = "Button1";
string property = "Visible";
bool value = false;
if (!IsPostBack)
{
/* Use below two lines if you are using Master Page else you wouldnot be able to access your control */
ContentPlaceHolder MainContent = Page.Master.FindControl("MainContent") as ContentPlaceHolder;
Control myControl1 = MainContent.FindControl(hidefield);
if (myControl1 != null)
{
myControl1.GetType().GetProperty(property).SetValue(myControl1,value,null);
}
}
}

How to select Listbox value in asp.net

I have a ListBox in my webpage that is bound from database in this way:
ListBox1.DataTextField = "Text";
ListBox1.DataValueField = "MenuID";
ListBox1.DataSource = SqlHelper.ExecuteReader(DAL.DALBase.ConnectionString, "GetMenu");
ListBox1.DataBind();
I want to get selected item value and used this code but have a error and does not worked.
ListBox1.SelectedValue;
Forgive me if I have problems on how to write because my English is not good.
Can you be more specific on the error you are getting?
Using ListBox1.SelectedValue should work.
For example:
int mySelectedValue = int.Parse(ListBox1.SelectedValue);
or
string mySelectedValue = ListBox1.SelectedValue;
Edit
Added code to ensure the original poster was keeping values in ListBox databound.
protected void Page_Load( object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindListBox();
}
}
private BindListBox()
{
ListBox1.DataTextField = "Text";
ListBox1.DataValueField = "MenuID";
ListBox1.DataSource = SqlHelper.ExecuteReader(DAL.DALBase.ConnectionString, "GetMenu");
ListBox1.DataBind();
}
protected void SomeButton_Click( object sender, EventArgs e)
{
string mySelectedValue = ListBox1.SelectedValue;
}

how to retain the value of global string variable even after page load in asp.net

I am having problems in retaining the string variable which I defined on the top of my scoop, everytime when page loads the string value becomes null. below is the snippet of the code:
public partial class Caravan_For_Sale : System.Web.UI.Page
{
string check;
PagedDataSource pds = new PagedDataSource(); //paging
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
DataTable dt = null;
switch (check)
{
case "0-1500":
break;
case "1500-2000":
dt = caravans.GetFilterbyPrice1();
break;
case "2000+":
break;
default:
dt = caravans.GetAllCaravans();
break;
}
// DataTable dt = caravans.GetAllCaravans();
pds.DataSource = dt.DefaultView;
pds.AllowPaging = true;
pds.PageSize = 3;//add the page index when item exceeds 12 //Convert.ToInt16(ddlPageSize.SelectedValue);
pds.CurrentPageIndex = CurrentPage;
DataList1.RepeatColumns = 3; // 4 items per line
DataList1.RepeatDirection = RepeatDirection.Horizontal;
DataList1.DataSource = pds;
DataList1.DataBind();
lnkbtnNext.Enabled = !pds.IsLastPage;
lnkbtnPrevious.Enabled = !pds.IsFirstPage;
doPaging();
}
protected void lnkPrice2_Click(object sender, EventArgs e)
{
LinkButton _sender = (LinkButton)sender;
check = _sender.CommandArgument;
// items["test"] = test;
DataTable dt = caravans.GetFilterbyPrice2();
if (dt.Rows.Count < 3)
{
lnkbtnNext.Enabled = false;
lnkbtnPrevious.Enabled = false;
}
CurrentPage = 0;
BindGrid();
}
protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.Equals("lnkbtnPaging"))
{
CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());
BindGrid();
}
}
The string check becomes null everytime when the dlPaging_ItemCommand becomes active(page loads). Any help or suggestions will be appreciated
As far as I know, you have two options:
1) Load it again.
Not sure if it's possible in your case. This is usually done when dealing with database queries.
2) Put it in the ViewState just like this:
ViewState["check"] = check;
And load it after with this:
string check = Convert.ToString(ViewState["check"]);
Your class is instantiated on every load so it will not have a global variable from page view to page view. You will need to store it somehow. Like in the querystring or a session. You can also use the viewstate.
For example
ViewState("Variable") = "Your string"
Viewstate is the way to go, as the other people have answered. Whatever you do, please don't stuff it in the session.

CheckedChanged event for Dynamically generated Checkbox column in DataGrid(Asp.Net)

I have a datagrid (Asp.Net) with dynamically generated checkbox column..I am not able to generate the checkedChanged event for the checkbox..
Here is my code:
public class ItemTemplate : ITemplate
{
//Instantiates the checkbox
void ITemplate.InstantiateIn(Control container)
{
CheckBox box = new CheckBox();
box.CheckedChanged += new EventHandler(this.OnCheckChanged);
box.AutoPostBack = true;
box.EnableViewState = true;
box.Text = text;
box.ID = id;
container.Controls.Add(box);
}
public event EventHandler CheckedChanged;
private void OnCheckChanged(object sender, EventArgs e)
{
if (CheckedChanged != null)
{
CheckedChanged(sender, e);
}
}
}
and Here is the event
private void OnCheckChanged(object sender, EventArgs e)
{
}
Thanks In advance
When do you add your custom column? If it is on load, then it is too late. Load it on init. I.e. following works with your code:
protected void Page_Init(object sender, EventArgs e)
{
ItemTemplate myTemplate = new ItemTemplate();
myTemplate.CheckedChanged += new EventHandler(myTemplate_CheckedChanged);
TemplateField col = new TemplateField();
col.ItemTemplate = myTemplate;
col.ItemStyle.Wrap = false;
grid.Columns.Add(col);
}
If your checkbox ID's are not being set the same way on every postback, then they can never be connected to the event handlers when it comes time to process the events. Where is your field "id" coming from?

Resources