ASPxCombobox not fetched from SQLdatasource saved in session - asp.net

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["SavedSQLSources"] == null)
SavedSQLSources = new Dictionary<String, SqlDataSource>();
SavedSQLSources.Add(ASPxComboBox1.ID, SqlDataSource1);
SavedSQLSources.Add(ASPxComboBox2.ID, SqlDataSource2);
Session["SavedSQLSources"] = SavedSQLSources;
}
else
{
if (Session["SavedSQLSources"] != null)
SavedSQLSources = (Dictionary<String, SqlDataSource>)Session["SavedSQLSources"];
}
}
Greetings, I have multiple ASPxCombobox with each having their own datasource. So first I saved
each control ID with their corresponding datasource object in a dictionary.
protected void Cmb_Callback(object source, CallbackEventArgsBase e)
{
ASPxComboBox comboBox = (ASPxComboBox)source;
string[] args = e.Parameter.Split('|');
for (int i = 0; i < args.Length; ++i)
SavedSQLSources[comboBox.ID].SelectParameters[i].DefaultValue = args[i];
comboBox.DataSourceID = SavedSQLSources[comboBox.ID].ID;
comboBox.DataBind();
}
Doing a few actions on the page, each control then launch its callback and bind its data with the corresponding datasource.
Well... Work perfectly when using directly the datasource, but having no items fetched when it's from a datasource saved in Session (from SavedSQLSources).
Shouldn't the instance of the object be the same ?
Thanks in advance, TheRainFall.

Ok, I gave up on the dictionnary method and resolved this by linking each ASPxCombobox to its SqlDatasource from client-side:
DataSourceID="SqlDataSource1"
Then in the callback I got the sqldatasource instance from the parent container by using the datasourceID referenced from client-side:
SqlDataSource tempSqlDatasource= (SqlDataSource)comboBox.Parent.FindControl(comboBox.DataSourceID);
The main purpose was to reload all combobox without reloading the page although I could have done this client-side only.

Related

Get control which is generated on runtime

am creating some TextBoxes by backend on a text change event, Like this :
protected void txtHowMany_TextChanged(object sender, EventArgs e)
{
int totalSections = Convert.ToInt32(txtHowMany.Text.Trim());
for (int i = 1; i <= totalSections; i++)
{
TextBox tbx = new TextBox();
tbx.Text = "";
tbx.ID = "section" + i;
tbx.Style.Add("width", "90%");
tdSectionsAdd.Controls.Add(tbx);
}
trSectionsName.Visible = true;
}
The auto post back is true for txtHowMany, so when I enter a number, it generates the textboxes and add it to table division
Now the problem is, I am trying to get text from generated textboxes like this :
protected void btnSave_click(object sender, EventArgs e)
{
int numbersOfSectionsToSave = 1;
int sectionsToSave =Convert.ToInt32(txtHowMany.Text.Trim());
for (int i = 1; i < sectionsToSave; i++)
{
Sections section = new Sections();
section.CourseId = result;
section.OrganizationId = course.OrganizationId;
foreach (Control c in tdSectionsAdd.Controls)
{
if (c.GetType() == typeof(TextBox))
{
TextBox txtBox = (TextBox)c;
string id = "section" + i;
if (txtBox.ID == id)
{
section.Name = txtBox.Text.Trim();
}
}
}
string name = Request.Form["section1"];
section.CreatedBy = "Admin";
section.CreationDate = DateTime.Now;
section.ModifiedBy = "Admin";
section.ModificationDate = DateTime.Now;
numbersOfSectionsToSave += section.SaveSection();
}
But its showing 0 count for the controls in tdSectionsAdd , The controls are added before I am trying to access them, but still it shows no controls in td.
Please help, How can I get these textboxes?
Thanks!
You need to add them in each postback. Store the totalSections variable in ViewState so you can add them i page load also:
protected void AddTextBoxes()
{
int totalSections;
if (int.TryParse(Convert.ToString(ViewState["TotalSections"]), out totalSections)
{
for (int i = 1; i <= totalSections; i++)
{
TextBox tbx = new TextBox();
tbx.Text = "";
tbx.ID = "section" + i;
tbx.Style.Add("width", "90%");
tdSectionsAdd.Controls.Add(tbx);
}
trSectionsName.Visible = true;
}
}
protected void txtHowMany_TextChanged(object sender, EventArgs e)
{
ViewState["TotalSections"] = Convert.ToInt32(txtHowMany.Text.Trim());
tdSectionsAdd.Controls.Clear();
AddTextBoxes();
}
protected void Page_Load(object sender, EventArgs e)
{
AddTextBoxes();
}
Dynamic Created controls "Disappear" on postback, if they are not "recreated" in the Page_Init of that page.
Only if they are created in the page_init will the page's viewstate get updated with their information.
Long Explantion:
When we perform a postback (or partial postback) we want to be able to access those controls (or at least the values the user put into them).
We know that the data is in the viewstate, but ASP.NET doesn’t really know which control a ViewState item belongs to. It only knows to match a viewstate item and a control through the same index (e.g. Matches item n in the viewstate tree to item n in the control tree). Therefore in order to get the dynamic controls' data, we need to re-create the controls each time the page is postbacked.
BUT in order for this to work, we need to re-create the controls in the Page_Init function NOT in the Page_Load.
Why? Because when the ViewState is created it needs all the controls to already exist.
This is taken from MSDN, as you can see the viewstate is loaded AFTER the init but before the page load.
TL;DR Call the function that creates the dynamic controls in the page_init and you should be able to see all the values the user entered when the page postbacks
A few links on this issue:
http://forums.asp.net/t/1186195.aspx/1
ASP.NET - Dynamic controls created in Page_Pre_init() or Page_Init() or Page_Load()
Option 2:
I should note: If the controls all had unique Ids and you're not interested in re-creating them again every postback - you could always look for them in the Request Object.
The Request.Form is a NameValueCollection that holds the values of all the controls that were part of the form, just search it for whatever you're looking for

asp.net - dynamically created dropdown not calling the event handler method in post back

I have a page to do a heirarchical search, it starts with a dropdownlist and based on the value selected in the dropdown it will query the database and show the childs in another dropdown list and this continues as long as it hits the leaf... so I've first dropdown added dynamically and it has the event handler on SelectedIndexChanged, when I change the selected value, it triggers the postback but however not calling event handler method.. Not sure what i'm doing wrong here.. or is it a bug??
Using a session variable to keep track the created controls
private List<DynamicControlProperties> PersistedControls
{
get
{
if (_persistedControls == null)
{
if (Session[PersistedControlsKey] == null)
{
Session[PersistedControlsKey] = new List<DynamicControlProperties>();
}
_persistedControls = Session[PersistedControlsKey] as List<DynamicControlProperties>;
}
return _persistedControls;
}
}
And in Page Init, recreating the dynamically generated controls
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
// regenerate the persisted controls
foreach (var prop in PersistedControls)
{
CreateControl(prop);
}
}
In page load, created the very first dropdown
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// create the control
CreateControl(....)
// bind the data to the dropdown
}
}
In create control method, just creating a label and a dropdown wrap it inside a and adding it to place holder
private DropDownList CreateControl(DynamicControlProperties dynamiccntrlprop)
{
// create a new HTML row
HtmlGenericControlWithParentID tr = new HtmlGenericControlWithParentID("tr");
HtmlGenericControlWithParentID td1 = new HtmlGenericControlWithParentID("td");
HtmlGenericControlWithParentID td2 = new HtmlGenericControlWithParentID("td");
// make sure we set the id and parentid
tr.ID = string.Format("tr{0}", dynamiccntrlprop.ID);
tr.ParentID = dynamiccntrlprop.ParentID;
tr.EnableViewState = true;
// create a new label for dropdown
Label lbl = new Label() { ID = string.Format("lbl{0}", dynamiccntrlprop.DisplayName), Text = dynamiccntrlprop.DisplayName };
// create a new dropdown list
DropDownList ddl = new DropDownList()
{
ID = string.Format("ddl{0}", dynamiccntrlprop.DisplayName),
// set the postback
AutoPostBack = true,
EnableViewState = true
};
// subscribe for the select index changed event
ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
// add the controls to table row
td1.Controls.Add(lbl);
td2.Controls.Add(ddl);
tr.Controls.Add(td1);
tr.Controls.Add(td2);
// add the control to place holder
this.filtersPlaceHolder.Controls.Add(tr);
return ddl;
}
Here is the index changed handler,
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
}
Enabled the viewstate,autopostback blah blah blah... recreated the controls with same id in post back.. tried all the answers in google.. but NO luck.. It does trigger the postback when i changed the index but not calling the event handler method..
Any ideas, please???
Many Thanks,
K
You have to make sure that The CreateControl method is called on each and every page postback. This needs to happen to ensure that the dynamic control's event handler is hooked up after the postback.
protected void Page_Load(object sender, EventArgs e)
{
// you shouldn't wrap the call to CreateControl in this 'if' statement
//if (!Page.IsPostBack)
//{
// create the control
CreateControl(....)
// bind the data to the dropdown
//}
}
once you do this, the selected index changed event will fire.
Maybe It is beacuse new value of the dropdownlist don't be loaded.
protected override void LoadViewState(object savedState)
{
// regenerate the persisted controls
foreach (var prop in PersistedControls)
{
CreateControl(prop);
}
base.LoadViewState(savedState);
}

Preserving CheckBox's Value in Dynamic GridView TemplateField

I am trying to create a GridView which will contain a list of users and permission levels that they have access to. Each row will have the following fields: User_ID, Username, Permission1, Permission2, ..., PermissionN, where the values of permissions field are "0" if the user does not have that permission and "1" if they do (note that columns returned by the DAL are not named Permission1, but rather are the actual name of the permission). I would like to represent the data by using CheckBoxes, to allow an admin to quickly grant or revoke permissions to a large number of users at once.
Since I will not know the number of permissions before-hand, I dynamically create TemplateFields and CheckBoxes, and this works fine; the GridView shows the current permission levels of all the users. I run into a problem when I try to update permissions based on the user checking and unchecking boxes.
Once the user is done changing permissions, I have an "Update" button, which of course causes a postback. Since the postback occurs before the OnClick event, by the time I reach OnClick all of the CheckBoxes have been reset to their initial values. Is there a way I can somehow grab the value of the CheckBoxes' Checked property before the postback occurs? Is there another (better) way of doing this? Thanks.
ASPX:
<asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="False"
EnableModelValidation="True" DataKeyNames="ID">
</asp:GridView>
<asp:ObjectDataSource ID="odsUsers" runat="server" SelectMethod="GET_USERS"
TypeName="oDAL">
</asp:ObjectDataSource>
<asp:Button ID="btnUpdate" runat="server" Text="Update Permissions" OnClick="btnUpdate_OnClick"/>
Code Behind:
private static string[] excludeCols = { "ID", "Username" };
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) // Removing the IsPostBack check refreshes the GridView when the Update button is clicked
bindGridViewWithHiddenID(gvUsers, ((DataView)odsUsers.Select()).Table, excludeCols);
}
public static bool bindGridViewWithHiddenID(GridView gv, DataTable dt, string[] excludeCols)
{
gv.Columns.Clear();
gv.DataBind();
if (gv != null && dt != null && dt.Rows.Count > 0)
{
DataControlField newField;
foreach (DataColumn column in dt.Columns)
{
if (excludeCols.Contains(column.ColumnName))
{
newField = new BoundField();
((BoundField)newField).DataField = column.ColumnName;
}
else
{
newField = new TemplateField();
((TemplateField)newField).ItemTemplate = new CustomTemplate(column.ColumnName);
}
newField.HeaderText = column.ColumnName;
if (column.ColumnName == "ID" || column.ColumnName.EndsWith("_ID"))
newField.Visible = false;
gv.Columns.Add(newField);
}
gv.DataSource = dt;
gv.DataBind();
return true;
}
return false;
}
// By this time execution reaches here the CheckBoxes have already been reset
protected void btnUpdate_Click(object sender, EventArgs e)
{
...
}
CustomTemplate class:
public class CustomTemplate : ITemplate
{
private string binding;
private static int count = 0;
public CustomTemplate(string colNameBinding)
{
binding = colNameBinding;
}
public void InstantiateIn(Control container)
{
CheckBox chk = new CheckBox();
chk.ID = "chk" + count++;
chk.DataBinding += new EventHandler(this.chk_OnDataBinding);
container.Controls.Add(chk);
}
public void chk_OnDataBinding(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
GridViewRow namingContainer = (GridViewRow)chk.NamingContainer;
DataRowView dataRow = (DataRowView)namingContainer.DataItem;
if (dataRow[binding].ToString() == "1")
chk.Checked = true;
else
chk.Checked = false;
}
This behavior is expected and is normal. It has to do with the Page Life cycle and tracking of ViewState on dynamically added controls. I recommend you read this article from Scott Mitchell, specially the section titled: View State and Dynamically Added Controls.
I tried adding the GridView binding to OnInit() but since the CheckBoxes aren't actually instantiated until the GridView is DataBound, and since DataBinding will revert the GridView back to its original state, I seem to be stuck again.

Control caused the post back

I have a form that contains a dropdownlist,
on index changed method,i will call my user control class .cs with parameters choosen by the user, when im putting my code inside the index changed like the code below, it doesnt work, which is a normal behavior:
protected void ResourceTypesDDL_SelectedIndexChanged(object sender, EventArgs e)
{
....
MyUsercontrol c = new MyUSercontrol(....);
this.panel.controls.add(c);
}
thats why i have to put the code inside my onload method, but the thing is how can i know if it is the ddl that caused the post back? is there a propertie? or should i use page.Request.Params.Get("__EVENTTARGET") technic ?
Thanks alot !
If your MyUserControl is really user control, that means .ascx file, you should use this:
Page.LoadControl("~/Controls/MyUserControl.ascx")
instead of creating the instance of the control by calling constructor directly.
protected void ResourceTypesDDL_SelectedIndexChanged(object sender, EventArgs e) {
....
var c = Page.LoadControl("~/Controls/MyUserControl.ascx");
this.panel.controls.add(c);
}
EDIT:
But of course, after every other post back, you will lose this control. So you should also make sure that you will create all dynamic controls during OnLoad event.
set the property autoPostBack=true on the dropdownlist in order for the page to postback
Or use the below function to get the post back control on the page_load
private string GetPostBackControl()
{
string retVal = string.Empty;
try
{
string ctrlname = Page.Request.Params.Get("__EVENTTARGET");
if (ctrlname != null && ctrlname != string.Empty)
{
Control ctrl = this.Page.FindControl(ctrlname);
if (ctrl != null)
{
retVal = ctrl.ID;
}
}
}
catch (Exception ex) { ManageException(ex, ShowGeneralErrorMessage); }
return retVal;
}
Try setting AutoPostBack="True" property of drop down list. After setting this property when you select an item in list it will automatically do the postback and your event ResourceTypesDDL_SelectedIndexChanged will be fired.

Read data from SqlDataSource or GridView

I have SqlDataSource and GridView on web form. GridView.DataSourceID = mySqlDataSource.
When I call myGridView.DataBind(), all data successfully bind on the page.
How is it possible to read already got data from mySqlDataSource or myGridView objects as DataTable or DataView? Thanks
The data in the gridview can read by using FindControl property of Gridview control. For example, for reading values set in the Checkbox column in the grid.
for (i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chk = (CheckBox)GridView1.Rows[i].FindControl("checkbox1");
//here code for using value captured in chk
}
Provided your data set isn't gigantic, you could store it in the Session, bind your GridView to the Session data, and then re-use the Session data in your other web objects.
Your code would then look something like this (you'll have to forgive any minor inaccuracies -- I'm away from my development box at the moment):
protected override OnInit(object sender, EventArgs e)
{
base.OnInit();
if (Page.IsPostback == false)
{
SetSessionData();
}
//
// Set your GridView, DataTable, DataView, etc. events here.
//
}
void SetSessionData();
{
List<YourDataBoundObject> myDataBoundObject = GetYourDataBoundObject(); // Or Collection<T>, IEnumerable<T>, etc.
Session["data"] = myDataBoundObject;
}
void YourGridView_Load(object sender, EventArgs e)
{
BindYourGridView();
}
void BindYourGridView()
{
YourGridView.DataSource = GetSessionData();
YourGridView.DataBind();
}
List<YourDataBoundObject> GetSessionData()
{
return (List<YourDataBoundObject>) Session["data"];
}
void YourDataTable_Load(object sender, EventArgs e)
{
BindYourDataTable();
}
void BindYourDataTable()
{
YourDataTable.DataSource = GetSessionData();
YourDataTable.DataBind();
}

Resources