Datalist paging in asp.net? - asp.net

In asp.net Web application, i write code for datalist paging like this :
PagDat = new PagedDataSource();
PagDat.AllowPaging = true;
PagDat.PageSize = 10;
PagDat.CurrentPageIndex = **currentpage**;
PagDat.DataSource = ds.Tables[0].DefaultView;
dtlstMagazine.DataSource = PagDat;
dtlstMagazine.DataBind();
In this "currentpage" is a integer varaible which i declared as a static. I think it could be conflict when more user access this page am i right?

Yes your are right.
You should Save your PageDataSouce page index in State Management
object. using static variable is not a good approach in web
application for such page level operations.
Create CurrentPage property:
public int CurrentPage
{
get
{
// look for current page in ViewState
object o = this.ViewState["_CurrentPage"];
if (o == null)
return 0; // default page index of 0
else
return (int) o;
}
set
{
this.ViewState["_CurrentPage"] = value;
}
}
Check following link for more information:
Adding Paging Support to the Repeater or DataList with the PagedDataSource Class

Related

View state Property null

I m getting null in checking view state null condition but ViewState name is not null , I enabled ViewState property .This methods calling inside a for each loop .In some objects View state not null but majority getting null.I haven't set ViewState in any other places.
private void SetSelectedDates(string viewStateName, System.Web.UI.WebControls.Calendar calanderControl)
{
var variable = ViewState[viewStateName];
var dateTimeList = new List<DateTime>();
if (ViewState[viewStateName] != null)
{
dateTimeList = (List<DateTime>)ViewState[viewStateName];
}
else
{
}
}
Try this.Put double quotes in viewstatename
private void SetSelectedDates(string viewStateName, System.Web.UI.WebControls.Calendar calanderControl)
{
var variable = ViewState[viewStateName];
var dateTimeList = new List<DateTime>();
if (ViewState[viewStateName] != null)
{
dateTimeList = (List<DateTime>)ViewState["viewStateName"];
}
else
{
}
}
Use like this
ViewState["viewStateName"]
View state data is stored in one or more hidden fields as
base64-encoded strings. You can access view state information using
the page's ViewState property, which exposes a dictionary object.
Because the data in view state is stored as a string, only objects
that can be serialized can be stored.

dynamically created controls within a usercontrol is not recognized

In the ascx.cs file I'm dynamically generating buttons. In .aspx file I add the control to the form. The control itself renders well, but when the buttons are clicked I get this error
An error has occurred because a control with id 'ctl03' could not be
located or a different control is assigned to the same ID after
postback.
DestopControl.ascx.cs
public partial class DesktopControl : PlaceHolder
{
public void Build()
{
for (int i = 0; i < 10; i++)
{
Button button = new Button()
{
Width = 50,
Height = 50,
ID = string.Format("button{0}", i),
Text = i.ToString()
};
button.Click+=new EventHandler(button_Click);
}
}
}
Default.aspx.cs
DesktopControl desktop = new DesktopControl();
desktop.Build();
MainContent.Controls.Add(desktop);
After reading the comments (little hard to read the code-part of the comments) it appears that yes, you are generating your controls inside an if(!isPostBack){}; well, looks like it's in the else part of that if statement.
You have to generate your controls every time the page posts back, as the page_load gets fired before your button click. So once the controls have been re-created the code will continue on to your button click handler, where the controls should be available to handle.
Essentially, take ReloadUI(Session["ui"]); OUT of the if(!isPostBack){}else{} statement. Put it after your if statement.
Like this:
if (!isPostBack){
// my first load code
}else{
// my postback code
}
// load all my dynamic controls here
ReloadUI(Session["ui"]);
Found a solution:
Every time there is a new UI I call this ClearScreen() which does the trick.
The error on 'ctl03' was a menu control which was generating it's own ID and somehow wasn't available on postback. I assigned an ID to it. But I guess all the issue went away with this ClearScreen() method.
private void ClearScreen()
{
try
{
List<Control> controls = new List<Control>();
foreach (Control control in MainContent.Controls)
{
controls.Add(control);
}
for (int i = 0; i < controls.Count; i++)
{
if (!(controls[i].GetType() == typeof(LiteralControl) || controls[i].GetType() == typeof(ScriptManager)))
{
MainContent.Controls.Remove(controls[i]);
}
}
}
catch (Exception ex)
{
}
}

Validate AutoCompleteExtender

Hi
i need to validate a textbox value in order to accept only values that are in the completion list of the associated autocompleteextender control.
I'm using ajaxtoolkit (version 20229) on asp.net 2.0.
For now i use the code below to validate the textbox ; as you can see i had a hiddenfield that keep the selected key. The hiddenfield is set to 0 if the user enter a value without selecting it from the list.
Do you have any idea?
Thanks
/**** Javascript code
function AutoCompleteItemPopulated(source, eventArgs)
{
var assocHiddenField = document.getElementById( source.get_element().id+'_hidden');
assocHiddenField.value=0;
}
function AutoCompleteItemSelected(source, eventArgs)
{
var assocHiddenField = document.getElementById( source.get_element().id+'_hidden');
assocHiddenField.value = eventArgs.get_value();
}
/*****CODEBEHIND code used to populate the autocompletion list
[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
public static string[] getStrada(string prefixText, int count, string contextKey)
{
System.Collections.Generic.List<string> items = new System.Collections.Generic.List<string>();
DataSetIncidentiTableAdapters.StradarioTableAdapter adapter = new DataSetIncidentiTableAdapters.StradarioTableAdapter();
DataSetIncidenti.StradarioDataTable dtStrade = adapter.GetStrade(contextKey, prefixText);
foreach (DataSetIncidenti.StradarioRow strada in dtStrade.Rows)
{
items.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(strada.DenominazioneCompletaVia, strada.IdStrada.ToString()));
}
return items.ToArray();
}
Yes this can be validated; you need to use a CustomValidator to do this, which you can setup both a client and server validation function, and then check the hidden field for its value.
This works great for us.
HTH.

How to use Partial Caching with dynamically created controls?

I have a control declared with PartialCaching attribute, like this:
[PartialCaching(60 * 60 * 12)]
public class MyControl : Control {
// control contents ...
}
but I create it in code, using new keyword. The problem is that if the control is in cache I must not create the control again the next time, but I need to add the control to the page hierarchy, otherwise nothing is going to be rendered. What I need in pseudo-code is something like this:
if (myControlIsCached) {
var ctl = ???; // something that represents the cached control
// e.g. could be: new LiteralControl( myControlCachedData )
this.Controls.Add( ctl );
}
else {
var ctl = new MyControl();
// setup control ...
this.Controls.Add( ctl );
}
What is the correct way of doing it?
Thanks people.
I believe you are looking to do something like this:
Control possiblyCachedControl = LoadControl("path to control");
MyControlType control = null;
if (possiblyCachedControl is MyControlType)
{
//control wasn't cached
control = possiblyCachedControl as MyControlType;
}
else if (possiblyCachedControl is PartialCachingControl && ((PartialCachingControl)possiblyCachedControl).CachedControl != null)
{
//control was cached
control = (MyControlType)((PartialCachingControl)possiblyCachedControl).CachedControl;
}
if (control != null)
{
//use the control
}

Return ASP DDL or Telerik control

I'm trying to write a more generic method that will populate either an ASP.NET dropdownlist OR a telerik RadComboBox with states. I'd like to pass the control in as a parameter to the method. I have a DataTable that holds all the states, which I loop through (see below) - I'd like to make this applicable to a Telerik RadComboBox - so I need to change the first parameter, and also the part where I Insert a new ListItem - for Telerik RadComboBox it is new RadComboBoxItem. How can I do this?
public void PopulateStates(DropDownList ddlStates, string country)
{
ddlStates.Items.Clear();
DataLookup dl = new DataLookup();
DataTable dt = dl.GetStatesByCountry(country);
if (dt != null)
{
if (dt.Rows.Count > 0)
{
ddlStates.Items.Insert(0, new ListItem(""));
for (int i = 0; i < dt.Rows.Count; i++)
{
ddlStates.Items.Add(new ListItem(dt.Rows[i]["STCD_Descr"].ToString(),
dt.Rows[i]["STCD_State_CD"].ToString()));
}
}
}
}
I looked up the telerik documentation & there doesn't seem to be common way of doing - what you are trying to do.
If it is possible, try using the databinding (setting the DataSource & calling DataBind).
Note: I haven't tried it. But I think that should be supported by both.
Since ListBox and RadComboBox does not have common classes except for the "Control" class you will need to check the actual type.
How about the following code?
public void PopulateStates(Control ddl, string country)
{
object listItem = new object();
switch (ddl.GetType().Name)
{
case "RadComboBox":
listItem = listItem as RadComboBoxItem;
ddl = ddl as RadComboBox;
break;
case "ListBox":
listItem = listItem as ListItem;
ddl = ddl as ListBox;
break;
default:
return;
}
// proceed with your code
}

Resources