After doing lots of debugging, I've narrowed down as to why my dbContext update does not work.
I have a script that runs on Page_Load that will populate a form based on the query string category_Id which is the primary key of my table.
protected void Page_Load(object sender, EventArgs e)
{
// Populate Edit Fields
if (Request.QueryString["categoryId"] != null)
{
CategoryDAL categoryDAL = new CategoryDAL();
RecipeCategory myCategory = new RecipeCategory();
try
{
addDiv.Attributes["class"] = "hidden";
editDiv.Attributes["class"] = "display";
int categoryToGet = Convert.ToInt32(Request.QueryString["categoryId"]);
myCategory = categoryDAL.GetCategory(categoryToGet);
tbEditCategoryName.Text = myCategory.Category_Name;
tbEditCategoryDescription.Text = myCategory.Description;
ddlEditCategoryGroupList.SelectedValue = Convert.ToString(myCategory.CatGroup_Id);
ddlEditCategoryGroupList.DataBind();
}
catch(Exception ex)
{
updateStatus.Attributes["class"] = "alert alert-info alert-dismissable fade in";
updateStatus.Visible = true;
lblStatus.Text = "Could not get Category Info, please try again.";
}
}
This is my script that runs when the edit_Button is clicked, it should update the row in the database and redirect to the viewCategories page.
protected void btnEditCategory_Click(object sender, EventArgs e)
{
if (Request.QueryString["categoryId"] != null)
{
CategoryDAL categoryDAL = new CategoryDAL();
RecipeCategory myCategory = new RecipeCategory();
try
{
int categoryToEdit = Convert.ToInt32(Request.QueryString["categoryId"]);
myCategory.Category_Name = tbEditCategoryName.Text;
myCategory.Description = tbEditCategoryDescription.Text;
myCategory.CatGroup_Id = Convert.ToInt32(ddlEditCategoryGroupList.SelectedValue);
try
{
bool editStatus = categoryDAL.EditCategory(categoryToEdit, myCategory);
if (editStatus)
{
HttpContext.Current.Session["editStatus"] = "Successful";
Response.Redirect("~/Admin/ManageCategories.aspx");
}
else
{
lblEditStatus.Text = "Unable to update category, please try again";
lblEditStatus.CssClass = "alert-danger";
}
}
catch (Exception ex)
{
lblEditStatus.Text = Convert.ToString(ex);
lblEditStatus.CssClass = "alert-danger";
}
}
catch (Exception ex)
{
updateStatus.Attributes["class"] = "alert alert-info alert-dismissable fade in";
updateStatus.Visible = true;
lblStatus.Text = "Invalid categoryId.";
}
}
else
{
updateStatus.Attributes["class"] = "alert alert-info alert-dismissable fade in";
updateStatus.Visible = true;
lblStatus.Text = "Nothing to update.";
}
}
And this is in my DALayer which holds the functions that has anything to do with categories.
public bool EditCategory(int categoryToEdit, RecipeCategory newCategoryInfo)
{
RecipeXchangeDBContext dbContext = new RecipeXchangeDBContext();
RecipeCategory myCategory = new RecipeCategory();
bool status = false;
myCategory = (from c in dbContext.RecipeCategories
where c.Category_Id == categoryToEdit
select c).First();
myCategory.Category_Name = newCategoryInfo.Category_Name;
myCategory.Description = newCategoryInfo.Description;
myCategory.CatGroup_Id = newCategoryInfo.CatGroup_Id;
try
{
if (dbContext.SaveChanges() == 1)
status = true;
else
status = false;
}
catch (InvalidOperationException ex)
{
status = false;
}
return status;
}
For some reason, whenever I try to update a row with a prepopulated form, the code will always return 0 from dbContext.SaveChanges() and does not update the row in the database.
Note: if I do not populate the form, it works perfectly as normal.
Page_Load doesn't just run the first time the page is loaded, it runs every time the page is loaded, including when the user submits the form. The result is that you're overwriting the user's input before saving it.
In this case, since you're using regular browser navigation to go to a specific category page, you can just check Page.IsPostBack in Page_Load and not set anything in that case.
Related
I have a simple client registration form. I placed some textboxes next to a data grid view, so that I could add and update users. That was working fine and still does.
Recently, I have added a new windows form for client definition, so that when double-clicking a row a form with required field comes up that shows clients information and lets you change them. Clicking the "OK" button will save changes to the SQL database.
With the field beside the grid view, when I update a user info the grid view immediately gets updated and shows data, but when updating data with the new form, updates do not show in the grid view even if I double-click the row again. When I close the app and run it again I will see the updated data.
I have added an activation event for the main form to update the grid view with selecting data again from the database, but no success. This is the code that i am using for the update from side panel:
private void btnUpdate_Click(object sender, EventArgs e)
{
if (btnUpdate.Text == "Update")
{
txtUsername.Text = ClientsGridView.CurrentRow.Cells["Username"].Value.ToString();
txtPassword.Text = ClientsGridView.CurrentRow.Cells["Password"].Value.ToString();
txtUID.Text = ClientsGridView.CurrentRow.Cells["UID"].Value.ToString();
txtName.Text = ClientsGridView.CurrentRow.Cells["Name"].Value.ToString();
chkIsActive.Checked = (bool)ClientsGridView.CurrentRow.Cells["IsActive"].Value;
chkItemListAccess.Checked = (bool)ClientsGridView.CurrentRow.Cells["ItemListAccess"].Value;
chkMaterialSumAccess.Checked = (bool)ClientsGridView.CurrentRow.Cells["MaterialSumAccess"].Value;
chkPartListAccess.Checked = (bool)ClientsGridView.CurrentRow.Cells["PartListAccess"].Value;
chkPriceListAccess.Checked = (bool)ClientsGridView.CurrentRow.Cells["PriceListAccess"].Value;
btnUpdate.Text = "Apply Update";
btnSubmit.Enabled = false;
txtUsername.ReadOnly = true;
}
else if (btnUpdate.Text == "Apply Update")
{
if (ClientFormValidation())
{
int id = Convert.ToInt32(ClientsGridView.CurrentRow.Cells["ID"].Value.ToString());
var SelectedUser = from Client in ClientsContext.Clients
where Client.ID == id
select Client;
if (SelectedUser.Count() == 1)
{
Client UpdatingClient = SelectedUser.Single();
UpdatingClient.Password = txtPassword.Text.Trim();
UpdatingClient.UID = txtUID.Text.Trim();
UpdatingClient.Name = txtName.Text.Trim();
UpdatingClient.IsActive = chkIsActive.Checked;
UpdatingClient.ItemListAccess = chkItemListAccess.Checked;
UpdatingClient.MaterialSumAccess = chkMaterialSumAccess.Checked;
UpdatingClient.PartListAccess = chkPartListAccess.Checked;
UpdatingClient.PriceListAccess = chkPriceListAccess.Checked;
ClientsContext.SubmitChanges();
}
ShowAll();
ClearClientForm();
btnUpdate.Text = "Update";
btnSubmit.Enabled = true;
txtUsername.ReadOnly = false;
}
}
}
and this is for Client definition form:
private void btnOK_Click(object sender, EventArgs e)
{
if(ISnewUser)
{
InsertNewClient();
}
else if(!ISnewUser)
{
UpdateClient();
}
this.Close();
}
private void UpdateClient()
{
if (ClientFormValidation())
{
var SelectedUser = from Client in ClientsContext.Clients
where Client.ID == id
select Client;
if (SelectedUser.Count() == 1)
{
Client UpdatingClient = SelectedUser.Single();
UpdatingClient.Password = txtPassword.Text.Trim();
UpdatingClient.UID = txtUID.Text.Trim();
UpdatingClient.Name = txtName.Text.Trim();
UpdatingClient.IsActive = chkUserActiveSatus.Checked;
UpdatingClient.ItemListAccess = chkItemListAccess.Checked;
UpdatingClient.MaterialSumAccess = chkMaterialSummeryAccess.Checked;
UpdatingClient.PartListAccess = chkPartListAccess.Checked;
UpdatingClient.PriceListAccess = chkPriceListAcess.Checked;
ClientsContext.SubmitChanges();
}
}
}
Can anyone tell me what is wrong with this code?
*var SelectedUser = from Client in ClientsContext.Clients
where Client.ID == id
select Client;
It is Iqueryable, apply .ToList() to fetch into memory and then patch the change.
Instead i suggest , use this,
var SelectedUser = (from Client in ClientsContext.Clients
where Client.ID == id
select Client).FirstOrDefault();
if(SelectedUser!=null){
SelectedUser.Password = txtPassword.Text.Trim();
SelectedUser.UID = txtUID.Text.Trim();
SelectedUser.Name = txtName.Text.Trim();
SelectedUser.IsActive = chkUserActiveSatus.Checked;
SelectedUser.ItemListAccess = chkItemListAccess.Checked;
SelectedUser.MaterialSumAccess = chkMaterialSummeryAccess.Checked;
SelectedUser.PartListAccess = chkPartListAccess.Checked;
SelectedUser.PriceListAccess = chkPriceListAcess.Checked;
ClientsContext.SubmitChanges();
}
else{
//write your logic
}*
I am leaving exception handling to you only.
i solved it myself,
i passed a Client object while initializing the client definition form.
so for updating i used exactly the same object not getting its parapeter and selecting it again from data base:
public frmClientDefinition(Client thisClient=null)
{
InitializeComponent();
if (thisClient!=null)
{
User = thisClient;
id = thisClient.ID;
ISnewUser = false;
txtName.Text = thisClient.Name;
txtUsername.Text = thisClient.Username;
txtPassword.Text = thisClient.Password;
txtDate.Text = thisClient.Date.ToString();
txtUID.Text = thisClient.UID;
chkUserActiveSatus.Checked = thisClient.IsActive;
chkItemListAccess.Checked = thisClient.ItemListAccess;
chkPartListAccess.Checked = thisClient.PartListAccess;
chkMaterialSummeryAccess.Checked = thisClient.MaterialSumAccess;
chkPriceListAcess.Checked = thisClient.PriceListAccess;
chkFullPriceListAccess.Checked = false;
chkOfficialRecieptAccess.Checked = false;
chkNonOfficialRecieptAccess.Checked = false;
chkAdvancedPriceControlsAccess.Checked = false;
chkFullPriceListSaveAccess.Checked = false;
chkOfficialRecieptSaveAccess.Checked = false;
chkNonOfficialRecieptSaveAccess.Checked = false;
txtUsername.ReadOnly = true;
}
txtDate.Text = DateTime.Now.ToString();
}
and for updating this snippet:
private void UpdateClient()
{
if (ClientFormValidation())
{
User.Password = txtPassword.Text.Trim();
User.UID = txtUID.Text.Trim();
User.Name = txtName.Text.Trim();
User.IsActive = chkUserActiveSatus.Checked;
User.ItemListAccess = chkItemListAccess.Checked;
User.MaterialSumAccess = chkMaterialSummeryAccess.Checked;
User.PartListAccess = chkPartListAccess.Checked;
User.PriceListAccess = chkPriceListAcess.Checked;
ClientsContext.SubmitChanges();
}
}
Hi I have one gridview on the left and I have Multiview pane on the right. Basically what I am trying to do is when the use click select in the gridview, the information of that row will display in the Multiview.
I have two view.
View 1 contains label saying please select row to view full details.
View 2 basically retrieving all the necessary data.
The problem is, in my view 2, I do allow user to update the data. When the user updates the data and save, the view will go back to its initial view. And when the user click on the same row, it will then display the updated information.
How can I do such that when they save the changes, the view will show the updated information?
I have tried putting updatepanel but it does not work too.
CODE BEHIND:
protected void Page_Load(object sender, EventArgs e)
{
xxBLL schBLL = new xxBLL ();
GVFBAcc.DataSource = schBLL.getInfo();
GVFBAcc.DataBind();
MainView.ActiveViewIndex = 1;
}
protected void GVFBAcc_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
string Selectedid = GVFBAcc.SelectedRow.Cells[1].Text;//get user id
int selectedIdtoPass = Convert.ToInt32(Selectedid);
xxBLL getRecord = new xxBLL ();
addInfo InfoRetrieve = new addInfo ();
InfoRetrieve = getRecord.getDetail(selectedIdtoPass);
lbid.Text = Convert.ToString(InfoRetrieve .info_id1);
lbType.Text = InfoRetrieve .type;
lbName.Text = InfoRetrieve .name;
lbAbb.Text = InfoRetrieve .abb;
MainView.ActiveViewIndex = 0;
}
catch (Exception ex)
{
lbMessage.Visible = true;
lbMessage.Text = "Please select a Row.";
}
}
protected void editInfo_Click(object sender, ImageClickEventArgs e)
{
MainView.ActiveViewIndex = 0;
string cIcon = editInfo.ImageUrl;
if (cIcon.Equals("~/images/edit.png"))
{
editInfo.ImageUrl = "~/images/save.png";
lblEdit.Text = "";
tbName.Text = lbName.Text;
tbAbb.Text = lbAbb.Text;
tbtype.Text = lbType.Text;
lbName.Visible = false;
lbAbb.Visible = false;
lbType.Visible = true;
tbName.Visible = true;
tbAbb.Visible = true;
tbtype.Visible = false;
}
else if (cIcon.Equals("~/images/save.png"))
{
addInfo[] update = new addInfo[1];
int id = Convert.ToInt32(lbid.Text);
string name = tbName.Text;
string abb = tbAbb.Text;
addInfo updated = new addInfo(name, id, abb);
update[0] = updated;
xxBLL obj = new xxBLL ();
if (obj.updateDetail(update))
{
editInfo.ImageUrl = "~/images/edit.png";
lbName.Visible = true;
lbAbb.Visible = true;
lbType.Visible = true;
tbName.Visible = false;
tbAbb.Visible = false;
tbtype.Visible = false;
lblEdit.Text = "Saved";
lblEdit.ForeColor = Color.Green;
tbName.Text = lbName.Text;
tbAbb.Text = lbAbb.Text;
tbtype.Text = lbType.Text;
}
}
}
When the user updates the data and save, the view will go back to its initial view. And when the user click on the same row, it will then display the updated information. How can I do such that when they save the changes, the view will show the updated information?
or alternative How do i call the button click event at page load so that when the user clicks the save button, it will display the updated infomation
We have aspx page that is being used as a dialog box.
Page has ascx control which has Text box to search available users from oracle DB tables.
Every search click posts back to same control and renders search results.
If I click search and before response is back from server I close the dialog aspx page, then next time I try to open same dialog box it takes forever to render.
Please suggest what could be happening, going wrong?
Any help is highly appreciated
Here is the code
protected void UserListControl_PreRender(object sender, EventArgs e)
{
//set UI text
m_objTitle.Text = TITLE_LABEL;
//Set Properties of search
m_objSearchResults.CacheResults = true;
m_objSearchResults.RefreshCache = true;
m_objSearchResults.DoSearch = true;
m_objSearchResults.Pageable = true;
m_objSearchResults.NoRecordsMessage = NO_RECORDS_MSG;
m_objSearchResults.PageSize = 25;
m_objSearchResults.SearchType = m_sSearchType;
//Add items to the dropdown
if (m_objStatusDropDown.Items.FindByText(AVAIL_USER_TEXT) == null)
{
m_objStatusDropDown.Items.Add(AVAIL_USER_TEXT);
m_objStatusDropDown.Items.FindByText(AVAIL_USER_TEXT).Value = AVAIL_USER_VALUE;
}
if (m_objStatusDropDown.Items.FindByText(ALL_USER_TEXT) == null)
{
m_objStatusDropDown.Items.Add(ALL_USER_TEXT);
m_objStatusDropDown.Items.FindByText(ALL_USER_TEXT).Value = ALL_USER_VALUE;
}
if (m_objStatusDropDown.Items.FindByText(SEARCH_USER_TEXT) == null)
{
m_objStatusDropDown.Items.Add(SEARCH_USER_TEXT);
m_objStatusDropDown.Items.FindByText(SEARCH_USER_TEXT).Value = SEARCH_USER_VALUE;
}
if (this.Page.IsPostBack == false)
{
m_objStatusDropDown.SelectedValue = SEARCH_USER_VALUE;
}
if (IsPostBack)
{
try
{
m_objUserInstructionText.Text = "";
//add the DAO Parameters
string assignmentTypeSelected = Request.QueryString["AssignmentType"];
m_objSearchResults.DAOParams.Add("RequestType", Request.QueryString["RequestType"]);
m_objSearchResults.DAOParams.Add("AssignmentID", Request.QueryString["AssignmentID"]);
m_objSearchResults.DAOParams.Add("AssignmentType", assignmentTypeSelected);
m_objSearchResults.DAOParams["StatusFilter"] = m_objStatusDropDown.SelectedValue.ToUpper();
m_objSearchResults.DAOParams["Name"] = m_objSearchTextBox.Value.Trim();
if (null == SetApplCode(assignmentTypeSelected))
{
throw new ApplicationException("Invalid Assignment Type.");
}
else
{
m_objSearchResults.DAOParams["ApplCode"] = SetApplCode(assignmentTypeSelected).ToUpper();
}
//add searchControl
m_objListPH.Controls.Add(m_objSearchResults);
// Get the values from the ResultsForm
string sRecordsDisplayed = m_objSearchResults.RecordsDisplayed;
string sTableWidth = m_objSearchResults.TableWidth;
bool bPageable = m_objSearchResults.Pageable;
int iCurrentPageIndex = m_objSearchResults.CurrentPageIndex;
int iPageSize = m_objSearchResults.PageSize;
int iRecordCount = m_objSearchResults.RecordCount;
int iEndRecord = m_objSearchResults.EndRecord;
// Create the html if we are paging data
m_objNavigation.Visible = bPageable;
m_objNavigation.DisplayViewAllButton = false;
m_objNavigation.PageSize = iPageSize;
m_objNavigation.Count = iRecordCount;
m_objNavigation.ItemsDisplayText = "Users";
m_objNavigation.CurrentPage = iCurrentPageIndex + 1;
}
catch (ApplicationException ex)
{
m_objInvalidAssignTypeErr.Text = ex.Message;
m_objUserInstructionText.Text = "";
}
}
}
I have this code that works fine when I call it from within the form, however, when I call the same from the Parent it runs through the code without results:
public void hideHelp()
{
//Check in db if panel1 is visible
SqlCeCommand checkHelp = new SqlCeCommand("Select Show_Help from Options where Opt_Id = 1", this.optionsTableAdapter.Connection);
if (this.optionsTableAdapter.Connection.State == ConnectionState.Closed)
{ this.optionsTableAdapter.Connection.Open(); }
try
{
bool showHelp = (bool)(checkHelp.ExecuteScalar());
this.panel1.Visible = showHelp;
this.Refresh();
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
On Main form I have a toggle button with the following code:
private void tglHelp_Click(object sender, EventArgs e)
{
if (tglHelp.ToggleState.ToString() == "On")
{
HRDataSet.OptionsRow updateHelp = hRDataSet.Options.FindByOpt_Id(1);
try
{
updateHelp.Show_Help = true;
this.optionsTableAdapter.Update(this.hRDataSet);
Form activeChild = this.ActiveMdiChild;
if (activeChild.Name == "frmAddEmployees")
{
frmAddEmployees chForm = new frmAddEmployees();
chForm.MdiParent = this;
chForm.hideHelp();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName);
}
tglHelp.Text = "Help Panel \nOFF";
}
Any ideas?
In this piece of code
if (activeChild.Name == "frmAddEmployees")
{
frmAddEmployees chForm = new frmAddEmployees();
chForm.MdiParent = this;
chForm.hideHelp();
}
you open another frmAddEmployees and add to the MDI, but you don't show it.
If your intent was to call the code in the current frmAddEmployees identified by the activeChild you should use something like this
if (activeChild.Name == "frmAddEmployees")
{
((frmAddEmployees)activeChild).hideHelp();
}
I am using Radgrid with pager. When clicking on the next page number on a pager the data is not displaying(not binding the data). Can anyone help me to fix this. here is my code.
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
Session["SearchRes"] = null;
if (Session["TaskName"] != null)
lblTskName.Text = Session["TaskName"].ToString();
Session["FilColms"] = null;
Session["SortExp"] = null;
Session["FilExp"] = null;
Session["ViewAll"] = null;
BindGrid();
}
}
catch (Exception ex)
{
throw ex;
}
}
private void BindGrid()
{
try
{
DataSet dsResult = new DataSet();
clsSearch_BL clsObj = new clsSearch_BL();
clsObj.TaskID = (string)Session["TaskID"];
clsObj.CustName = (string)Session["CustName"];
clsObj.MarketName = (string)Session["MarketName"];
clsObj.HeadendName = (string)Session["HeadendName"];
clsObj.SiteName = (string)Session["SiteName"];
clsObj.TaskStatus = (string)Session["TaskStatus"];
clsObj.OrdType = (string)Session["OrdType"];
clsObj.OrdStatus = (string)Session["OrdStatus"];
clsObj.ProName = (string)Session["ProName"];
clsObj.LOC = (string)Session["LOC"];
clsObj.QuoteID = (string)Session["QuoteID"];
clsObj.CMNumber = (string)Session["CMNumber"];
if (Session["SearchRes"] == null)
{
dsResult = clsObj.getSearchResults_BL(clsObj);
Session["SearchRes"] = dsResult;
}
else
dsResult = (DataSet)Session["SearchRes"];
DataView dataView = dsResult.Tables[0].DefaultView;
rg200.DataSource = dsResult;
rg200.DataBind();
}
catch (Exception ex)
{
throw ex;
}
}
protected void rg200_UpdateCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
{
if (Session["TaskID"] != null)
{
string strTaskID = (string)Session["TaskID"];
if (strTaskID != string.Empty)
{
clsTaskUpdates_BL objBL = new clsTaskUpdates_BL();
GridEditableItem editedItem = e.Item as GridEditableItem;
//Get the primary key value using the DataKeyValue.
string OrdID = editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["orderId"].ToString();
//Access the textbox from the edit form template and store the values in string variables.
string ClarifyAccountNbr = ((GridTextBoxColumnEditor)editedItem.EditManager.GetColumnEditor("Clarify Account Nbr")).TextBoxControl.Text;
string SiteID = ((GridTextBoxColumnEditor)editedItem.EditManager.GetColumnEditor("Site ID")).TextBoxControl.Text;
string QuoteID = ((GridTextBoxColumnEditor)editedItem.EditManager.GetColumnEditor("Quote ID")).TextBoxControl.Text;
CheckBox chkEDP = ((GridCheckBoxColumnEditor)editedItem.EditManager.GetColumnEditor("EDP Created?")).CheckBoxControl;
//string ClarifyAccountNbr = (editedItem["Clarify Account Nbr"].Controls[0] as TextBox).Text;
//string SiteID = (editedItem["Site ID"].Controls[0] as TextBox).Text;
//string QuoteID = (editedItem["Quote ID"].Controls[0] as TextBox).Text;
//CheckBox chkEDP = (editedItem["EDP Created?"].Controls[0] as CheckBox);
try
{
objBL.setTask200_Bl(OrdID, ClarifyAccountNbr, SiteID, QuoteID, chkEDP.Checked);
Session["SearchRes"] = null;
BindGrid();
}
catch (Exception ex)
{
rg200.Controls.Add(new LiteralControl("Unable to update Employee. Reason: " + ex.Message));
e.Canceled = true;
}
}
}
}
protected void rg200_PageIndexChanged(object source, GridPageChangedEventArgs e)
{
try
{
rg200.CurrentPageIndex = e.NewPageIndex;
BindGrid();
}
catch (Exception ex)
{
throw ex;
}
}
Your code shows that you use binding with DataBind() calls. In this way you should manually change the page index hooking PageIndexChanged, assign data source to the grid and bind it. Alternatively, use NeedDataSource binding to spare some manual coding.