ASP.net web page update issue ( Postback?) - c#

Greeting of the day everyone.
Hoping you are all well. I need your help to solve a simple issue ( I an new to C# + ASP.net).
I have created a ASp.net portal. When a user open that portal (web page). the Webpage give him a list of Groups whose he is the member of and the list of group whose he can add to himself..
It also contain two Drop Downs. One contains the list of groups, whose use can add to themselves. The second one contains the list of groups , whose the user is member of, and he can remove it from those groups.
Adding and removing code is working fine. But I have to refresh the page manually to show the updated information. After clicking the Add or Remove Button page is not refreshing with the updated information.
I tried to use redirected to main page using Response.Redirect("Success.aspx")
But nothing working,
protected void Page_Load(object sender, EventArgs e)
{
string uN = "domain\\michael.jackson";
//SystemResources sr = new SystemResources();
//ActiveUser usr = sr.GetUserDetails(uN).FirstOrDefault();
LabelUserName.Text = "michael.jackson";
// Getting the list of groups using of praticular OU the classOrgUnitGroup
string sdomain = ClassGroupPortalSettings.getDomainName();
string sInterstOU = "OU=testing,DC=analysys,DC=com";
classOrgUnitGroup a = new classOrgUnitGroup();
List<string> allGroups = a.GetGroupFromOu(sdomain, sInterstOU);
string grouplist = "<ul>";
foreach (string group in allGroups)
{
grouplist = grouplist + "<li><a href='showgroupmembers.aspx?group=" + group + "'>" + group + "</a></li>";
}
grouplist = grouplist + "</ul>";
lblOpenGroups.Text = grouplist;
//// 4. Finding users group membership.
string sDomain = ClassGroupPortalSettings.getDomainName();
classUserGroupMembership myMembership = new classUserGroupMembership();
List<string> myGroupsMem = myMembership.getMyGroupMembership(sDomain, "domain\\michael.jackson");
string glList = "<ul>";
string openlList = "<ul>";
string otherGroup = "<ul>";
foreach (string grp in myGroupsMem)
{
//BulletedListMyGroups.Items.Add(grp);
glList = glList + "<li>" + grp + "</li>";
if (allGroups.Contains(grp))
{
DropDownListMyGroups.Items.Add(grp);
openlList = openlList + "<li>" + grp + "</li>";
}
else
{
otherGroup = otherGroup + "<li>" + grp + "</li>";
}
}
glList = glList + "</ul>";
openlList = openlList + "</ul>";
otherGroup = otherGroup + "</ul>";
LabelOtherGrp.Text = otherGroup;
LabelOpenGrp.Text = openlList;
// LabelMyGroup.Text = glList;
foreach (string emailGroup in allGroups)
{
if (!myGroupsMem.Contains(emailGroup))
{
DropDownListOpenGroups.Items.Add(emailGroup);
}
}
}
This is code which run when a page reload.
The issue is : When I click on Remove Button or Add Button, it run the code to add or remove user from selected group. when page reload after clicking on button. The Group membership labels. and Dropdown box is not updating with code :(

I'm assuming your scenario like this, you're having two Drop down. One is full of records and the items can be select. Once items are selected, user will submit the button then records will save into database/xml. Later you're retrieving the items from db/xml and showing that in second Drop down.
Now you're issue is that the records are not showing in second Drop down after clicking the submit button,
If it so, you have two options.
1) You can pull your records as soon as insert things made into db.
2) You can pull your records in Page load itself as I mentioned below,
If(Postback) // Or If(PostBack == true)
{
// Pull your records and display in Drop down.
}

It is just the order of events which causing confusion IMO. Page_Load is called first and then control events(click, change etc). So on add/delete you need to rebind the items.
https://msdn.microsoft.com/en-gb/library/ms178472%28v=vs.100%29.aspx
Move out the data bind logic to a function and call function at the end of click event as well. Then you can reuse the function in page load and put logic to bind in page load only of its not postback because you might be rebinding unnecessarily in page load.
protected void Page_Load(object sender, EventArgs args)
{
if(!IsPostBack)
{
DataBindLogic();
}
}
private void DataBindLogic()
{
/*Put databind code here */
}
protected void RemoveBtn_Click(Object sender,Eventargs args)
{
/*Do db update */
DataBindLogic();
}

Thanks a lot everyone and and each of you for your time and help and energy, thanks a ton.
The issue is resolved, I have added another lines of code in the Postback, which checks the action of the User.
For example, if used Remove from the Group,
Then get the name of the Group and use action REMOVE
Then Update the DropDown box and Current membership box.
I did the same for the add group too, and it resolved the issue for me.
Thanks again , and whishing you a great day ahead.
Regards and Best wishes
Aman

Related

Why are my list controls being cleared after being populated in WizardStep0 in an ASP.NET Wizard control?

I'm using a Wizard control in an ASP.NET application. In several of the WizardSteps, I'm populating a DropDownList and a CheckBoxList in the Activate event of the step. This works correctly in all steps except WizardStep0. What's happening is that the code is running to populate the lists, but once rendering is complete on WizardStep0, the list controls are empty, as if they've been cleared.
Here's the WizardStep0_Activate method:
protected void WizardStep0_Activate(object sender, EventArgs e)
{
//Initialize dropdowns
PopulateRelationList(ddlRelation);
PopulateGuardianshipTypeList();
} //end method WizardStep0_Activate
Here are the two methods called in WizardStep0_Activate (the method BindSelectionListLocalized works elsewhere, so I know the problem isn't there):
protected void PopulateRelationList(DropDownList ddlist)
{
//First, clear the list
ddlist.Items.Clear();
string valueField = "RelationID";
string textField = "Relation";
string query = "SELECT CONVERT(nvarchar(2), RelationID) AS RelationID, Relation FROM tlkRelation WHERE Lang ='" + lang + "'";
DBFunctions.BindSelectionListLocalized(query, textField, valueField, ddlist, GetGlobalResourceObject("LocalizedText", "selectDDL").ToString());
} //end method PopulateRelationList
protected void PopulateGuardianshipTypeList()
{
//First, clear the list
cblGuardianshipType.Items.Clear();
string valueField = "GuardianshipType";
string textField = "TypeDescr";
string query = "SELECT GuardianshipType, TypeDescr FROM tlkGuardianshipTypes WHERE Lang = '" + lang + "'";
DBFunctions.BindSelectionListLocalized(query, textField, valueField, cblGuardianshipType, null);
}
Here's what I'm getting (just the two list controls mentioned above) - the "Type of Guardianship Requested" should have a CheckBoxList with four items next to it; the "Relation to Client" DropDownList should have several choices:
The most important information is that the same code works correctly in the Activate events for all subsequent WizardSteps, just not for WizardStep0. When I run this in the debugger, WizardStep0_Activate is firing, and the methods to populate the list controls are running; the offending controls are somehow being cleared afterwards, when the page is rendered.

How to return value back to parent page from window.ShowModelDialog?

I'm facing some issue with returning value back to the parent page.
Please kindly help.
I have a gridview that allow users to add new record at the row, but users also can click on the Search button on the row, and I will show a pop up with the below code.
TextBox txtCarNo = gvLookup.FooterRow.FindControl("txtNo") as TextBox;
System.Text.StringBuilder s = new System.Text.StringBuilder();
s.Append("<script language='javascript' id='SearchResult'> " );
s.Append("var WinSettings = 'dialogHeight:400px ; dialogWidth: 550px ;center: Yes ;resizable: No;status: no'; ");
s.Append("javascript: window.showModalDialog('Search.aspx?no=" + txtNo.Text.Trim().ToUpper() + "','',WinSettings); ");
s.Append("</script > ");
if ((!ClientScript.IsStartupScriptRegistered("SearchResult")))
{
ClientScript.RegisterStartupScript(this.GetType(), "SearchResult", s.ToString());
}
At the child page, there will be another gridview that shows the search result, and users can click on one of the row to return the number back to the parent page.
I thought of using Session to pass the value back, but when showing the ShowModalDialog, the code at the parent page already went through, meaning Session won't work on this scenario.
Please advise how do I return a value to the parent page.
Appreciate very much.
Example from Wrox
When you call showModalDialog you do this:
var oReturnValue = showModalDialog(....);
Within showModalDialog, assuming your textboxes have IDs of "txtForename" and "txtSurname":
<body onbeforeunload="terminate();">
function terminate()
{
var o = new Object();
o.forename = document.getElementById("txtForename").value;
o.surname = document.getElementById("txtSurname").value;
window.returnValue = o;
}
Then continuing in your main window:
alert(oReturnValue.forename + "\n" + oReturnValue.surname);

Asp.Net Get Control Values from PlaceHolder

I have defined a placeholder in my page like this;
<asp:PlaceHolder ID="attrPlaceHolder" runat="server"></asp:PlaceHolder>
I am populating this place holder from a database table using query string productId like this;
// obtain the attributes of the product
DataTable attrTable = CatalogAccess.GetProductAttributes(productId);
// temp variables
string prevAttributeName = "";
string attributeName, attributeValue, attributeValueId;
// current DropDown for attribute values
Label attributeNameLabel;
DropDownList attributeValuesDropDown = new DropDownList();
// read the list of attributes
foreach (DataRow r in attrTable.Rows)
{
// get attribute data
attributeName = r["AttributeName"].ToString();
attributeValue = r["AttributeValue"].ToString();
attributeValueId = r["AttributeValueID"].ToString();
// if starting a new attribute (e.g. Color, Size)
if (attributeName != prevAttributeName)
{
prevAttributeName = attributeName;
attributeNameLabel = new Label();
attributeNameLabel.Text = "<li class=\"txt\">" + attributeName + ":</li>";
attributeValuesDropDown = new DropDownList();
attrPlaceHolder.Controls.Add(attributeNameLabel);
attrPlaceHolder.Controls.Add(attributeValuesDropDown);
}
// add a new attribute value to the DropDownList
attributeValuesDropDown.Items.Add(new ListItem(attributeValue, attributeValueId));
}
However, when inside a button click event, when I loop through this place using visual studio debugging, I saw that the visual studio studio debugger first hit the "attrPlaceHolder.Controls" word in my foreach loop, then secondly comes to 'in' keyword (in foreach loop) but it isn't hitting the first two words (i-e 'Control cnt' in my foreach loop. Here it looks;
protected void ButtonBuyNow_Click(object sender, EventArgs e)
{
// Retrieve the selected product options
string options = "";
foreach (Control cnt in attrPlaceHolder.Controls)
{
if (cnt is Label)
{
Label attrLabel = (Label)cnt;
options += attrLabel.Text;
}
if (cnt is DropDownList)
{
DropDownList attrDropDown = (DropDownList)cnt;
options += attrDropDown.Items[attrDropDown.SelectedIndex] + "; ";
}
}
// Add the product to the shopping cart
ShoppingCartAccess.AddItem(productId, options);
}
Basically I need 'options' variable to be populated but it isn't hitting the foreach loop inside, therefore I am not able to get the 'options' variable populated.
This is a serious problem in my application. Please tell me why I can't get the inside the foreach loop.
NOTE:
please note that this isn't the complete code of my entire page. My rest of the code executes correctly.
why I can't get the inside the foreach loop
Because the list is empty.
Why is the list empty? (Would be the next logical question)
Because, at ASP.Net, dynamically created controls must be re-created at Page_Init in order to exist. When you create them at this stage, the page lifecycle will bind the viewstate and will be ready for use.
If you receive a postback (from the button, for example) and don't recreate them, they simply don't exist.

Postback not maintaining selected values

I have a page with several dynamically generated DropDownLists. The DDs load and display the correct values on page load. However, when I try to retrieve the values at post back, the DDs all seem to be maintaining the values they had at page load.
All are created in Page_Load;
No test for IsPostBack;
Processing is handled in code below:
void btnSubmit_Click(object sender, EventArgs e)
{
System.IO.StreamWriter sw = new System.IO.StreamWriter(Server.MapPath("\\") + "\\Logs\\Permissions.log",false);
string szMask = hMask.Value.ToString();
sw.WriteLine("\t\t\t\t\t\t\t" + szMask);
foreach (Control c in Page.Controls)
LoopControls(c, szMask, sw);
sw.Close();
}
private void LoopControls(Control Page, string szMask, System.IO.StreamWriter sw)
{
foreach (Control c in Page.Controls)
{
if (c is DropDownList)
{
string szId = c.ID;
if (szId.StartsWith("ddlPerm"))
{
string[] szSplit = szId.Split(':');
int iMaskPosition = Convert.ToInt32(szSplit[1].ToString());
int iSecurityPermissionID = Convert.ToInt32(szSplit[2].ToString());
DropDownList dd = (DropDownList)c;
string szPermission = dd.SelectedValue.ToString();
if (szMask.Substring(iMaskPosition, 1) != szPermission)
{
sw.WriteLine("NE");
if (iMaskPosition == 0)
szMask = szPermission + szMask.Substring(1);
else
szMask = szMask.Substring(0, iMaskPosition) + szPermission + szMask.Substring(iMaskPosition);
}
sw.WriteLine(szId + "\t\t" + iMaskPosition.ToString() + "\t" + iSecurityPermissionID.ToString() + "\t" + szPermission + "\t\t" + szMask);
}
}
else
{
if (c.Controls.Count > 0)
{
LoopControls(c, szMask, sw);
}
}
}
}
This is really bugging me. Any help would be greatly appreciated.
Thanks,
jb
Normally, this problem can be solved by
if (!IsPostback){
// bind all your dropdownlist here
}
Otherwise the selected values will be lost after rebinding.
ViewState is maintained between the Init and Load events. By creating and populating your controls during Load, you're basically coming in after ViewState has already been handled. Create your controls during Init and you should notice your postback values sticking.
For more information regarding what happens between and at each particular stage of the life cycle, consult the information at this link: http://msdn.microsoft.com/en-us/library/ms178472.aspx
The problem may be, as you said No test for IsPostBack. You're likely overwriting the values and state each time.
Instead, test for IsPostback and don't write them out if it's true.
All are created in Page_Load; No test
for IsPostBack; Processing is handled
in code
If you aren't testing for IsPostBack then on every page load the dropdowns are being recreated.
You need to test for IsPostBack and only create the dropdowns when it's not a PostBack. AKA - On the first load.

C# dynamically created control issue

i'm having issues retreiving the values out of a dynamically created dropdownlist. all controls are created in the Page_Init section. the listitems are added at that time as well from an array of listitems. (the controls are named the same so should be accessable to the viewstate for appropriate setting.)
here is the function that attempts to retrieve the values:
protected void Eng98AssignmentComplete_Click(object sender, EventArgs e)
{
String myID = "0";
Page page = Page;
Control postbackControlInstance = null;
// handle the Button control postbacks
for (int i = 0; i < page.Request.Form.Keys.Count; i++)
{
postbackControlInstance = page.FindControl(page.Request.Form.Keys[i]);
//Response.Write(page.Request.Form.Keys[i].ToString());
if (postbackControlInstance is System.Web.UI.WebControls.Button)
{
myID = Convert.ToString(
postbackControlInstance.ID.Replace("button_", ""));
}
}
String txtholder = "ctl00$ContentPlaceHolder$Eng098Instructors_" + myID;
Response.Write("MYID: " + myID + "<br/>");
DropDownList ddInstructorCheck = (DropDownList)Page.FindControl(txtholder);
Response.Write("Instructor Selected: "
+ ddInstructorCheck.SelectedValue + "<br/>");
}
here is the output I get, no matter which instructor was selected.....
MYID: 1_1
Instructor Selected: 0
ctl00$ContentPlaceHolder$Eng098Instructors_1_1
the name of the control is correct (verified via view source)....
ideas?
You're going to a lot of work to build this fancy string:
ctl00$ContentPlaceHolder$Eng098Instructors_1_1
That is the client ID of your control, not the server id. This code is running on the server side, and so you need the server id. To get that control using the server id, you need to do this:
ContentPlaceHolder.FindControl("Eng08Instructors_1_1");
Notice I didn't look in the page, because your content place holder created a new naming container.
Also, the way your loop is set up the myID variable will always end up holding the last button in the Keys collection. Why even bother with the loop?
Based on your comments, a better way to find the id of the dropdownlist is like this:
string id = ((Control)sender).ID.Replace("button_", "Eng098Instructors_");
why not just save the control in an instance in your class so that you don't have to use FindControl?
Do you also re-create the controls during the postback? Dynamically generated/added controls must be re-created with every request, they are not automatically re-created.
Why don't you cast the sender? This should be the button that caused the postback:
string myId = "0";
Button btn = sender as Button;
if (btn != null)
myId = btn.ID
...
You need to perform something like this because the UniqueID property is the key in Request.Form.
List<Button> buttons = new List<Button>();
List<DropDownList> dropdowns = new List<DropDownList>();
foreach (Control c in Controls)
{
Button b = (c as Button);
if (b != null)
{
buttons.Add(b);
}
DropDownList d = (c as DropDownList);
if (d != null)
{
dropdowns.Add(d);
}
}
foreach (String key in Request.Form.Keys)
{
foreach (Button b in buttons)
{
if (b.UniqueID == key)
{
String id = b.ID.Replace("button_", "");
String unique_id = "ctl00$ContentPlaceHolder$Eng098Instructors_" + id;
Response.Write("MYID: " + id + "<br/>");
foreach (DropDownList d in dropdowns)
{
if (d.UniqueID == unique_id)
{
Response.Write("Instructor Selected: " + d.SelectedValue + "<br/>");
break;
}
}
}
}
}
I'm not sure why you are generating the control in code (you can still add items dynamically if you do), but the code that generates the controls would probably be a huge help here. I'm guessing you are not setting the list item value, and instead just setting the list item text. Try seeing what you get from the SelectedText field and post your control creation function.
EDIT:
In response to your comment on #Martin's post, you said "yes I recreate the controls in the Page_Init function each time the page is created (initial or postback)". Are you also setting the selected value when you create them?
You can also use controls on the page even if your data comes from a database, the controls themselves don't have to be dynamically generated.
How about this?
((Button)sender).Parent.FindControl(myid)
Edit:I misunderstood your question. But i think you should follow page lifecycle. it is common issue for dynamically created controls.
I did some research and here is some info about Dynamically Created Controls may help you...
I had 2 catches.... here's what they were.
1. I didn't clear the table I was adding to before re-creating the controls.
apparently my attention to detail was off yesterday, i'm pretty sure the ctlXX frontrunner of the control was some different number upon postback due to how I was recreating the controls.
2. I was assigning the same list to all the dropdownlist controls.
once I called the lookup upon each creation a dropdownlist control, all works well.
anyway for what it's worth....

Categories

Resources