Client populating server collections at runtime - asp.net

I am adding to a List of DateTime objects on the server every time a date is selected on a Calender control by the client, and in turn highlighting all the selected dates on the control. I'm able to highlight (change back-color) of dates instantiated in the List on page load, and the first selected date by the client. However further date selections on the control are just changing which date is highlighted, ie. not highlighting more.
I had thought by adding the selected DateTime object to a list at runtime upon a selection and then adding each of them to the Calendars "selected dates" property will get around the problem of the calendar control clearing the SelectedDates property on selection of a new date. Debugging by printing all the dates within the dates List to a textbox show that the dates the list was instantiated with and the latest selection are only in the list, not previous selections. My question and what I think is the problem,
Can a List on the server be populated by actions from the client at runtime, and added to?
I am using ASP with C# .Net3.5 on VS2008.
Thanks
My Code
System.Collections.Generic.List dates;
protected void Page_Load(object sender, EventArgs e) {
this.dates = new List<DateTime>();
this.dates.Add(new DateTime(2009,12,2));
this.dates.Add(new DateTime(2009, 12, 3));
this.dates.Add(new DateTime(2009, 12, 16));
fillDates();
}
protected void AvailCalender_SelectionChanged(object sender, EventArgs e){
this.dates.Add(this.AvailCalender.SelectedDate);
foreach (DateTime date in this.dates)
{
this.AvailCalender.SelectedDates.Add(date);
this.displayText.Text = this.displayText.Text + date.ToShortDateString();
}
fillDates();
}
protected void fillDates()
{
foreach (DateTime dates in this.dates)
{
this.AvailCalender.SelectedDates.Add(dates);
}
this.AvailCalender.SelectedDayStyle.BackColor = System.Drawing.Color.Blue;
}

The List<DateTime> is getting created with each postback so it is not saving the previous selections. You need to persist it in some way like using ViewState, Session or storing it in a DB. Only create it the first time by using Page.IsPostBack to check if this is the first time the page has been hit.

Related

How to update calendar?

I'm using DayPilot Calendar and Navigator on Visual Studios 2013, webform.
I am able to link the navigator to the calendar, so when I click on a different week, it reflects on the calendar as well.
Problem is, when i select a different week, all my data in the calendar is gone, and the week I click on is not updated in the calendar.
I tried changing the properties for the Calendar to postback/callback but it still doesn't work.
However, my Navigator is able to retain the data when I select a different week.
This is when i first debug the webform.
And this is when i click on the Navigator (the calendar at the bottom). As shown, the data is gone.
How do i solve this problem?
-- You can see that the navigator retains the data shown by the date in bold.
These are the codes I've used.
protected void DayPilotCalendar1_Command (object sender, DayPilot.Web.Ui.Events.CommandEventArgs e)
{
switch (e.Command)
{
case "navigate":
DateTime start = (DateTime)e.Data["EventStart"];
DateTime end = (DateTime) e.Data["EventEnd"];
DayPilotCalendar1.StartDate = start;
DayPilotCalendar1.DataBind();
DayPilotCalendar1.Update();
break;
}
}
You need to reload the event data as well:
protected void DayPilotCalendar1_Command (object sender, DayPilot.Web.Ui.Events.CommandEventArgs e)
{
switch (e.Command)
{
case "navigate":
DateTime start = (DateTime)e.Data["EventStart"];
DateTime end = (DateTime) e.Data["EventEnd"];
DayPilotCalendar1.StartDate = start;
DayPilotCalendar1.DataSource = LoadYourEventsHere(); // load data
DayPilotCalendar1.DataBind();
DayPilotCalendar1.Update();
break;
}
}
This is the missing part:
DayPilotCalendar1.DataSource = LoadYourEventsHere(); // load data

Two way binding with custom expression?

I am using a gridview in my asp.net project to view and modify some records from the database. The database has two columns: start_date and end_date. When a new record is created these columns contains null, but they can be modified later using the gridview update command.
In gridview I have two template fields (having names start_date and end_date) in which I have placed two calendar controls. Upon clicking an update link of gridview it always returns an error because of the null value binding to the calendar. I have used this helper function to solve it:
protected DateTime ReplaceNull(Object param)
{
if (param.Equals(DBNull.Value))
{
return DateTime.Now;
}
else
{
return Convert.ToDateTime(param);
}
}
and used these two custom expressions in calendar control's SelectedDate:
ReplaceNull(Eval("start_date"))
ReplaceNull(Eval("end_date"))
The problem is that two-way data binding the calendars upon selecting a date does not update the database table. Are there any workarounds? Or alternatively, a better solution would be appreciated.
I don't know why you let them null when insert a new record , but many ways you can solve this problem i think .
one of them : in the RowDataBound event of the Gridview
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[1] == null) //the index of the start_date
{
e.Row.Cells[1].Text = DateTime.Now.ToString(); // in your case you will make the selected date of the calender(through casting to calender) with the value you need.
}
}
}
Or: you can catch the exception , you meet in your Update button through
try and catch block.

Maintaining GridView current page index after navigating away from Gridview page

I have a GridView on ASP.NET web form which I have bound to a data source and set it to have 10 records per page.
I also have a hyper link column on the GridView, such that a user can navigate to another page (details page) from the list. On the details page, they have "Back" button to return to the GridView page
Edit
Just to clarify the query
I am looking for sample code snippet on the Server Side on how to specify the page index to set the GridView after data binding. The idea is to ensure the user navigates to the same page index they were on.
The three basic options at your disposal: query string, session, cookie. They each have their drawbacks and pluses:
Using the query string will require you to format all links leading to the page with the gridview to have the proper information in the query string (which could end up being more than just a page number).
Using a session would work if you're sure that each browser instance will want to go to the same gridview, otherwise you'll have to tag your session variable with some id key that is uniquely identifiable to each gridview page in question. This could result in the session management of a lot of variables that may be completely undesirable as most of them will have to expire by timeout only.
Using a cookie would require something similar where cookie data is stored in a key/data matrix (optimized hash table might work for this). It would not be recommended to have a separate cookie name for each gridview page you're tracking, but rather have a cookie with a common name that holds the data for all gridview pages being tracked and inside that have the key/value structure.
Edit: A small code snippet on setting the page index.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
try
{
if(HttpContext.Current.Request["myGVPageId"] != null])
{
myGridview.PageIndex = Convert.ToInt32(HttpContext.Current.Request["myGVPageId"]);
}
}
catch(Exception ex)
{
// log it
}
}
}
I'm more of a fan of the Session approach, personally. Simply save your page index as a session variable, and, if this Session variable isn't null on page load, use it to fire your "OnPageIndexChanging" method, like so:
Set your current page number whenever the page number changes:
protected void GridViewIndexChanging(object sender, GridViewPageEventArgs e)
{
myGridView.PageIndex = e.NewPageIndex;
Session["pageNumber"] = e.NewPageIndex;
//whatever your page index changing does...
}
Then, on Page_Load do something like:
if (!IsPostBack)
{
if (Session["pageNumber"] != null)
{
GridViewIndexChanged(myGridView, new GridViewPageEventArgs((int)Session["pageNumber"]));
}
}
you can ues the Page Index Change Event of Gridview and Find out the Current Page Index for e:g
yourGridId.PageIndex=e.NewPageIndex;
ViewState["GridPageIndex"]=e.NewPageIndex;
on PageLoad Get the Viewstate Value
string pIndex=string.Empty;
pIndex=Convert.toInt32(ViewState["GridPageIndex"]);
if(!string.Empty(pIndex))
{
yourGridId.PageIndex =pIndex;
}
you must use query string and is recommended, otherwise you can use session object but don't use that for this as you may have grid view opening in different pages so use query string .
gridView1.CurrentPageIndex = (Request["pageNo"] != null) ? Request["pageNo"] as int : 0;
gridView1.DataSource = myDataSet;
gridView1.DataBind();
you can update your link on GridView_DataBound event

How can I retrieve a subset of data from entity object data source and pass to another page

I am playing about just now trying to teach myself a little bit about the entity framework.
I have a Gridview data bound to a Entity Date Source using the Entity Framework. If I select certain items in that list I then wish to redirect another page and populate another gridview with just the items selected (but with more detail, different includes/navigation properties)
This is probably the most simple thing but I have spent 2 hours banging my head on the wall trying to get this to work.
Essentially I have a continue button which when clicked should identify all the UIDs (a column in the gridview) of the rows and allow me to subset to just these rows and pass them to another page to be rebound to another datagrid
Any ideas???
Well, the big picture is that you should get those IDs, pass them to the other page, and then use a query with Contains; see this question for an idea of how to use it:
How search LINQ with many parametrs in one column?
Assuming you haven't used DataKeys in your GridView, this would be my approach.
Page 1
protected void Button1_Click(object sender, EventArgs e)
{
var checkedItems = new List<int>();
foreach (GridViewRow row in GridView1.Rows)
{
var checkbox = (CheckBox)row.FindControl("CheckBox1");
if (checkbox.Checked)
{
checkedItems.Add(int.Parse(row.Cells[1].Text));
}
}
Session["checkedItems"] = checkedItems;
Response.Redirect("Page2.aspx");
}
Page 2
protected void Page_Load(object sender, EventArgs e)
{
var checkedItems = (List<int>)Session["checkedItems"];
Session["checkedItems"] = null;
foreach (var checkedItem in checkedItems)
{
Response.Write(checkedItem);
}
}
Using the IDs in the checkedItems List you can now query those from you DB and finally assign the Result to your GridView on the second page.
Instead of using Session you could pass the IDs via QueryString.

System.Web.UI.WebControls.Calendar is it possible to change the color of individual selections?

I have code to do multiple selections in a calendar control but I would like to change the color of the initially selected day to green and the end date to red. Visually this would indicate the start date and end date of a certain service to be
provided. Should I be looking into RenderControl Method for my calander or more looking into setting some attribute of the days in the control?
The multiple select code is attributable to
Steve Wellins
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
System.Web.UI.WebControls.Calendar TheCalendar = sender as System.Web.UI.WebControls.Calendar;
// create new list of dates or get stored list of dates
List SelectedDates;
if (ViewState["SelectedDates"] == null)
SelectedDates = new List();
else
SelectedDates = ViewState["SelectedDates"] as List;
// if date is already in list, remove it, otherwise, add it
if (SelectedDates.Contains(TheCalendar.SelectedDate) == false)
SelectedDates.Add(Calendar1.SelectedDate);
else
SelectedDates.Remove(Calendar1.SelectedDate);
// set the calendar to our list of dates
TheCalendar.SelectedDates.Clear();
foreach (DateTime Date in SelectedDates)
TheCalendar.SelectedDates.Add(Date);
// store list for next postback
ViewState["SelectedDates"] = SelectedDates;
}
This code may overwrite any date or formatting applied to the calendar but I am not above saving and restoring this formating to the calendar.
foreach (DateTime Date in SelectedDates)
TheCalendar.SelectedDates.Add(Date);
I am glad to research leads if you point me down the right path or terms to search for.
From the MSDN site the Calendar..::.OnDayRender Method is invoked while each day is being rendered. I am a .NET noob... how to use it all?

Resources