ASP.Net Control Visible=False Random Data Problem - asp.net

Does anyone know of an issue with setting the Visible property of a control to false causing the value to change?
In the code below, the line:
control.Visible = dr.ParmDisplay;
On some servers, if the control is not visible it is not saving the value that was just set above it. We have a test server that this code works just fine, but we have a customer that the value is not saving. If the control is visible, it saves/shows/stores the value just fine on any server.
Is there some security patch that changes how this works??? I've Google'd it, and I don't find anything related to the visible property having this affect.
Here's the full code for this procedure:
protected void LoadReport()
{
dsReport.ReportParametersDataTable dt = objLoadXml.GetReportParameters(objReport.ReportName);
foreach (dsReport.ReportParametersRow dr in dt.Rows)
{
Control control = null;
IParm parameterControl = null;
if (dr.ParmType.ToUpper().StartsWith("DATERANGE"))
{
control = LoadControl("./UserControls/DateRange.ascx");
}
else if (dr.ParmType.ToUpper().StartsWith("DATE"))
{
control = LoadControl("./UserControls/Date.ascx");
}
else
{
control = LoadControl("./UserControls/Parameter.ascx");
}
control.EnableViewState = true;
parameterControl = (IParm)control;
parameterControl.ParmName = dr.ParmName;
parameterControl.ParmDescription = dr.ParmDescription;
parameterControl.ParmPickList = dr.ParmPickList.ToString();
if (dr["ParmDefaultValue"].ToString() != "")
parameterControl.ParmDefaultValue = dr.ParmDefaultValue;
control.Visible = dr.ParmDisplay;
PlaceHolder1.Controls.Add(control);
}
Thanks.

When you set a control to not visible, it does not get rendered to the browser. Therefore it will not be there on post back and the value won't make it back to the server.
If you need to persist the value w/out showing the control, store it directly in view state, or hidden input etc.

Related

Kentico CmsRepeater: When to call databind when DataBindByDefault="false"

I want to set DataBindByDefault to false on my repeater because otherwise it makes a call to the db which returns all data from the child nodes of the page which comes to 12MB.
I've hacked it for now and set the Path value to "." (same page only) in the code in front but it's still an extra db call.
So my plan was to set DataBindByDefault to false, assign the data from my custom query to the repeater and then call databind() as follows:
<cms:CMSRepeater ID="repItems" runat="server" Path="."/>
private void InitRepeater()
{
var data = (DataSet)NewsProvider.GetNews(ClassNames, Path, MaxRelativeLevel, OrderBy, WhereStatement, SelectTopN, -1, -1);
if (!DataHelper.DataSourceIsEmpty(data))
{
repItems.DataSource = data;
repItems.ControlContext = ControlContext;
repItems.EnablePaging = true;
repItems.PageSize = PageSize;
repItems.PagerControl.CurrentPage = 1;
repItems.PagerControl.PageSize = PageSize;
repItems.PagerControl.Visible = false;
repItems.HideControlForZeroRows = true;
repItems.TransformationName = Transformation;
repItems.DataBind();
}
}
InitRepeater() is called from SetupControl() which called from OnContentLoaded() and ReloadData() but nothing gets rendered.
If I try calling InitRepeater() in PreRender it renders but it ignores the paging settings.
I'm using Kentico v12.0.65
You should be using the LoadPagesIndividually property of the repeater control. If true, each page is loaded individually in case of paging.

HiddenField empty and Viewstate value null on Page_Load

This issue started when trying to get a DevExpress ASPxPopupControl to show after pressing a button. Using popup.ShowOnPageLoad = true; didn't seem to suffice, checking the value on Page_Load shows it reverts to false, even though the code on the server definitely executed.
So I decided to have a variable that reads from and writes to the ViewState so it persists. I then had the variable:
bool ShowPopup
{
get
{
if (ViewState["ShowPopup"] == null)
return false;
return (bool)ViewState["ShowPopup"];
}
set
{
ViewState["ShowPopup"] = value;
}
}
Which was called on the button press by simply ShowPopup = true. When using popup.ShowOnPageLoad = ShowPopup; in Page_Load, ViewState["ShowPopup"] is null and therefore it returns false.
I then tried to use a HiddenField. So I changed ShowPopup to:
bool ShowPopup
{
get
{
return hfShowPopup.Value != "" && hfShowPopup.Value.ToLower() != "false";
}
set
{
hfShowPopup.Value = value.ToString();
}
}
Again using ShowPopup = true on button click, when ShowPopup is read in Page_Load its value is "" and again therefore ShowPopup is false.
I then tried to set the HiddenField directly via hfShowPopup.Value = "true"; and using
popupDuplicatePlayer.ShowOnPageLoad = hfShowPopup.Value != "" && hfShowPopup.Value.ToLower() != "false";
in Page_Load, but again hfShowPopup.Value is empty.
I have used a number of other variables reading from/writing to the ViewState in the same page and they work fine. I know that ViewState and HiddenField might not exist early in the page life cycle but there are being used in Page_Load and so should be fine? I also tried to access them in Page_LoadComplete with the same issues. There are no UpdatePanels on the page so this isn't an issue, is there any other reason for this?
I would assume that the issue with the ViewState, HiddenField AND the ShowOnPageLoad being set directly are related?
Rather silly mistake from me. In the button press I redirected to the current page, rather than allowing the post back. Therefore the values are lost on Page_Load. Very silly, but I figured it out anyway.

Dynamic controls(Textbox) in asp.net

I want to create dynamic text boxes during run time.
Suppose im gettng a text from a database as "# is the capital of India" now i want to replace that "#" by text box while it is rendered to user as below
<asp:TextBox runat="server" id = "someid"></asp:TextBox> is the capital of India
Im able to get the textbox and text as combination. However I cannot access the textboxes with the given id and when any event occurs on the page the textboxes are lost as they logically does not exist untill their state is stored.
I also went through the concepts of place holder and Viewstate to store the dynamically created controls and make their id's available for the methods, but as far as I tried I could not meet the textbox and text combination requirement.
Im looping over the entire text recieved from database and checking if there is any"#". Is yes then i want to replace it with a textbox on which i can call methods to take back the value entered in the text box to database and store it.
eg: text is "#" is the capital of India
for (int i = 0; i < que.Length; j++) //que holds the text
{
if (que[i] == '#')
{
//Textbox should be created
}
else
{
//the texts should be appended before or after the textbox/textboxes as text demands
}
}
On button click I'm passing request to database, which will send me necessary details i.e. question text, options and also saves the current checked value etc.
protected void BtnLast_Click(object sender, EventArgs e)
{
CheckBox1.Checked = false;
CheckBox2.Checked = false;
CheckBox3.Checked = false;
CheckBox4.Checked = false;
QuestionSet q = new QuestionSet();
StudentB b = new StudentB();
q = b.GetQuestion(1, 1, qid, 'L', 0, Checked, date);
qid = Convert.ToInt32(q.Question_Id);
Checked = q.Checked;
if (q.Question_Type == 11) //indicates its objective Question
{
//ill bind data to checkboxes
}
else if (q.Question_Type == 12) // indicate its fill in the blanks question
{
for (int j = 0; j < que.Length; j++)
{
if (que[j] == '#')
{
count++;
string res = "<input type = 'text' runat = 'server' id ='TxtBoxFillUp" + count + "'/>";
htm = htm.Append(res);
}
else
{
htm = htm.Append(que[j]);
}
}
}
}
Any help will be greatly appreciated, thanks in advance.
Adding control in the way you do it won't create control as asp.net creates it. You do have to create controls as usual .net object.
TextBox myNewTextBox = new TextBox() {};
// Set all initial values to it
And add this cotrol to placeholder or panel, whatever you use. Keep in mind that asp.net page events fire even if you use update panel, so in order to maintain state and events of newly created controls you have take care of creating such controls long before page's Load event fires. Here is my answer to another simialiar question.
Seeing the requirements you have:
1.) You need to use JavaScript. Since the ASP.NET will not recreate controls which are dynamically added. Dynamically added controls need to be recreated after every postback. This is the reason why your TextBoxes are Lost after every postback.
2.) You can write JavaScript code to Hide and show the textboxes for blank texts since at every button click you can call Client side functions using: OnClientClick() property of buttons.
3.) Also to Get the TextBoxes using ID property, add them in Markup( .aspx ) portion itself.

Resetting PageIndex when refreshing data source

I am trying to implement paging when reading from a huge database. When user moves to a page outside a window, i fetch the next set of records and populate the table for 9-10 pages. Problem is, after refreshing data source, i am not able to reset the PageIndex to 0, it is still on the last page after refresh.
My code is as follows:
protected void AccountQueueGrid_PageIndexChanged(object sender, Telerik.Web.UI.GridPageChangedEventArgs e)
{
int newWindowNumber = currentWindowNumber() + ( e.NewPageIndex / (windowSize / PageSize));
if (newWindowNumber != currentWindowNumber())
{
PopulateAccountQueueGrid(newWindowNumber, true);
AccountQueueGrid.CurrentPageIndex = 0;
AccountQueueGrid.Rebind();
}
}
PopulateAccountQueueGrid gets the new data and sets as DataSource and calls DataBind too. That part works fine. But setting CurrentPageIndex and then Rebinding doesnt reset it to 0.
Have tried setting AccountQueueGrid.MasterTableView.CurrentPageIndex also, doesnt work.
AllowPaging and EnableViewState are set to true.
Set your page index to 0 (zero) before binding the datasource
below example perfectly worked for me.
AccountQueueGrid.CurrentPageIndex = 0;
AccountQueueGrid.DataSource = dsList.Tables[0];
AccountQueueGrid.Rebind();

why my view state not getting cleared and on reload it save the value to the databse again?

I am having user control registered on a aspx page.
there is a button on user control resisted on some aspx page that perform some action to store the value of viewste to the database, and below that i have cleared my viewstate value, but if i do right click and reload the page it reinsert the values to the data base, what i am missing or the viewstate do not get cleared, how should i prevent it to resave the same entries to the database.
I am partially writing my code below.
protected void btnFinish_Click(object sender, EventArgs e)
{
if (ViewState["dtQuestions"] != null)
{
foreach (DataRow dr in dtQuestions.Rows)
{
int currQueScore = GetAnswerScore(dr["AnswerType"].ToString().Trim(), dr["ClientAnswerValue"].ToString().Trim());
dr["ClientAnswerScore"] = currQueScore;
myScore += currQueScore;
SurveyClientAnswer objDetail = new SurveyClientAnswer();
objDetail.SurveyClientID = objMaster.SurveyClientID;
objDetail.QuestionID = int.Parse(dr["QuestionID"].ToString());
objDetail.Answer = dr["ClientAnswerValue"].ToString();
objDetail.Score = int.Parse(dr["ClientAnswerScore"].ToString());
DB.SurveyClientAnswers.InsertOnSubmit(objDetail);
DB.SubmitChanges();
}
objMaster.FinalScore = myScore;
DB.SubmitChanges();
ViewState["dtQuestions"] = null;
}
else
{
ModalPopupExtender1.Show();
pnl.Visible = true;
}
}
If you don't want to reinsert the data, simply create a unique constraint on the database to disallow this scenario.
As far as doing it in code, you could possibly only insert the data adding this condition to the if statement:
if(IsPostBack && (ViewState["dtQuestions"] != null)
{
//meaning the user is not simply reloading the page but actually posting back
}
Note that there might be some corner cases where this won't work. Without testing is difficult to know but I strongly believe that this should be handled at the database level instead.

Resources