i have this project am working on the registration form has four dropdownlist .two are been populated at page load event from the database
if (!IsPostBack)
{
if (!getState()) { return; }
if (!GetFaculty()) { return; }
}
the rest two are been populated at the selectIndexchange of the two (state and faculty)
protected void ddlFaculty_OnSelectedIndexChanged(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
try
{
string sqltext = #"Select Name from Department where FacultyID=" + this.ddlFaculty.SelectedValue.ToString();
List<Department> mlist = new List<Department>();
mlist = ServiceProvider.Instance().GetDepartmentService().GetDepartment_GetDepartment(sqltext);
if (mlist.IsNullOrEmpty()) { return; }
this.ddlDepartment.DataSource = mlist;
this.ddlDepartment.DataTextField = "Name";
this.ddlDepartment.DataValueField = "DepartmentID";
this.ddlDepartment.DataBind();
this.ddlDepartment.Items.Insert(0, new ListItem("--Select Department--", "0"));
}
catch (Exception ex) { return; }
}
}
protected void ddstate_OnSelectedIndexChanged(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
try
{
string sqltext = #"Select Name from University where StateID=" + this.ddlState.SelectedValue.ToString();
List<University> mlist = new List<University>();
mlist = ServiceProvider.Instance().GetUniversityService().GetUniversity_UniversityName(sqltext);
this.dDUniversity.DataSource = mlist;
this.dDUniversity.DataTextField = "Name";
this.dDUniversity.DataValueField = "UniversityID";
this.dDUniversity.DataBind();
this.dDUniversity.Items.Insert(0, new ListItem("-- Select University--", "0"));
this.dDUniversity.SelectedIndex = 0;
}
catch (Exception ex) { return; };
}
}
the problem now is that once i select a value from the selectedIndexChanged of the ddstate in ddUniversity it works fine , then selecting value from the selectedIndexChanged of the ddfaculty from the ddDepartment will automatically reset the ddUniversity and also clicking the signup button equally rests every thing in the ddUniversity and ddDepartment.
this my html code
Experiment with UpdatePanels or use plain AJAX instead to load the DropDowns
Related
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.
I have a 3 dropdownlist control with a selectedindexchanged event that fires correctly. However, when you select an item from the list the index value that is returned to the selectedindexchanged event does not change; the list box pops back to the first item in the list. Any help would be appreciated. ~Dharmendra~
`public partial class Production : System.Web.UI.Page
{
EmployeeQuotientCL.Production _production = null;
DataSet dsNatureOfWork = new DataSet();
DataSet dsProjectRegion = new DataSet();
DataSet dsCountyDetails = new DataSet();
DataSet dsWorkType = new DataSet();
DataSet dsTask = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string userEcode=Convert.ToString(Session["UserID"]);
_production = new EmployeeQuotientCL.Production();
dsNatureOfWork = _production.GetNatureOfWork();
if (dsNatureOfWork.Tables[0].Rows.Count > 0)
{
BindDdlNatureOfWork(dsNatureOfWork);
}
else
{
}
}
}
public void BindDdlNatureOfWork(DataSet dsNatureOfWork)
{
ddlNatureofWork.DataSource = dsNatureOfWork.Tables[0];
ddlNatureofWork.DataTextField = "NatureOfWorkName";
ddlNatureofWork.DataValueField = "NatureOfWorkID";
ddlNatureofWork.DataBind();
ddlNatureofWork.Items.Insert(0, "--Select Nature of Work--");
}
public void FillRegionProject(int NatureOfWorkID)
{
if ((NatureOfWorkID != null) || (NatureOfWorkID != 0))
{
_production = new EmployeeQuotientCL.Production();
dsProjectRegion = _production.GetProjectRegion(NatureOfWorkID);
if (dsProjectRegion.Tables[0].Rows.Count > 0)
{
ddlRegionProjectName.DataSource = dsProjectRegion.Tables[0];
ddlRegionProjectName.DataTextField = "RegionProjectName";
ddlRegionProjectName.DataValueField = "RegionProjectID";
ddlRegionProjectName.DataBind();
ddlRegionProjectName.Items.Insert(0, "--Select Region/Project--");
}
else
{
}
}
}
protected void ddlRegionProjectName_SelectedIndexChanged(object sender, EventArgs e)
{
int RegionProjectID = Convert.ToInt32(ddlRegionProjectName.SelectedValue.ToString());
FillCounty(RegionProjectID);
ddlRegionProjectName.SelectedIndex = 0;
}
public void FillCounty(int regionprojectID)
{
if ((regionprojectID != null) || (regionprojectID != 0))
{
_production = new EmployeeQuotientCL.Production();
dsCountyDetails = _production.GetCounty(regionprojectID);
if (dsCountyDetails.Tables[0].Rows.Count > 0)
{
ddlCountyName.DataSource = dsCountyDetails.Tables[0];
ddlCountyName.DataTextField = "CountyName";
ddlCountyName.DataValueField = "CountyID";
ddlCountyName.DataBind();
ddlCountyName.Items.Insert(0, "--Select County--");
}
else
{
}
}
}
protected void ddlNatureofWork_SelectedIndexChanged(object sender, EventArgs e)
{
int NowID = Convert.ToInt32(ddlNatureofWork.SelectedValue.ToString());
FillRegionProject(NowID);
ddlRegionProjectName.SelectedIndex = 0;
}
}
}`
You are doing ddlRegionProjectName.SelectedIndex = 0; in every SelectedIndexChanged event.
You have no event for ddlCountyName control in the code shared by you.
I need to dynamically add CheckBoxList on the SelectedIndexChanged event of DropDownList. I have achieved this but I cannot retain its value on postback.
Here’s what I have done so far:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
loadTracks();//Needs to generated dynamically
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
loadDegrees();
}
loadTracks();
}
public void loadTracks()
{
try
{
ConfigurationDB objConfig = new ConfigurationDB();
DataSet ds = objConfig.GetTracksByDegreeID(
Convert.ToInt32(ddlDegree.SelectedValue.ToString()));
CheckBoxList CbxList = new CheckBoxList();
CbxList.ID = "Cbx";
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
CbxList.Items.Add(new ListItem(ds.Tables[0].Rows[i]["Track_Name"]
.ToString(), ds.Tables[0].Rows[i]["ID"].ToString()));
}
ph.Controls.Add(CbxList);
ViewState["tracks"] = true;
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
}
//For testing, I added a button and on its click I have added this code
protected void btnDetails_Click(object sender, EventArgs e)
{
CheckBoxList Cbx = (CheckBoxList)ph.FindControl("chk");
foreach (ListItem ex in Cbx.Items)
{
if (ex.Selected)
{
Response.Write(String.Format("You selected: <i>{0}</i> <br>", ex.Value));
}
}
}
Might be a typo:
CbxList.ID = "Cbx";
v.s.
CheckBoxList Cbx = (CheckBoxList)ph.FindControl("chk");
You can try it without changing the code and use pre PreRender
just run you loadTracks()
I have a web part for managing comments related to ongoing promotions. The web part is hosted in a Sandbox Solution because server access of all kinds is restricted (//sharepoint)
I have two main issues with my code.
1: Items submitted do not appear after postback, leaving user to think their comments was not saved,
2: PostBack data refires after page refresh, meaning if a user refreshes hoping to see their comments, it is re-submitted and saved.
What am I doing wrong here?
public string OfferID { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
OfferID = Context.Request.QueryString["ItemID"];
LoadOffers();
}
protected void LoadOffers()
{
if (!String.IsNullOrEmpty(OfferID))
{
PopulateOfferDetails(OfferID);
PopulateComments(OfferID);
PopulateBestPractices(OfferID);
}
else
{
OfferID = "123";
PopulateOfferDetails(OfferID);
PopulateComments(OfferID);
PopulateBestPractices(OfferID);
}
}
protected void PopulateComments(string offerID)
{
rcOiD.InnerText += " " + offerID;
List<Comment> Comments = new List<Comment>();
SPList TargetList = web.Lists.TryGetList("Offer Comments");
SPQuery query = new SPQuery();
query.RowLimit = 100;
query.Query = "<Where><Eq><FieldRef Name=\"OfferID\"/><Value Type=\"Text\">" + offerID + "</Value></Eq></Where>";
try
{
SPListItemCollection items = TargetList.GetItems(query);
if (items.Count > 0)
{
commentsCount.InnerText = items.Count.ToString();
SPUser user = web.CurrentUser;
string alias = user.Email.Substring(0, user.Email.IndexOf('#'));
string profilePicBase = "<div class=\"profilePic\" " + "style=\"background-image:url('http://who/Photos/XX.jpg');\"" + "> </div>";
foreach (SPListItem item in items)
{
Comment c = new Comment();
c.Author = ((string)item["Created By"]).CleanUserName();
c.Body = (string)item["Body"];
c.Date = String.Format("{0:MMM dd, yyyy}", (DateTime)item["Created"]);
c.ProfilePic = profilePicBase.Replace("XX", alias);
Comments.Add(c);
}
Comments.Reverse();
CommentRepeater.DataSource = Comments;
CommentRepeater.DataBind();
}
else
{
commentsCount.InnerText = "0";
}
}
catch (Exception ex)
{
}
}
protected void SubmitListItem(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
SPUser user = web.CurrentUser;
string alias = user.Email.Substring(0, user.Email.IndexOf('#'));
if (ListChoice.SelectedItem.Text == "comment")
{
SPList TargetList = web.Lists.TryGetList("Offer Comments");
SPListItem item = TargetList.Items.Add();
item["Title"] = TitleBox.Text;
item["Body"] = BodyBox.Text;
item["OfferID"] = OfferID;
item["Alias"] = alias;
item.SystemUpdate();
TargetList.Update();
}
else
{
SPList TargetList = web.Lists.TryGetList("Offer Best Practices");
SPListItem item = TargetList.Items.Add();
item["Title"] = TitleBox.Text;
item["Body"] = BodyBox.Text;
item["OfferID"] = OfferID;
item.SystemUpdate();
TargetList.Update();
}
}
}
EDIT: I can confirm this isn't a databind() issue. The item.count being pulled on postback is being rendered properly, but is still 1 item short.
I assume SubmitListItem is an event handler of an control on the page.
If that is so then as in your previous question, Page_Load is is fired before any control's event handler.
Therefore on postback your repeater is getting bound before the item addition occurs so on that load you do not get to see the new item.
To prevent this rebind the repeater after item addition.
I think you should do this only if not is page postback:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
OfferID = Context.Request.QueryString["ItemID"];
LoadOffers();
}
}
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.