Passing Value Between Web User Controls - DifferentQuestion - asp.net

I want pass values between web user controls without writing any code to the main page which user controls are put on. I do something like that but after doing that I need to click double to pass the value.
The example of what I've done :
Department User Control (Code-Behind)
protected void Page_Load(object sender, EventArgs e)
{
int productId = ProductUserControl.selectedProductId;
... doing some bind work with productId
}
Product User Control
public static int selectedProductId;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void lvDepartments_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "selectDepartment")
{
selectedProductId = int.Parse(e.CommandArgument);
}
}
Thanks in advance...

In your Department User Control you are trying to get the value of selectedProductId before it is set in the Product User Control. That's why you don't get the value you expect until you postback twice.
You'll need to get it after the Product User Control sets it in the ItemCommand event. Perhaps placing the Department User Control code in the Page_LoadCompleted... though I'm not sure if that will work either.
Another way to do it is to have Product User Control set a public property in Department User Control instead of having Department User Control try to read a property in Product User Control.
The issue seems to be a Page Lifecycle issue.
http://www.robincurry.org/blog/content/binary/o_aspNet_Page_LifeCycle.jpg
I'm sure there's a better way than that as well.

Try using delegates to achieve this more cleanly, example here

Related

Create User Using ASP.NET Membership

When I create a user using membership in asp.net, after successfully create user it get automatically login to the system. But I don't want to login immediately. Can someone help me?
Set LoginCreatedUser property to false.
For example,
protected void Page_Load(object sender, EventArgs e)
{
// Replace createUserWizard1 with ID of your CreateUserWizard control.
createUserWizard1.LoginCreatedUser = false;
}

how to disable a pageload property under certain circumstances

In .NET i have a gridview which has to display on the mainpage with default settings. So i put it in pageload code. In the same page i have a "List" button; people choose date etc. and when they press the button gridview loads data from another stored procedure. I put that code under List button event. But after people press List button and gridview comes with the needed data, if they press something else (because of page refresh itself) gridview turns back to default settings.
How do i keep the gridview with wanted data?
protected void Page_Load(object sender, EventArgs e)
{
opsbelgegridview.DataSource = DB.OpsHavuzGetir();
opsbelgegridview.DataBind();
protected void listelebtn_Click(object sender, EventArgs e)
{
opsbelgegridview.DataSource = DB.OpsHavuzDetayListeleBtn(tarih1.ToString("yyyy-MM-dd"), tarih2.ToString("yyyy-MM-dd"), durumdd.SelectedItem.Text.ToString(), islemtipdd.SelectedItem.Text.ToString());
opsbelgegridview.DataBind();
You can use IsPostBack() and only load the initial grid on the first load of the page. Then if the grid data changes it will stay.
private void Page_Load()
{
if (!IsPostBack)
{
opsbelgegridview.DataSource = DB.OpsHavuzGetir();
opsbelgegridview.DataBind();
}
}

Aspx and Ascx lifecycles : avoid multiple select on database

I use an ascx user control for manage CRUD o database entity. I reuse this userc control in my aspx page for show in readonly mode the database data of a record on database. The user control have inside a simple FormView and an objectdatasource.
Now, in a aspx page that contains that ascx i have to know, in DATABIND time of the aspx some data of the record of the database that is considerate by the user control. User control are databind after the aspx page, and for this reason i don't have the data. I have to do a select in aspx page on database and after the user control do the same select.
How can i do for optimize this process?
ASCX base events may be fired after your ASPX's base events, but in the whole lifecycle, you can fire your own events.
You could define an Event on your ASCX, make your page register to this event, and then propagate your custom event from your ASCX to your ASPX, with whatever data you need in the arguments
rough example (may not compile) : in the ASCX
public partial YourControl : System.Web.UI.UserControl {
public event EventHandler MyControlDataBound;
public void FireMyControlDataBound()
{
if (MyControlDataBound!= null)
{
MyControlDataBound(this, new EventArgs());
}
}
protected void MyDataBound(object sender, EventArgs e) {
// ......
FireMyControlDataBound();
}
}
and in the ASPX
public partial class MyPage: Page
{
protected void Page_Load(object sender, EventArgs e)
{
yourUserControlInstance.MyControlDataBound += HandleYourDataInYourPage;
}
protected void HandleYourDataInYourPage(object sender, EventArgs e) {
// .. do whatever needed in your page, with your data
// if you have defined a custom Args class that inherits EventArgs, your could collect data here...
}
}
Feel free to create a class that inherits EventArgs to pass data with your event if you need this
You can pass your arguments to your UserContol in init event of your Page
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
var control = (UserControl)this.FindControl("UserControlId");
control.Property = ...;//Pass User Control properties
}

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?

FormView not updating with control events

Time for my daily ASP.NET question.
One of my pages shows all of our customer information from a customer table. I want the user to choose whether to see all customer records, or select a specific record from a list. So, my webpage has two radio buttons (show all customers, show specific customer), a listbox (full of customer names), and a formview control. The problem I'm having is getting the formview to update when I change modes via radio buttons or listbox selection (see code below).
Can anyone provide me with some pointers on how to do what I'm trying to do?
protected void Page_Load(object sender, EventArgs e)
{
UpdatePage ();
}
protected void RadioButtonShowAll_CheckedChanged(object sender, EventArgs e)
{
}
protected void RadioButtonShowSelected_CheckedChanged(object sender, EventArgs e)
{
}
protected void DropDownListCustomers_SelectedIndexChanged(object sender, EventArgs e)
{
RadioButtonShowSelected.Checked = true;
UpdatePage ();
}
protected void UpdatePage ()
{
if (RadioButtonShowAll.Checked)
SqlDataSource1.SelectCommand = "SELECT * FROM [Customer] ORDER BY [Company]";
else
SqlDataSource1.SelectCommand = "SELECT * FROM [Customer] WHERE ([CustomerID] = #CustomerID) ORDER BY [Company]";
FormView1.DataBind();
}
First, you only have the SelectedIndexChanged event wired up... In that case, what happens when you change the drop down box is first, Page_Load() fires--which calls UpdatePage(). Then, the event fires, which calls UpdatePage() again. The second time probably doesn't do what you expect.
The fix is to only call UpdatePage() from Page_Load() the first time the page is loaded, but not from postbacks:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
UpdatePage();
}
Your page has to be updated on Client side, for it to show the new data. You'll need to use Javascript or AJAX and have some variable that keeps track of the need to refresh your page, this way you can send a request to update the page to the server when the Formview needs updating.

Resources