I'm using a dropdownlist which allows the user to choose a value (representing a client name.) I'm binding that list in the Page_Load doing it like that :
if(!IsPostBack)
{
var airClients = (from ac in db.AIR_CLIENTS orderby ac.CLIENT select ac.CLIENT).ToList();
ddlClients.DataSource = airClients;
ddlClients.DataBind();
}
If I'm reaching my Edit view (with all the fields filled, including that dropdownlist), I can change the client by selecting another one in the list. However, when I'm saving, the new selected value is not taken into account. I'm trying to get it by doing that :
protected void btnSave_Click(object sender, EventArgs e)
{
Entities db = new Entities();
if (Session["id"] != null)
{
int id = Convert.ToInt32(Session["id"].ToString());
SIMULATION simulation = (from s in db.SIMULATION where s.SIMULATION_ID == id select s).FirstOrDefault();
string client = ddlClients.SelectedItem.Text;
AIR_CLIENTS currentClient = (from ac in db.AIR_CLIENTS where ac.CLIENT == client select ac).FirstOrDefault();
int monthNego = Convert.ToInt32(ddlMonthNegotiation.SelectedItem.Text);
int roundNego = Convert.ToInt32(ddlRoundNegotiation.SelectedItem.Text);
simulation.SIMULATION_NAME = mmDesc.Text;
simulation.SIMULATION_TYPE = ddlSimulationType.SelectedItem.Text;
simulation.CLIENT_ID = currentClient.CLIENT_ID;
simulation.SIM_START_DATE = dteStart.Date;
simulation.SIM_END_DATE = dteEnd.Date;
simulation.CONTRACT_YEAR = ddlContractYear.SelectedItem.Text;
simulation.MONTH_OF_NEGOTIATION = monthNego;
simulation.ROUND_OF_NEGOTIATION = roundNego;
db.SaveChanges();
Response.Redirect("MainPage.aspx");
}
}
So in order to have a clear idea of what I want to say, if in my Edit View I've got "Apple" as the original value and I want to change it by selecting "Amazon", when I'm debugging I still see "Apple" as the selected value.
I can't figure out where I should fix the code to make it work. Any idea?
EDIT : ASPX dropdownlist code
<dx:ASPxComboBox runat="server" ID="ddlClients" ClientInstanceName="ddlClients"></dx:ASPxComboBox>
I'm using the DevExpress library but I think it isn't reliable.
Related
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!
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:)
I'm creating a WPF C# application that has a datagrid hooked up to a SQL Server database. The user has the option of editing data in the datagrid by highlighting a row and clicking an edit button which then populates several textboxes with the data from the highlighted row. At this point, the user can then edit the data, click save and the datagrid reflects the changes. Until recently that feature was working fine. However, I was asked to add a feature that displays a highlighted row of data somewhere else on the screen (as looking at a datagrid for too long can become tiresome). So when a user clicks on a row a series of textblocks to the right of the datagrid change to show the data of the highlighted row in an easier to view format. That feature also works fine. The issue I'm having now, is that when a row is highlighted and automatically displays the data in the textblocks, if the user also tries to edit that row, the application crashes. The data displays just fine in the textboxes after the user clicks edit (while simultaneously displaying the same highlighted row in the textblocks); it's just when save is clicked that I run into an issue.
Debugging the program shows that everything is running smoothly. However after clicking save, the debugger jumps back up to my myGridSelectionChanged event and say's "NullReferenceException was unhandled -- Object reference not set to instance of an object" When I reload the program however, the datagrid reflects the changes that I tried to make before the application crashed. I'm assuming that means that the issue doesn't have to do with actually editing the database, rather the problem is with the textblocks not being able to reflect those edits. Below is some of my code:
Here is the code for the save button:
private void saveBtn_Click(object sender, RoutedEventArgs e)
{
var stqmDC = new SqtmLinqDataContext();
var selectedRow = EditGrid.GetSelectedRow(myGrid);
var ID = EditGrid.GetCell(myGrid, selectedRow, 0);
string selectedID = ((TextBlock)ID.Content).Text;
int convertedID = Convert.ToInt32(selectedID);
int newQuantity = int.Parse(quantityTxt.Text);
var query = from info in stqmDC.General_Infos
where info.Quote_ID == convertedID
select info;
foreach (General_Info info in query)
{
info.Customer_Name = customerNameTxt.Text;
info.OEM_Name = oemNameTxt.Text;
info.Qty = newQuantity;
info.Quote_Num = quoteNumberTxt.Text;
info.Fab_Drawing_Num = fabDrawingNumTxt.Text;
info.Rfq_Num = rfqNumberTxt.Text;
info.Rev_Num = revNumberTxt.Text;
}
try
{
stqmDC.SubmitChanges();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
var mainTable = from generalInfo in stqmDC.GetTable<General_Info>()
select new
{
generalInfo.Quote_ID,
generalInfo.Open_Quote,
generalInfo.Customer_Name,
generalInfo.OEM_Name,
generalInfo.Qty,
generalInfo.Quote_Num,
generalInfo.Fab_Drawing_Num,
generalInfo.Rfq_Num,
generalInfo.Rev_Num
};
myGrid.ItemsSource = mainTable;
leftSP.Visibility = Visibility.Hidden;
rightSP.Visibility = Visibility.Hidden;
cancelBtn.Visibility = Visibility.Hidden;
submitBtn.Visibility = Visibility.Hidden;
saveBtn.Visibility = Visibility.Hidden;
sendBtn.Visibility = Visibility.Hidden;
}
And the code for displaying the highlighted row in textblocks:
private void myGridSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var rowSelection = EditGrid.GetSelectedRow(myGrid);
var quoteID = EditGrid.GetCell(myGrid, rowSelection, 0);
string quoteIDEdit = ((TextBlock)quoteID.Content).Text;
QuoteIDtxtblk.Text = quoteIDEdit;
var date = EditGrid.GetCell(myGrid, rowSelection, 1);
string dateEdit = ((TextBlock)date.Content).Text;
Datetxtblk.Text = dateEdit;
var custName = EditGrid.GetCell(myGrid, rowSelection, 2);
string custNameEdit = ((TextBlock)custName.Content).Text;
CustomerNametxtblk.Text = custNameEdit;
var OemName = EditGrid.GetCell(myGrid, rowSelection, 3);
string OemNameEdit = ((TextBlock)OemName.Content).Text;
OemNametxtblk.Text = OemNameEdit;
var Quantity = EditGrid.GetCell(myGrid, rowSelection, 4);
string QuantityEdit = ((TextBlock)Quantity.Content).Text;
Quantitytxtblk.Text = QuantityEdit;
var quoteNum = EditGrid.GetCell(myGrid, rowSelection, 5);
string quoteNumEdit = ((TextBlock)quoteNum.Content).Text;
QuoteNumbertxtblk.Text = quoteNumEdit;
var fabDrawing = EditGrid.GetCell(myGrid, rowSelection, 6);
string fabDrawingEdit = ((TextBlock)fabDrawing.Content).Text;
FabDrawingNumbertxtblk.Text = fabDrawingEdit;
var rfqNum = EditGrid.GetCell(myGrid, rowSelection, 7);
string rfqNumEdit = ((TextBlock)rfqNum.Content).Text;
RfqNumbertxtblk.Text = rfqNumEdit;
var revNum = EditGrid.GetCell(myGrid, rowSelection, 8);
string revNumEdit = ((TextBlock)revNum.Content).Text;
RevNumbertxtblk.Text = revNumEdit;
}
Thanks in advance to anyone who can help.
Where exactly would you think it's handled?
To handle exceptions that cause app crashes you need to exception-proof every "entry point", defined as every spot in your app where unmanaged code can call in or a the code starts running on a different thread.
This includes button click handlers. Add a try/catch in your button handler and show some UI message that an error happened and write a log message or at least a 'Debug.WriteLine(exceptionObjectHere);' so you can see where did the exception come from
You change ItemsSource of a DataGrid in saveBtn_Click which means that your selection will disapear and SelectionChanged will be fired.
So you need to handle this case (myGrid.SelectedItem == null) somewhere, and just do nothing (return) if so.
I got problem facing the problem that i am using the table, "locationstation" and create station and location inside and both the station and location were linked to locationstation by their primary key. I have already successfully showed their data in the combo box but the problem now is that i don't know how to select the data inside the combo box and save the data in the locationstation table.
private void btnCreate_Click(object sender, EventArgs e)
{
using (testEntities Setupctx = new testEntities())
{
//station selectStation = cbStation.SelectedItem as station;
//location selectLocation = cbLocation.SelectedItem as location;
string selectStation = cbStation.SelectedItem.ToString();
string selectLocation = cbLocation.SelectedItem.ToString();
locationstation creLS = new locationstation();
creLS.idStation = cbStation.SelectedItem.ToString();
selectLocation.Location1 = (string)cbLocation.SelectedItem;
Setupctx.locationstations.AddObject(selectStation);
//Setupctx.SaveChanges();
//cbStation.SelectedIndex = -1;
//cbLocation.SelectedIndex = -1;
MessageBox.Show("New Location Station Is Created");
}
}
I don't how to make it working but my codes that i'm trying is right here. Help will be greatly appreciated.
This is the code that i bind the station name and location name into the combo box.
private void Create_LS_Load(object sender, EventArgs e)
{
using (testEntities Setupctx = new testEntities())
{
var storeStation = (from SLS in Setupctx.locationstations
join station s in Setupctx.stations on SLS.idStation equals s.idstations
select s.Station1).Distinct().ToList();
foreach (var LocationStation in storeStation)
{
cbStation.Items.Add(LocationStation);
}
var storeLocation = (from SLS in Setupctx.locationstations
join location l in Setupctx.locations on SLS.idLocation equals l.idlocation
select l.Location1).Distinct().ToList();
foreach (var LocationStation1 in storeLocation)
{
cbLocation.Items.Add(LocationStation1);
}
}
}
Hi set all Navigation properties of selectStation equal to null before Adding the the object using
Setupctx.locationstations.AddObject(selectStation);
instead of
string selectStation = cbStation.SelectedItem.ToString();
use
LocationStation selectStation=(LocationStation)cbStation.SelectedItem;
and then extract values from selectStation or do what you want with it.
I hope this will help.
Station selectStation = (Station)cbStation.SelectedItem ; //cast here to your T
Location selectLocation = (Location)cbLocation.SelectedItem; //cast here to your T
locationstation creLS = new locationstation()
{
StationId=selectStation.Id ,
LocationId=selectLocation.Id
};
Setupctx.locationstations.AddObject(creLS);
Setupctx.SaveChanges();
However I can not imagine doing something like above on the combobox with Key/Value data.
because probably binding lookup types comboboxes to KeyValuePair by using .ToDictionary()
(where T is type of primary key) opens up easier code reuse to handle
selected items and bindings on any combobox in whole app by setting ValueMember = Key
and DisplayMember =Value (or whatever Key/Value properties are in your combo control) then you can do this for example:
long GetSelectedId(comboBox cbo)
{
long IdOut=-1;
if (cbo.SelectedItem==null)
return IdOut;
KeyValuePair<long, string> Item= (KeyValuePair<long, string>)cbo.SelectedItem;
IdOut = Item.Key;
return IdOut;
}
I have a website for dance academy where Users can register and add/drop dance classes.
In the web page to drop a particular dance, for a particular user, the dropdown displays her registered dances.
Now I want to delete one of the dances from the list.
So i'll remove the row from the table and also from the dropdownlist. The problem is that every time the item with the lowest ID (index) is getting deleted, no matter which one the user selects.
I think I am storing the DataTextField and DataValueField for the dropdown incorrectly. Can someone please help me out?
The code is:
private void PopulateDanceDropDown()
{
var registereddanceList = from dd in context.DANCER_AND_DANCE
where dd.UserId == dancerId
select new
{
Text = dd.DanceName,
Value = dd.DanceId
};
dances.DataSource = registereddanceList;
dances.DataTextField = "Text";
dances.DataValueField = "Value";
dances.DataBind();
}
protected void dropthedance(object o, EventArgs e)
{
String strDataValueField = dances.SelectedItem.Value;
int danceIDFromDropDown = Convert.ToInt32(strDataValueField);
var dancer_dance = from dd in context.DANCER_AND_DANCE
where dd.DanceId == danceIDFromDropDown
select dd;
foreach (var dndd in dancer_dance)
{
context.DANCER_AND_DANCE.DeleteOnSubmit(dndd);
}
try
{
context.SubmitChanges();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
PopulateDanceDropDown();
}
<asp:DropDownList ID = "dances" runat="server">
</asp:DropDownList>
<asp:Button ID="dropDance" runat="server" OnClick="dropthedance" Text="Drop Class" BackColor="Maroon" ForeColor="#FFCC99"/>
As your question says you want to access records without storing it in Linq.
So below one could be an alternative for you.
First store all the data from Database to, lets say List<NameIDPair>
Heres what NameIDPair could be:
class NameIDPair
{
public NameIDPair(){}
public string NameValue{get;set;}
public string IDValue{get;set;}
}
Then populate drop down list as follows:
List<NameIDPair> storeInMe = From Database
foreach(NameIDPair pair in storeInMe )
{
ListItem item = new ListItem();
item.Value = pair.IDValue;
item.Text = pair.NameValue;
ddldancesList.Items.Add(item);
}
Then for droppingTheDance, you can call the delete stored procedure to delete the same...
Hope this helps...