Store and transfer values in a ascx control - asp.net

I have a problem that I have been struggling with for some time, and it is regarding transfering values from one control to another.
Basically I have two .ascx controls. On control1: I have an email textbox called txtEmail. The txtEmail is used to save the email in the SQL table, and on update button click, I load Control2 that has a email textbox as well. I need the emailtext box from control1 to be available on email textbox on control2.
I have tried all kinds of different ways but to no avail. I even tried using delegates and events but I can't make it work.
Does anyone know how I can do this.
Regards
Please find below the code:
public event EventHandler Notify;
public string Email
{
get { return txtEmail.Text; }
set {Email= value ; }
}
//button that will handle the update
protected void btnUpdateDB_Click(object sender, EventArgs e)
{
var email = txtEmail.Text.ToString();
public BaseClass.BAL.MBAL m = new BaseClass.BAL.MBAL();
var s = new BaseClass.Controllers.m();
s.email=email;
if(m.save(s)!=0) txtMsave.Text="Saved....";
}
//second control
public void notifyEmailChange(object sender,EventArgs e)
{
txtUsername.Text = member1.Email;
}
protected void Page_Load(object sender, EventArgs e)
{
if(Page.IsPostBack)
{
member1.Notify += new EventHandler(notifyEmailChange);
}
}
public string email {
set { txtUsers.Text = value; }}

Maybe I am trivializing the problem, but if you are wanting to be able to read/write to the text box on each of the custom controls, just make a public property that reads and writes to the textbox on each of the two controls.
public string EmailAddress {
get {
return txtEmailAddress.Text;
}
set {
txtEmailAddress.Text = value;
}
}
Now the page that contains the two controls can read the email address from the first control and write it into the email address text box in the second control.
If I am misunderstanding the problem, let me know.

The way that I have done this in the past is to have
UserControl1 have a custom event called (for instance) Notify.
The containing control wires Notify to an EventHandler
When notify fires (on the update) the consuming event handler fires and this event handler updates the email on UserControl2
Might seem overengineered but because UserControl2 can't "see" UserControl1 I think this is the way to go
Example
In UserControl1
public event EventHandler Notify;
and within the update button click event handler
if(Notify != null)
{
Notify(this, new EventArgs());
}
In parent control
in Page_Load
ucUserControl2.Notify += new EventHandler(NotifyUserControl);
and to set the message
protected void NotifyUserControl(object sender, EventArgs args)
{
ucUserControl2.Email = ucUserControl1.Email;
}
You obviously need public properties in UserControls to expose the Email text

Related

Validation in different Tabs of windows form using ErrorProviders

I am working on a windows Forms Application and trying to validate few textboxes using errorproviders but the problem is when I am clicking on a button present in Tab 1, all the textboxes even present on a different tabs gets validated. I want the validation to occur for textboxes present on the current tab and not on any control present on any other tab. How can I achieve this? Please help. Below is the code related to validation in the click event.
private void btnCreateUser_Click(object sender, EventArgs e)
{
if (this.ValidateChildren(ValidationConstraints.Enabled))
{
// Some Code here
}
}
Below is code used for validating and validated event for one textbox. I am using similar code for other textboxes as well present on other tabs.
private void txtFirstNm_Validating(object sender, CancelEventArgs e)
{
bool cancel = false;
if (txtFirstNm.Text.Trim().Length == 0)
{
cancel = true;
errorProvider1.SetError(txtFirstNm,"Please enter First Name");
}
else
{
cancel = false;
errorProvider1.SetError(txtFirstNm, "");
}
e.Cancel = cancel;
}
private void txtFirstNm_Validated(object sender, EventArgs e)
{
errorProvider1.SetError(txtFirstNm,"");
}
The Scenario that is given in my question can be handled by using below code. We can use the ValidationConstraint as Visible and this will make sure that Validation occurs on the Current visible Controls.
private void btnCreateUser_Click(object sender, EventArgs e)
{
if (this.ValidateChildren(ValidationConstraints.Visible))
{
// Some Code here
}
}

.net using and reaching public value

I wrote this code in .NET. When I want to change ‘s’ by clicking button2, it doesn’t change. I mean after clicking button2 and then I click Button1 to see the changes but nothing changes. How can I change and access the value of ‘s’ properly. What am I doing wrong?
public string s;
public void Button1_Click(object sender, EventArgs e)
{
Label1.Text = s;
}
public void Button2_Click(object sender, EventArgs e)
{
s = TextBox1.Text;
}
You need to understand how web applications work.
In each post back an instance of the class that handles the page is loaded, so when you click on button 1, the page does a post back and loads again, so this way the variable s isn't loaded with your content.
To make this code work, you need to save the S values on the page viewstate.
try replacing "public string s;" with this:
public string s
{
get { return (string)ViewState["myValue"]; }
set [ ViewState["myValue"] = value };
}
More Information about Page Life Cycle at: http://msdn.microsoft.com/en-us/library/ms178472(v=vs.100).aspx

textBox onBlur to call server method instead of client method

I'm extending a web control. I need to call server methods on every event fired by the control instead of javascript.
public partial class MyTextBox : RadTextBox, IScriptControl
{
public MyTextBox()
{
Attributes.Add("onBlur", "handleLostFocus();");
Attributes.Add("runat", "server");
}
public void handleLostFocus()
{
MyObject obj = new MyObject();
obj.someproperty = this.Text; //or somehow get the user entered text.
MyService1 service = new MyService1();
service.sendRequest(obj);
}
}
As I said in my comment, TextBox will post by default if AutoPostBack = "True", however, you need to handle your event. Supposing your TextBox is named TextBox1:
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
string str = TextBox1.Text;
}
Get rid of handleLostFocus() or have it be the handler for your TextBox control.
Good luck mate.

how to insert data within a calendar cell into a database

i have a calender and i was able to add text-box inside the cell using the day-render event but what i am trying to do is allow the user to add data to the text-box and then press add and the content is added to a database and showed inside that same text-box:
here is what i did:
protected void Page_Load(object sender, EventArgs e)
{
Calendar1.SelectedDate = DateTime.Now;
}
protected void update(object sender, DayRenderEventArgs e)
{
TextBox tb = new TextBox();
Button1.click += new EventHandler(insert);
e.Cell.Controls.Add(Button1);
e.Cell.Controls.Add(textBox2);
}
protected void insert(object sender, EventArgs e)
{
}
and i know how to insert the data but i am lost on how to identify it and output it back to the same text box
thanks
Well I'm not sure exactly what part you are lost on based on your question, so short of providing a complete working example I'll hit some of the main points:
1) To identify the data you are inserting, attach a date (and time if applicable) to the record. (Edit: are you looking for a mechanism to accomplish this? If so post your current DayRender handler code and Calendar markup).
2) To populate individual day data in a calendar, use Calendar.VisibleDate (to filter DB results) in a Page.Load handler to load a data structure (such as a List<T>) with day data for the entire month. Then in a Calendar.DayRender handler, add appropriate records from the structure to the e.Cell.
3) To cause the new results to show up on the first page refresh after insertion, you should be able to get away with using a Response.Redirect to the current page after insertion. This will cause the page generation process to restart, but you will lose ViewState.
Edit: Here is a basic prototype of what I tried to describe above. Note that you could pre-fetch into any enumerable data type, I use a List<T> here.
//Page code-behind
public partial class Default2 : System.Web.UI.Page
{
List<DataObject> liCurrentMonth = new List<DataObject>();
protected void Page_Load(object sender, EventArgs e)
{
liCurrentMonth = DataObject.GetCurrentMonth(Calendar1.VisibleDate);
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
foreach (DataObject item in liCurrentMonth)
{
if (item.date == e.Day.Date)
{
Literal lit = new Literal();
lit.Text = item.text;
e.Cell.Controls.Add(lit);
}
}
}
}
//Data layer object
public class DataObject
{
public DateTime date { get; set; }
public string text { get; set; }
public static List<DataObject> GetCurrentMonth(DateTime currentdate)
{
//Get items from the db here, based on currentdate parameter
//and populate the List<DataObject>.
return new List<DataObject>();
}
}
I'm not sure you'll get this to work. Its the page viewstate that remembers the value entered into textboxes etc. Viewstate is created just before the page renders. The Calendar DayRender event is called during the calendars rendering, and hence after viewstate has done its thing. Therefore the viewstate mechanism is not aware of the existance of the textboxes and so will not track their content.
Perhaps you could assign each textbox an ID based on the month and day number, on postback you could check for this control ID in the Request.Form collection and do something with the data?

How to change property of UserControl on PostBack?

Let's say I have a page with my custom UserControl (containing only asp:Literal and some string property) and a button. Now I want to change Literal's text on button click, so I change my control's string property in button clicked event. Like this:
//in aspx
protected void Button1_Click(object sender, EventArgs e)
{
testControl.Text = "triggered";
}
The problem is my Literal remains unchanged because Page_Load event fires first and creates my custom control, then Button_Clicked fires and changes property but as control is already created, it does nothing. This is my control's code behind:
public partial class TestControl : System.Web.UI.UserControl
{
public string Text { get; set; } }
protected void Page_Load(object sender, EventArgs e)
{
lblTest.Text = Text;
}
}
I figured out that if I move any logic in custom control from Page_Load to property setter it will change like intended. Like this:
public string Text { get { return lblTest.Text; } set { lblTest.Text = value; } }
Is there any other (better) way to do this? My real problem involves much more complicated controls than described here, but problems remains the same: on any postback all properties set in event handlers are ignored.
Moving all logic from Page_Load to Page_PreRender solved the problem. Now properties are set before logic executes. I'll wait for other answers to check if there is better solution and if there are any drawbacks of using Page_PreRender.
This video might help: How Do I: Persist the State of a User Control During a Postback

Resources