PageIndexChanged is not working - c#

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.

Related

Unable to check all check boxes in a GridView

I am using grid view check box to select all the values in the grid view when i click the check box, but the problem i am facing is it is selecting the only the first page value how ever i have coded to bring all the values in but in design it is not working out
this is the image
i want all the check box to checked in design when i press the all check button.
protected void gvBatch_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType != DataControlRowType.Header && e.Row.RowType != DataControlRowType.Footer && e.Row.RowType != DataControlRowType.Pager)
{
DropDownList ddlcountry1 = (DropDownList)e.Row.FindControl("ddlcountry");
populateLocationValues(ddlcountry1);
{
ArrayList checkboxvalues = (ArrayList)Session["BP_PrdId"];
//string Bp_Id = "";
if (checkboxvalues != null && checkboxvalues.Count > 0)
{
string strBp_Id = ((HiddenField)e.Row.FindControl("hf_ProductLblId")).Value.ToString();
if (checkboxvalues.Contains(strBp_Id))
{
CheckBox myCheckBox = (CheckBox)e.Row.FindControl("chkPLPSltItem");
myCheckBox.Checked = true;
}
}
}
DataSet dsaccess = MenuRestriction();
DataRow dr = null;
string sView = "";
string sEdit = "";
string sInsert = "";
string sDeactive = "";
if (dsaccess.Tables.Count > 0)
{
if (dsaccess.Tables[0].Rows.Count > 0)
{
dr = dsaccess.Tables[0].Rows[0];
sView = dr["MnuRgts_View"].ToString();
sEdit = dr["MnuRgts_Edit"].ToString();
sInsert = dr["MnuRgts_Insert"].ToString();
sDeactive = dr["MnuRgts_DeActivate"].ToString();
if (sInsert == "Y" && sDeactive == "Y")
{
BtnDelete.Visible = true;
imgNew.Visible = true;
}
else
{
BtnDelete.Visible = false;
imgNew.Visible = false;
if (sInsert == "Y")
{
imgNew.Visible = true;
}
if (sDeactive == "Y")
{
BtnDelete.Visible = true;
}
}
}
}
}
}
catch (Exception ex)
{
log.Error("gvBatch_RowDataBound", ex);
}
}
protected void gvBatch_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
RememberOldValues();
gvBatch.PageIndex = e.NewPageIndex;
//RetrieveValues();
BindGrid();
LoadLocation();
//RePopulateValues();
}
private void RememberOldValues()
{
ArrayList checkboxvalues = new ArrayList();
string strBp_Id = "";
foreach (GridViewRow row in gvBatch.Rows)
{
//index = (int)gvBatch.DataKeys[row.RowIndex].Value;
strBp_Id = ((HiddenField)row.FindControl("hf_ProductLblId")).Value.ToString();
bool result = ((CheckBox)row.FindControl("chkPLPSltItem")).Checked;
// Check in the Session
if (Session["BP_PrdId"] != null)
checkboxvalues = (ArrayList)Session["BP_PrdId"];
if (result)
{
if (!checkboxvalues.Contains(strBp_Id))
checkboxvalues.Add(strBp_Id);
}
else
{
if (checkboxvalues.Contains(strBp_Id))
checkboxvalues.Remove(strBp_Id);
}
}
if (checkboxvalues != null && checkboxvalues.Count > 0)
Session["BP_PrdId"] = checkboxvalues;
}
protected void gvBatch_PreRender(object sender, EventArgs e)
{
try
{
if (gvBatch.TopPagerRow != null)
{
((Label)gvBatch.TopPagerRow.FindControl("lbCurrentPage")).Text = (gvBatch.PageIndex + 1).ToString();
((Label)gvBatch.TopPagerRow.FindControl("lbTotalPages")).Text = gvBatch.PageCount.ToString();
((LinkButton)gvBatch.TopPagerRow.FindControl("lbtnFirst")).Visible = gvBatch.PageIndex != 0;
((LinkButton)gvBatch.TopPagerRow.FindControl("lbtnPrev")).Visible = gvBatch.PageIndex != 0;
((LinkButton)gvBatch.TopPagerRow.FindControl("lbtnNext")).Visible = gvBatch.PageCount != (gvBatch.PageIndex + 1);
((LinkButton)gvBatch.TopPagerRow.FindControl("lbtnLast")).Visible = gvBatch.PageCount != (gvBatch.PageIndex + 1);
DropDownList ddlist = (DropDownList)gvBatch.TopPagerRow.FindControl("ddlPageItems");
ddlist.SelectedIndex = ddlist.Items.IndexOf(ddlist.Items.FindByValue(ViewState["DropDownPageItems"].ToString()));
gvBatch.AllowPaging = true;
gvBatch.TopPagerRow.Visible = true;
}
}
catch (Exception ex)
{
}
}
protected void gvBatch_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "EDIT")
{
GridViewRow row = (GridViewRow)((Control)e.CommandSource).Parent.Parent;
string strAgentName = ((HiddenField)row.FindControl("hf_loginName")).Value.ToString();
if (strAgentName != "")
{
Response.Redirect("CustomerDetails.aspx?Name=" + strAgentName, false);
}
}
}
catch (Exception ex)
{
log.Error("gvAgentRowcommand_AgentSummary", ex);
}
}
You can keep a boolean field in your code and set its value to true whenever the select all is clicked. When loading new pages, you can check that field to automatically display all checked. The same can be done when exporting the grid also.
you can modify and use the following Method
private void selectAllChecksInDAtaGrid()
{
foreach (DataGridViewRow item in myDataGrid.Rows)
{
if (Convert.ToBoolean(item.Cells["Column_Name"].Value) == false)
{
item.Cells["Column_Name"].Value = true;
}
}
}
the 'Column_name' is the name of the checkbox column. if you haven'nt named it yet you can also use the index number .
in your case its 0
private void selectAllChecksInDAtaGrid()
{
foreach (DataGridViewRow item in myDataGrid.Rows)
{
if (Convert.ToBoolean(item.Cells[0].Value) == false)
{
item.Cells[0].Value = true;
}
}
}
You should update (ArrayList)Session["BP_PrdId"] to include all the "Id"s of datasource of gridview. then bind data again.

Prepopulated Form causing issues for DbContext.SaveChanges()

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.

Datagridview c# with SQL for Professional Developer

First of all I will give short description about my App:
C# application uses sql server to share "Tasks" between team
All user see the tasks
The event happens when user check the checkbox
I use a timer to refresh the grid every 4 seconds
Timer code:
private static int second = 0;
private void timer1_Tick(object sender, EventArgs e)
{
try
{
second++;
List<Tasks> list=taskController.taskController.GetList();
_FillGridFromList(list);
_RefreshGrid();
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/*reFill the grid*/
private void _RefreshGrid()
{
try
{
List<Tasks> list = taskController.taskController.GetList();
_FillGridFromList(list);
}
catch (Exception ex)
{
MessageBox.Show(this, "Unable to Retrive Data from Server", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/*This function will fill userGridView from Arraylist that get from SQL */
private void _FillGridFromList(List<Tasks> list)
{
dataGridView1.ClearSelection();
try
{
DataTable table1 = new DataTable("sheet");
System.Data.DataSet tmpSet = new System.Data.DataSet();
DataRow row = table1.NewRow();
table1.Columns.Add("ID");
table1.Columns.Add("Title");
table1.Columns.Add("Description");
table1.Columns.Add("Preiority");
table1.Columns.Add("Status");
table1.Columns.Add("Done By");
table1.Columns.Add("Start Date");
int j = 0;
for (int i = 0; i < list.Count; i++)
{
Tasks tmp = (Tasks)list[i];
row[j++] = tmp.ID;
row[j++] = tmp.Name;
row[j++] = tmp.Description;
row[j++] = tmp.Preiority;
row[j++] = tmp.Status;
row[j++] = tmp.Done_By;
row[j++] = tmp.Start_Date;
j = 0;
table1.Rows.Add(row);
row = table1.NewRow();
}
tmpSet.Tables.Add(table1);
dataGridView1.DataSource = tmpSet.Tables[0];
// dataGridView1.ReadOnly = true;
dataGridView1.Columns[1].ReadOnly = true;
dataGridView1.Columns[2].ReadOnly = true;
dataGridView1.Columns[3].ReadOnly = true;
dataGridView1.Columns[4].ReadOnly = true;
dataGridView1.Columns[5].ReadOnly = true;
dataGridView1.Columns[6].ReadOnly = true;
dataGridView1.Columns[7].ReadOnly = true;
for (int i = 0; i < list.Count; i++)
{
if (list[i].Done_By.Trim().Length > 0)
{
dataGridView1.Rows[i].Cells[0].Value = true;
if (list[i].Done_By != utility.Util.User.Display_Name)
{
dataGridView1.Rows[i].Cells[0].ReadOnly = true;
}
else
{
dataGridView1.Rows[i].Cells[0].ReadOnly = false;
}
}
else
{
dataGridView1.Rows[i].Cells[0].Value = false;
}
}
}
catch (Exception e)
{
MessageBox.Show(this, e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void dataGridView1_CellValueChanged_1(object sender, DataGridViewCellEventArgs e)
{
try
{
if(second > 5)
{
foreach (DataGridViewRow dr in dataGridView1.Rows)
{
DataGridViewCheckBoxCell drx = (DataGridViewCheckBoxCell)dr.Cells[0];
if(sender == drx)
if (drx.Selected != null) //Cells[0] Because in cell 0th cell we have added checkbox
{
if (drx.Selected==true && dr.Cells[6].Value.ToString() == utility.Util.User.Display_Name)
{
Tasks tsk = taskController.taskController.Read(dr.Cells[1].Value + "");
{
tsk.Done_By = "";
tsk.Status = "";
taskController.taskController.Update(tsk);
}
}
else
{
if (drx.Selected !=true)
{
Tasks tsk = taskController.taskController.Read(dr.Cells[1].Value + "");
tsk.Done_By = utility.Util.User.Display_Name;
tsk.Status = "Closed";
taskController.taskController.Update(tsk);
}
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
The main problem is that when I fill the form again the listener is called because I rebuild the gridview.
http://i.stack.imgur.com/l0Rdv.png
I solve the problem by using the below code :
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
//MessageBox.Show(e.RowIndex+" "+e.ColumnIndex);
// Int32 selectedRowCount = dataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected);
// Int32 selectedColumnCount = dataGridView1.Columns.GetColumnCount(DataGridViewElementStates.Selected);
if ( e.ColumnIndex == 0 && e.RowIndex >= 0 )
{
string x=dataGridView1.Rows[e.RowIndex-1].Cells[6].Value.ToString();
if ((bool)dataGridView1.Rows[e.RowIndex-1].Cells[0].Value == false && x!=null )
{
if(x==Util.User.Display_Name)
{
Tasks tsk = taskController.taskController.Read(dataGridView1.Rows[e.RowIndex-1].Cells[1].Value + "");
tsk.Done_By = "";
tsk.Status = "";
taskController.taskController.Update(tsk);
dataGridView1.Rows[0].Cells[1].Value = true;
}
}
else
{
if ((bool)dataGridView1.Rows[e.RowIndex-1].Cells[0].Value == true)
{
Tasks tsk = taskController.taskController.Read(dataGridView1.Rows[e.RowIndex-1].Cells[1].Value + "");
tsk.Done_By = utility.Util.User.Display_Name;
tsk.Status = "Closed";
taskController.taskController.Update(tsk);
}
}
}
}
I only change the type of listener from private void dataGridView1_CellValueChanged_1
to
private void dataGridView1_CellContentClick

Removing particular items from menu and replacing the new menu through content page in asp.net?

I have a menu and label in my master page which i want to update depending on the type of user logged in.
Firstly am removing few MenuItems from the menu that is working fine but its not showing up in the master page. Instead the old menu is only seen with all the menu items for limited user also. When i debug the label text shows what i have set but when page loads its not updating too.
Am using the following code.
Label lbWelcomeMessage = new Label();
protected void Page_Load(object sender, EventArgs e)
{
Master.FindControl("CAMenu").Visible = false;
}
protected void btnLogin_Click(object sender, EventArgs e)
{
string userName = txtUsername.Text;
string password = txtPassword.Text;
Common common = new Common();
DataTable tab = new DataTable();
tab= common.GetUserDetails(userName);
string firstName = string.Empty;
string userPassword = string.Empty;
string RoleID=string.Empty;
if (tab.Rows.Count == 1)
{
firstName = tab.Rows[0][2].ToString();
userPassword = tab.Rows[0][4].ToString();
RoleID = tab.Rows[0][5].ToString();
}
if (userPassword == password)
{
if (RoleID != "1")
{
Menu CAMenu = new Menu();
CAMenu = (Menu)Master.FindControl("CAMenu");
int count = CAMenu.Items.Count;
for (int i = 3; i > 0; i--)
{
string text = CAMenu.Items[i - 1].Text;
CAMenu.Items.RemoveAt(i - 1);
}
lbWelcomeMessage = (Label)Master.FindControl("lbLoginMessage");
lbWelcomeMessage.Text = "Welcome"+" "+ firstName;
((SiteMaster)Page.Master).MyText = lbWelcomeMessage.Text;
Response.Redirect("AdHocSMS.aspx");
}
else
{
lbWelcomeMessage = (Label)Master.FindControl("lbLoginMessage");
lbWelcomeMessage.Text = lbWelcomeMessage.Text+" "+firstName ;
Response.Redirect("NewTemplate.aspx");
}
}
}
I assume you have written this code in your login.aspx. When login button is clicked then it takes you to another page and all the life cycle of page is run again. and master page contents are reset.
The solution to this problem could be. Move this logic to your master page code like
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (Session.Count == 0 || Session["Username"] == null)
Response.Redirect("~/Login.aspx", true);
CheckRole();
}
public void CheckRole()
{
if (System.Web.HttpContext.Current.Session.Count > 0)
{
tab= common.GetUserDetails(Session["Username"]);
if (tab.Rows.Count == 1)
{
firstName = tab.Rows[0][2].ToString();
userPassword = tab.Rows[0][4].ToString();
RoleID = tab.Rows[0][5].ToString();
}
if (RoleID != "1")
{
Menu CAMenu = new Menu();
int count = CAMenu.Items.Count;
for (int i = 3; i > 0; i--)
{
string text = CAMenu.Items[i - 1].Text;
CAMenu.Items.RemoveAt(i - 1);
}
//your label logic
lbWelcomeMessage.Text = "Welcome"+" "+ firstName;
((SiteMaster)Page.Master).MyText = lbWelcomeMessage.Text;
Response.Redirect("AdHocSMS.aspx");
}
else
{
//Logic
Response.Redirect("NewTemplate.aspx");
}
}
else
{
Session.Abandon();
Response.Redirect("~/Login.aspx", true);
}
}
You have to put a UserId or Username in Session this is the one disadvantage but for every page you dont have to worry about anything.
for life cycle read this article http://msdn.microsoft.com/en-us/library/ms178472.aspx
let me know if it solves or not.
What i did is something like this
In Site.Mater:-
public void CheckRole()
{
try
{
if (System.Web.HttpContext.Current.Session.Count > 0)
{
string firstName = string.Empty;
// string userPassword = string.Empty;
string RoleID = string.Empty;
Common common = new Common();
DataTable tab = new DataTable();
string userName = (string)Session["UserName"];
User user = new User(userName);
tab = user.GetUserDetails(userName);
if (tab.Rows.Count == 1)
{
firstName = tab.Rows[0][1].ToString();
RoleID = tab.Rows[0][3].ToString();
}
if (RoleID != "1")
{
int count = CAMenu.Items.Count;
if (count == 5)
{
for (int menuCount = 3; menuCount > 0; menuCount--)
{
string text = CAMenu.Items[menuCount - 1].Text;
CAMenu.Items.RemoveAt(menuCount - 1);
}
}
lbLoginMessage.Text = "Welcome," + " " + firstName;
loginStatus.Visible = true;
}
else
{
lbLoginMessage.Text = "Welcome," + " " + firstName;
loginStatus.Visible = true;
}
}
else
{
Session.Abandon();
Response.Redirect("~/Login.aspx", true);
}
}
catch (Exception ex)
{
new Logger().Log("ShortCom.SiteMaster.CheckRole()", ex.Message);
Response.Redirect("~/Error.aspx");
}
}
In Login.Apsx:-
protected void Page_Load(object sender, EventArgs e)
{
try
{
Master.FindControl("CAMenu").Visible = false;
Master.FindControl("loginStatus").Visible = false;
}
catch (Exception ex)
{
new Logger().Log("ShortCom.Login.btnLogin_Click(object sender, EventArgs e)", ex.Message);
Response.Redirect("~/Error.aspx");
}
}
protected void LoadMessageBox(string MessageID)
{
try
{
messages = new GUIMessages();
popupExtend = new ModalPopupExtender();
lbMessage = (Label)Master.FindControl("label5");
lbMessage.Text = messages.GetGUIMessage(GUIModule.Login, MessageID);
popupExtend = (ModalPopupExtender)Master.FindControl("popupExtender");
popupExtend.Show();
}
catch (Exception ex)
{
new Logger().Log("ShortCom.Login.LoadMessageBox(string MessageID)", ex.Message);
Response.Redirect("~/Error.aspx");
}
}
protected void btnLogin_Click(object sender, EventArgs e)
{
try
{
string userName = txtUsername.Text;
string password = txtPassword.Text;
if (userName == string.Empty && password == string.Empty)
{
LoadMessageBox("5");
txtUsername.Focus();
return;
}
if (userName == string.Empty)
{
LoadMessageBox("1");
txtUsername.Focus();
return;
}
else if (password == string.Empty)
{
LoadMessageBox("3");
txtPassword.Focus();
return;
}
User user = new User(userName);
DataTable tab = new DataTable();
tab = user.GetUserDetails(userName);
string firstName = string.Empty;
string userPassword = string.Empty;
string RoleID = string.Empty;
string userID = string.Empty;
Session["UserName"] = userName;
if (tab.Rows.Count == 0)
{
LoadMessageBox("6");
txtPassword.Text = string.Empty;
txtUsername.Text = string.Empty;
txtUsername.Focus();
return;
}
if (tab.Rows.Count == 1)
{
userID = tab.Rows[0][0].ToString();
firstName = tab.Rows[0][1].ToString();
userPassword = tab.Rows[0][2].ToString();
RoleID = tab.Rows[0][3].ToString();
Session["UserID"] = userID;
}
//if (firstName != userName)
//{
// LoadMessageBox("2");
// txtUsername.Focus();
// return;
//}
//else
{
if (userPassword == password)
{
Response.Redirect("~/Default.aspx");
}
else
{
LoadMessageBox("4");
txtPassword.Focus();
return;
}
}
}
catch (Exception ex)
{
new Logger().Log("ShortCom.Login.btnLogin_Click(object sender, EventArgs e)", ex.Message);
Response.Redirect("~/Error.aspx");
}
}

All dropdownlist resets at single selectedIndexchange

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

Categories