asp.net Keep selected value on dynamically populated / created radiobuttonlist - c#

I hope this question hasn't been asked before in this manner, if it has, I sadly can't find it!
I'm currently trying to create a User Control in which I want a client to select a questionnaire from a dropdownmenu which is dynamically populated on page_load like this:
DiscoverConnectData(); //gets the items from a database
var formItems = 0;
using (var osContext = new OrganizationServiceContext(_crmAccessor.OrganisationService))
{
var forms = (from f in osContext.CreateQuery("form") select f);
foreach (var form in forms)
{
var name = formulier.GetAttributeValue<string>("name");
var formId = formulier.GetAttributeValue<Guid>("formid");
DropDownList_RP.Items.Insert(formItems, new ListItem(naam, formId.ToString()));
formItems++;
}
}
I've also tried putting the above code inside an if (!Page.IsPostBack), however this didn't fix my problem... Okay, moving on. When the client has selected a questionnaire and hit a button, I have a piece of code that runs through all the questions and answers related to that specific questionnaire in a for each loop and creates Labels and RadioButtonLists for each question. First it loads the questions and answers related to the selected formId:
var curQuestionName = string.Empty;
var lblId = 0;
_formGuid = new Guid(DropDownList_RP.SelectedValue);
DiscoverConnectData();
using (var osContext = new OrganizationServiceContext(_crmAccessor.OrganisationService))
{
_answerList =
(from a in osContext.CreateQuery("answer")
join v in osContext.CreateQuery("question")
on a["question"] equals v["questionid"]
where ((EntityReference)v["form"]).Id == _formGuid
select new AnswerClass
{
AnswerQuestionId = v.GetAttributeValue<Guid>("questionid"),
QuestionName = v.GetAttributeValue<string>("name"),
Name = a.GetAttributeValue<string>("ansname"),
Score = a.GetAttributeValue<int>("score")
}).ToList();
}
After picking up this data and adding it to a list, I create the Questionnaire items:
foreach (var ant in _answerList)
{
if (ant.QuestionName != curQuestionName)
{
var vLabel = new Label();
var qid = "Q" + lblId;
vLabel.ID = qid;
vLabel.Text = ant.QuestionName;
Questionnaire.Controls.Add(vLabel);
_aRadioList = new RadioButtonList();
var rblId = "list" + lblId;
_aRadioList.ID = rblId;
Questionnaire.Controls.Add(_aRadioList);
Questionnaire.Controls.Add(new LiteralControl("<br />"));
curQuestionName = ant.QuestionName;
lblId++;
}
_aRadioList.Items.Add(new ListItem((" " + ant.Name), ant.Score.ToString()));
}
This all works fine and I'm getting a list with questions and answers neatly put underneath each other. So far so good!
However, the big problem I'm having is the losing of data on page postback. Whenever the user selects certain answers and I then want to show them a score, or do anything else - the page reloads and all my dynamically added controls are lost. Now I have fixed that issue by putting the relevant functionality above into a function and calling that again when I press the button to show a score, and this recreates the questions and answers, but I lose all the selectedvalues. I don't specifically even need to keep the controls on the page or anything, I just need to keep the selectedvalues in order to do stuff with them!
I can't create the controls on page_load or page_init because I need user input to know exactly which questionnaire to pull from the database. I can't use "hard-coded" values for the dropdownlist items either, because that's not the functionality we're aiming for. We need to pull it all from the database - which I can't access directly, I need to use the DiscoverConnectData() function.
Please, if anyone has any ideas in order to get the functionality I want (also if it means exploring a whole new 'avenue'), please let me know!

Related

Making Changes to List Causes DataGridView to show blank

I have a project where a user can add new products or modify existing ones. Products can have parts associated with them. I created a list in the class where my product constructor lives to hold parts for each product.
I'm trying to figure out how to set up that if a user makes changes to the parts that are associated with a product but hits the cancel button then the list reverts to the original list. If they hit the save button after making edits to the products parts list then the updated list is saved and when they open the product again then the updated list displays.
All the code in the file I have is quite a bit but the parts I thought would be most helpful for what I have are...
Filling in the product text boxes with the information on the product. Populating the datagridview CurrentPartsDataGrid with the tempParts list that is a copy of the product.Parts list. Or creating a new empty list if it's a new product that is created.
if (product != null)
{
ProductIdText.Text = product.ID.ToString();
ProductNameText.Text = product.Name.ToString();
InvText.Text = product.QOH.ToString();
PriceText.Text = product.Price.ToString();
InvMinText.Text = product.Min.ToString();
InvMaxText.Text = product.Max.ToString();
tempParts = new BindingList<Part>(product.Parts);
}
else
{
product = new Product();
tempParts = new BindingList<Part>();
}
CurrentPartsDataGrid.DataSource = tempParts;
In the save/cancel button click event methods I have tried doing a for loop or for each loop. I clear the list and then try to repopulate.
Code in save
product.Parts.Clear();
foreach (Part part in tempParts)
{
product.Parts.Add(part);
}
Code in Cancel
tempParts.Clear();
foreach (Part part in product.Parts)
{
tempParts.Add(part);
}
If there is anything else that would be helpful, let me know. I'm new to posting here so don't want to overload the post but also don't want to not provide enough.
Any help on how to fix this would be awesome.
Thanks!
I ended up not needing to do any of the EndEdit() stuff.
In my (if product != null)
I added
tempList = new BindingList<Part>();
for (int i = 0; i < product.Parts.Count; i++)
{
tempList.Add(product.Parts[i]);
}
This created a new templist that when the user selected cancel I set product.Parts = tempList which resolved the issue.

Coded UI test - how to programmatically set a Select Option

I'm writing some coded UI tests to automate testing of some webpages. I've chosen to write the code by hand rather than record a manual testing session.
I can modify controls on the page, for example an input box:
var edit = new HtmlEdit(browser);
edit.SearchProperties.Add(HtmlEdit.PropertyNames.Id, id);
edit.Text = value;
or click on a button:
var btn = new HtmlInputButton(browser);
btn.SearchProperties.Add(HtmlInputButton.PropertyNames.ValueAttribute, "Enter");
Mouse.Click(btn);
I can't work out how to set the value of a dropdown, e.g.
var select = new HtmlControl(browser);
select.SearchProperties.Add(HtmlControl.PropertyNames.Id, "Country");
select.????
the ValueAttribute is read only.
Any ideas?
Use an HtmlComboBox instead. HtmlControl is generic and has limited properties.
HtmlComboBox combox = new HtmlComboBox(browser);
combox.SearchProperties.Add(HtmlControl.PropertyNames.Id, "Country");
//Select by Index
combox.SelectedIndex = 0;
//Select by ITem
combox.SelectedItem = "India";

Panel Does not update TreeView

I have a TreeView that is displayed inside a panel. The data in the TreeView is based on data returned from the database. The first time, the data is correct. The second time, the TreeView is not refreshed, and the previous data is still showing in the tree. I checked the list that contain the data. The list returned the correct data. I've Google the issue, and could not resolved it with some of the answers that were posted. Here is a sample code of how the TreeView is being created and added to the Panel.
ReportGroups gr = new ReportGroups();
var Name = gr.GetReportName(groupID);
TreeView tr = new TreeView();
tr.BeginUpdate();
tr.Size = new Size(570, 600);
tr.Name = "Home";
tr.Nodes.Add("Reports Name");
tr.CheckBoxes = true;
if (Name.Count() > 0)
{
foreach (var item in Name)
{
if (item != null)
{
tr.Nodes[0].Nodes.Add(item.reportName);
}
}
}
tr.Nodes[0].ExpandAll();
tr.EndUpdate();
this.pDisplayReportName.Width = tr.Width * 2;
this.pDisplayReportName.Height = 300;
this.pDisplayReportName.Controls.Add(tr);
this.pDisplayReportName.Refresh();
What am I doing wrong?
try to add this.pDisplayReportName.Clear(); so data will not double up. :)
The easy option would be to use this.pDisplayReportName.Controls.Clear(); just after tr.EndUpdate();. But, this would cause an issue if you have other controls within the same Panel.
The best option would be to use this.pDisplayReportName.Controls.RemoveByKey("MyTree"); instead of this.pDisplayReportName.Controls.Clear();
And, another option would be to add a TreeView in design time (with name tr) rather than dynamically to the panel. Then, use tr.Nodes.Clear(); before tr.BeginUpdate(); and remove following two lines from your code.
TreeView tr = new TreeView();
.
.
.
this.pDisplayReportName.Controls.Add(tr);
Cheers

Retrieve Values from asp control in c# code behind

I have looked extensively to find an answer to this question but I only get extremely close. I have a web form that I use to add and edit records. When a record is selected in the gridview, a session variable is set and then used on page load to populate the text fields. If the session variable is not set, the form will be blank and the logic run as a new record. My problem is that I can add a new record successfully - I debugged and checked to make sure the asp controls passed the proper values to the code behind - but I cannot edit a record successfully. For some reason, the code behind file does not retrieve the proper values from the text boxes. Instead, it keeps the original populated values thus defeating the purpose of the edit. I imagine it is a binding issue but I am unsure and have searched upon end. Here is my code behind file:
protected void Page_Load(object sender, EventArgs e)
{
resultOutput.Visible = false;//Output results as to whether or not a record was added successfully is automatically hidden at page load
//Checking to see if session variable has been created
if (Session["editID"] != null)
{
//Create objects to get recipe data
dbCRUD db = new dbCRUD();
Recipe editRecipe = new Recipe();
//Grabbing session ID
var id = Convert.ToInt32(Session["editID"]);
//Call method to retrieve db data
editRecipe = db.SelectRecord(id);
//Populate results to text boxes
recordID.Text = editRecipe.Recipe_ID.ToString();
addName.Text = editRecipe.Name;
addTypeDDL.SelectedValue = editRecipe.Meal;
addDifficultyDDL.SelectedValue = editRecipe.Difficulty;
addCookTime.Text = editRecipe.Cook_Time.ToString();
addDirections.Text = editRecipe.Directions;
//Change Button Text
submitRecord.Text = "Edit Record";
//Change Title Text
addEditTitle.Text = "Edit Recipe";
}
}
protected void submitRecord_Click(object sender, EventArgs e)
{
Recipe recipe = new Recipe();
dbCRUD newRecord = new dbCRUD();
//Variables for execution results
var modified = "";
int returned = 0;
//Creating the recipe Object to pull the values from the form and
//send the recipe object as a parameter to the method containing insert stored procedure
//depending on Add or Edit
//recipe.Recipe_ID = int.Parse(recordID.Text);
recipe.Name = addName.Text.ToString();
recipe.Meal = addTypeDDL.SelectedValue.ToString();
recipe.Difficulty = addDifficultyDDL.SelectedValue.ToString();
recipe.Cook_Time = int.Parse(addCookTime.Text);
recipe.Directions = addDirections.Text.ToString();
//Checking to see if the page is loaded for edit or new addition
if (Session["editID"] != null)
{
recipe.Recipe_ID = Convert.ToInt32(Session["editID"]);
//If recordID exists, recipe will be passed to UpdateRecord method
returned = newRecord.UpdateRecord(recipe);
modified = "has been edited.";
Session.Remove("editID");
}
else
{
//If recordID does not exist, record will be passed to InsertRecord method (new recipe)
returned = newRecord.InsertRecord(recipe);
modified = "added";
}
//Method returns 0 if successful, 1 if sql error, 2 if other error
if (returned == 1)
{
resultOutput.Text = "There was an sql exception";
resultOutput.Visible = true;
}
else if (returned == 2)
{
resultOutput.Text = "There was a non sql exception";
resultOutput.Visible = true;
}
else
{
resultOutput.Text = "\"" + addName.Text + "\" recipe " + modified;
resultOutput.Visible = true;
}
}
Any object passed to my edit method is successful, however, as I mentioned, it does not grab the newly updated text box values.
Did you try checking PostBack property , Your code is loading the data everytime the page is posted back. So when you update the values in the form and hit update button. The Page_Load method is called first and it reloads all the data (replaces your updated values on the form) and then hit the update button event handler. So everytime your old values are being saved.
You may remove the code from page_load method and put it where you are setting the Session["EditId"] value. This will solve your problem.
I would suggest using a static dataset and bind it to the recordsource of the gridview control. Whenever you wanna edit a record update the dataset simultaneously and rebind it to the gridview control....hope that helps:)

Listview Add Items not appearing C#

I'm working on a small program as part of my A Level Computing course that is designed to track orders. It is written in C# using the Windows Forms.
I am having an issue where I enter all the information for a new order and then press OK and it should update the ListView with the information. I have my ListView in Detail view with 4 columns but nothing ever gets added to the ListView. The section of code that should add the items to the ListView is being executed and is not throwing any errors or causing the program to crash but nothing is being added. Its weird because I am using the exact same method that I used in my little prototype mock up but for some reason now it is not working.
All the things I've found on here or on the internet seem to suggest its an issue with the View mode of the ListView and I've tried modifying this property to no avail.
Any ideas why this section of code is refusing to add anything to the ListView?
//Create an array to store the data to be added to the listbox
string[] orderDetails = { Convert.ToString(id + 1), rNameBox.Text, dateBox.Value.ToString(), orderBox.Text };
//DEBUGGING
Console.WriteLine(orderDetails[0]);
Console.WriteLine(orderDetails[1]);
Console.WriteLine(orderDetails[2]);
Console.WriteLine(orderDetails[3]);
//END DEBUGGING
//Add the order info to the ListView item on the main form
var listViewItem = new ListViewItem(orderDetails);
ths.listView1.Items.Add(listViewItem);
If you need any more information just say. Apologies if this is in the wrong format or something this is my first time here.
Your problem is that your ListViewItem contains a string array and it has no useful way of displaying it.
What you should be doing (there are a number of ways of doing this, but here's one) is creating a class, OrderDetail, with an Id, a Name, a Date, and so on. Give it a ToString() method (public override string ToString()) which returns what you want to display, e.g.:
public override string ToString()
{
return this.Name;
}
Create an instance of OrderDetail and set its properties. Create ListViewItem giving it the OrderDetail instance and add to the ListView. Repeat for as many OrderDetail instances you want.
Cheers -
Added: code which works:
int id = 12;
string rNameBoxText = "rName";
DateTime dateBoxValue = DateTime.Now;
string orderBoxText = "order";
string[] orderDetails = { Convert.ToString(id + 1), rNameBoxText, dateBoxValue.ToString(), orderBoxText };
//DEBUGGING
Console.WriteLine(orderDetails[0]);
Console.WriteLine(orderDetails[1]);
Console.WriteLine(orderDetails[2]);
Console.WriteLine(orderDetails[3]);
//END DEBUGGING
this.listView1.Columns.Clear();
this.listView1.Columns.Add("Id");
this.listView1.Columns.Add("rName");
this.listView1.Columns.Add("Date");
this.listView1.Columns.Add("Order");
this.listView1.View = View.Details;
//Add the order info to the ListView item on the main form
var listViewItem = new ListViewItem(orderDetails);
this.listView1.Items.Add(listViewItem);

Categories