Master/Details ASP.NET C# DataGrid? - c#

I want to display data Master/Details stype with DataGrid not GridView or anything else. At the present I must put a dropdownlist to do this manually. So how can do it automatically whenever we click one master item in the Master DataGrid then it link to Details DataGird , like this:
private void BindGridMaster()
{
grdReceivedNote.DataSource = ReceivedNoteService.ReceivedNote_GetByAll();
grdReceivedNote.DataBind();
if (grdReceivedNote.PageCount <= 1)
{
grdReceivedNote.PagerStyle.Visible = false;
}
else
{
grdReceivedNote.PagerStyle.Visible = true;
}
}
private void BindGridDetails()
{
grdReceivedNoteDetails.DataSource = RevNoteDetailsService.RevNoteDetails_GetByAll();
grdReceivedNoteDetails.DataBind();
if (grdReceivedNoteDetails.PageCount <= 1)
{
grdReceivedNoteDetails.PagerStyle.Visible = false;
}
else
{
grdReceivedNoteDetails.PagerStyle.Visible = true;
}
}
protected void grdReceivedNote_ItemDataBound(object sender, DataGridItemEventArgs e)
{
ListItemType itemType = e.Item.ItemType;
if ((itemType != ListItemType.Footer) && (itemType != ListItemType.Separator))
{
if (itemType == ListItemType.Header)
{
object checkBox = e.Item.FindControl("chkSelectAll");
if ((checkBox != null))
{
((CheckBox)checkBox).Attributes.Add("onClick", "Javascript:chkSelectAll_OnClick(this)");
}
}
else
{
string tableRowId = grdReceivedNote.ClientID + "_row" + e.Item.ItemIndex.ToString();
e.Item.Attributes.Add("id", tableRowId);
object checkBox = e.Item.FindControl("chkSelect");
if ((checkBox != null))
{
e.Item.Attributes.Add("onMouseMove", "Javascript:chkSelect_OnMouseMove(this)");
e.Item.Attributes.Add("onMouseOut", "Javascript:chkSelect_OnMouseOut(this," + e.Item.ItemIndex.ToString() + ")");
((CheckBox)checkBox).Attributes.Add("onClick", "Javascript:chkSelect_OnClick(this," + e.Item.ItemIndex.ToString() + ")");
}
}
}
}
protected void grdReceivedNoteDetails_ItemDataBound(object sender, DataGridItemEventArgs e)
{
ListItemType itemType = e.Item.ItemType;
if ((itemType != ListItemType.Footer) && (itemType != ListItemType.Separator))
{
if (itemType == ListItemType.Header)
{
object checkBox = e.Item.FindControl("chkSelectAll");
if ((checkBox != null))
{
((CheckBox)checkBox).Attributes.Add("onClick", "Javascript:chkSelectAll_OnClick(this)");
}
}
else
{
string tableRowId = grdReceivedNote.ClientID + "_row" + e.Item.ItemIndex.ToString();
e.Item.Attributes.Add("id", tableRowId);
object checkBox = e.Item.FindControl("chkSelect");
if ((checkBox != null))
{
e.Item.Attributes.Add("onMouseMove", "Javascript:chkSelect_OnMouseMove(this)");
e.Item.Attributes.Add("onMouseOut", "Javascript:chkSelect_OnMouseOut(this," + e.Item.ItemIndex.ToString() + ")");
((CheckBox)checkBox).Attributes.Add("onClick", "Javascript:chkSelect_OnClick(this," + e.Item.ItemIndex.ToString() + ")");
}
}
}
}
protected void grdReceivedNote_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
{
grdReceivedNote.CurrentPageIndex = e.NewPageIndex;
BindGridMaster();
}
protected void grdReceivedNoteDetails_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
{
grdReceivedNoteDetails.CurrentPageIndex = e.NewPageIndex;
BindGridMaster();
}
protected void grdReceivedNote_ItemCommand(object source, DataGridCommandEventArgs e)
{
string strCA = e.CommandArgument.ToString();
switch (e.CommandName)
{
case "Edit":
Insert = false;
Id = strCA;
ViewCustomers();
ViewRevType();
//ViewRevNote();
//ViewItems();
List<Data.ReceivedNote> listE = ReceivedNoteService.ReceivedNote_GetById(Id);
txtRevNote_No.Text = listE[0].RevNote_No;
txtRevDate.Text = listE[0].RevDate;
txtNotes.Text = listE[0].Notes;
drlCustIdAdd.SelectedValue = listE[0].CustID;
drlRevTypeIdAdd.SelectedValue = listE[0].RevTypeID;
pnViewMaster.Visible = false;
pnUpdateMaster.Visible = true;
break;
case "Delete":
ReceivedNoteService.ReceivedNote_Delete(strCA);
BindGridMaster();
break;
}
}
protected void grdReceivedNoteDetails_ItemCommand(object source, DataGridCommandEventArgs e)
{
string strCA = e.CommandArgument.ToString();
switch (e.CommandName)
{
case "Edit":
Insert = false;
Id = strCA;
//ViewCustomers();
//ViewRevType();
ViewRevNote();
ViewItems();
List<Data.RevNoteDetails> listE = RevNoteDetailsService.RevNoteDetails_GetById(Id);
txtQuantity.Text = listE[0].Quantity;
drlRevNoteIdAdd.SelectedValue = listE[0].RevNoteID;
drlItemIdAdd.SelectedValue = listE[0].ItemID;
pnlViewDetails.Visible = false;
pnlUpdateDetails.Visible = true;
break;
case "Delete":
RevNoteDetailsService.RevNoteDetails_Delete(strCA);
BindGridDetails();
break;
}
}

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.

Unable to move files into devexpress file treelist

I have created a file treelist in my WinForms application. The files and folders are displayed in a correct way. But when I try to drag a file from my pc (for ex. from my desktop) to the application the draggednode and the target node are null. Moving folders within my application works fine. How to change my application that I can drag files into the folders in the application?
Code:
class FileListHelper
{
string rootPath;
TreeList Tree;
private DevExpress.XtraTreeList.Columns.TreeListColumn treeListColumn1;
private DevExpress.XtraTreeList.Columns.TreeListColumn treeListColumn2;
private DevExpress.XtraTreeList.Columns.TreeListColumn treeListColumn3;
private DevExpress.XtraTreeList.Columns.TreeListColumn treeListColumn4;
private DevExpress.XtraTreeList.Columns.TreeListColumn treeListColumn5;
TreeListMenu folderMenu;
public FileListHelper(TreeList tree)
{
Tree = tree;
InitColumns();
Tree.BeforeExpand += new DevExpress.XtraTreeList.BeforeExpandEventHandler(this.treeList1_BeforeExpand);
Tree.AfterExpand += new DevExpress.XtraTreeList.NodeEventHandler(this.treeList1_AfterExpand);
Tree.AfterCollapse += new DevExpress.XtraTreeList.NodeEventHandler(this.treeList1_AfterCollapse);
Tree.CalcNodeDragImageIndex += new DevExpress.XtraTreeList.CalcNodeDragImageIndexEventHandler(this.treeList1_CalcNodeDragImageIndex);
Tree.DragDrop += new System.Windows.Forms.DragEventHandler(this.treeList1_DragDrop);
Tree.DoubleClick += new System.EventHandler(this.treeList1_DoubleClick);
Tree.PopupMenuShowing += new PopupMenuShowingEventHandler(Tree_PopupMenuShowing);
Tree.DragEnter += new DragEventHandler(this.treeList1_DragEnter); //added shows icons
tree.CellValueChanged += new CellValueChangedEventHandler(tree_CellValueChanged);
InitData();
folderMenu = new TreeListMenu(Tree);
folderMenu.Items.Add(new DXMenuItem("Create New Folder",MenuAddClick));
folderMenu.Items.Add(new DXMenuItem("Delete", MenuDeleteClick));
}
#region DragEnter
void treeList1_DragEnter(object sender,DragEventArgs e)
{
if (e.Data.GetDataPresent("FileGroupDescriptor"))
{
e.Effect = DragDropEffects.All;
}
else if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effect = DragDropEffects.Copy;
//ensure FileGroupDescriptor is present before allowing drop
}
else if (e.Data.GetDataPresent("RenPrivateMessages"))
{
e.Effect = DragDropEffects.All;
}
else
{
e.Effect = DragDropEffects.Move;
}
}
#endregion DragEnter
#region Rename
void tree_CellValueChanged(object sender, CellValueChangedEventArgs e)
{
if (e.Column.Caption =="Name")
{
if (e.Node["Type"] == "Folder")
{
DirectoryInfo di = e.Node["Info"] as DirectoryInfo;
di.MoveTo(di.Parent.FullName+"//"+e.Value);
}
else
{
FileInfo fi = e.Node["Info"] as FileInfo;
fi.MoveTo(fi.Directory.FullName + "//" + e.Value);
}
}
}
#endregion
#region Popup Menu
void Menu_Click(object sender, EventArgs e)
{
throw new Exception("The method or operation is not implemented.");
}
void Tree_PopupMenuShowing(object sender, PopupMenuShowingEventArgs e)
{
TreeListNode node = Tree.CalcHitInfo(e.Point).Node;
if (node != null)
{
e.Menu = folderMenu;
e.Menu.Tag = node;
//e.Menu.Items.Add(new DXMenuItem("Create New Folder"));
}
}
void MenuAddClick(object sender, EventArgs e)
{
DirectoryInfo di;
int ParentId = -1;
TreeListNode curentNode = folderMenu.Tag as TreeListNode;
TreeListNode folderParentNode;
if (curentNode["Type"] == "Folder")
folderParentNode = curentNode;
else
folderParentNode = curentNode.ParentNode;
if (folderParentNode == null)
{
di = new DirectoryInfo(rootPath);
}
else
{
ParentId = folderParentNode.Id;
di=folderParentNode["Info"] as DirectoryInfo;
}
DirectoryInfo newDirectory = Directory.CreateDirectory(di.FullName + "\\New Folder");
if (newDirectory != null)
{
Tree.FocusedNode = Tree.AppendNode(new object[] { newDirectory.FullName, newDirectory.Name, "Folder", null, newDirectory }, ParentId);
}
Tree.FocusedColumn = Tree.Columns["Name"];
Tree.ShowEditor();
}
void MenuDeleteClick(object sender, EventArgs e)
{
TreeListNode curentNode = folderMenu.Tag as TreeListNode;
(curentNode["Info"] as FileSystemInfo).Delete();
Tree.DeleteNode(curentNode);
}
#endregion
#region Initializing TreeList
void InitColumns()
{
this.treeListColumn1 = new DevExpress.XtraTreeList.Columns.TreeListColumn();
this.treeListColumn2 = new DevExpress.XtraTreeList.Columns.TreeListColumn();
this.treeListColumn3 = new DevExpress.XtraTreeList.Columns.TreeListColumn();
this.treeListColumn4 = new DevExpress.XtraTreeList.Columns.TreeListColumn();
this.treeListColumn5 = new DevExpress.XtraTreeList.Columns.TreeListColumn();
this.treeListColumn1.Caption = "FullName";
this.treeListColumn1.FieldName = "FullName";
this.treeListColumn2.Caption = "Name";
this.treeListColumn2.FieldName = "Name";
this.treeListColumn2.VisibleIndex = 0;
this.treeListColumn2.Visible = true;
this.treeListColumn2.SortOrder = SortOrder.Ascending;
this.treeListColumn2.SortIndex = 1;
this.treeListColumn3.Caption = "Type";
this.treeListColumn3.FieldName = "Type";
this.treeListColumn3.VisibleIndex = 1;
this.treeListColumn3.Visible = true;
this.treeListColumn3.SortOrder = SortOrder.Descending;
this.treeListColumn3.SortIndex = 0;
this.treeListColumn3.OptionsColumn.AllowEdit = false;
this.treeListColumn4.AppearanceCell.Options.UseTextOptions = true;
this.treeListColumn4.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far;
this.treeListColumn4.Caption = "Size(Bytes)";
this.treeListColumn4.FieldName = "Size";
this.treeListColumn4.VisibleIndex = 2;
this.treeListColumn4.Visible = true;
this.treeListColumn4.OptionsColumn.AllowEdit = false;
this.treeListColumn5.Caption = "treeListColumn5";
this.treeListColumn5.FieldName = "Info";
this.treeListColumn5.Name = "treeListColumn5";
Tree.Columns.AddRange(new DevExpress.XtraTreeList.Columns.TreeListColumn[] {
this.treeListColumn1,
this.treeListColumn2,
this.treeListColumn3,
this.treeListColumn4,
this.treeListColumn5});
}
private void InitData()
{
//int currentIncidentId=2;
//rootPath = Directory.GetDirectoryRoot(Directory.GetCurrentDirectory());
rootPath = "C:\\Data\\98-ProgrammData\\Maintenance\\Dossier\\"/*+currentIncidentId*/;
InitFolders(rootPath, null);
}
private void InitFolders(string path, TreeListNode pNode)
{
Tree.BeginUnboundLoad();
TreeListNode node;
DirectoryInfo di;
try
{
string[] root = Directory.GetDirectories(path);
foreach (string s in root)
{
try
{
di = new DirectoryInfo(s);
node = Tree.AppendNode(new object[] { s, di.Name, "Folder", null, di }, pNode);
node.StateImageIndex = 0;
node.HasChildren = HasFiles(s);
if (node.HasChildren)
node.Tag = true;
}
catch { }
}
}
catch { }
InitFiles(path, pNode);
Tree.EndUnboundLoad();
}
private void InitFiles(string path, TreeListNode pNode)
{
TreeListNode node;
FileInfo fi;
try
{
string[] root = Directory.GetFiles(path);
foreach (string s in root)
{
fi = new FileInfo(s);
node = Tree.AppendNode(new object[] { s, fi.Name, "File", fi.Length, fi }, pNode);
node.StateImageIndex = 1;
node.HasChildren = false;
}
}
catch { }
}
private void treeList1_FilterNode(object sender, DevExpress.XtraTreeList.FilterNodeEventArgs e)
{
TreeList tree = sender as TreeList;
if (string.IsNullOrEmpty(tree.FindFilterText)) return;
e.Node.Visible = IsNodeVisible(e.Node);
e.Handled = true;
}
private bool IsNodeVisible(TreeListNode node)
{
if (node.ParentNode == null)
{
foreach (TreeListColumn column in node.TreeList.VisibleColumns)
{
object val = node[column.FieldName];
if (val != null && val.ToString().ToUpper().Equals(node.TreeList.FindFilterText.ToUpper()))
return true;
}
return false;
}
return IsNodeVisible(node.ParentNode);
}
private bool HasFiles(string path)
{
string[] root = Directory.GetFiles(path);
if (root.Length > 0) return true;
root = Directory.GetDirectories(path);
if (root.Length > 0) return true;
return false;
}
private void treeList1_BeforeExpand(object sender, DevExpress.XtraTreeList.BeforeExpandEventArgs e)
{
if (e.Node.Tag != null)
{
Cursor currentCursor = Cursor.Current;
Cursor.Current = Cursors.WaitCursor;
InitFolders(e.Node.GetDisplayText("FullName"), e.Node);
e.Node.Tag = null;
Cursor.Current = currentCursor;
}
}
private void treeList1_AfterExpand(object sender, DevExpress.XtraTreeList.NodeEventArgs e)
{
if (e.Node.StateImageIndex != 1) e.Node.StateImageIndex = 2;
}
private void treeList1_AfterCollapse(object sender, DevExpress.XtraTreeList.NodeEventArgs e)
{
if (e.Node.StateImageIndex != 1) e.Node.StateImageIndex = 0;
}
#endregion
#region Dragging
private void treeList1_CalcNodeDragImageIndex(object sender, DevExpress.XtraTreeList.CalcNodeDragImageIndexEventArgs e)
{
if (e.Node[treeListColumn3].ToString() == "Folder")
{
e.ImageIndex = 0;
}
if (e.Node[treeListColumn3].ToString() == "File")
{
if (e.Node.ParentNode == Tree.FocusedNode.ParentNode)
{
e.ImageIndex = -1;
return;
}
if (e.ImageIndex == 0)
if (e.Node.Id > Tree.FocusedNode.Id)
e.ImageIndex = 2;
else
e.ImageIndex = 1;
}
}
private void treeList1_DragDrop(object sender, DragEventArgs e)
{
TreeListNode draggedNode = e.Data.GetData(typeof(TreeListNode)) as TreeListNode;
TreeListNode tagretNode = Tree.ViewInfo.GetHitTest(Tree.PointToClient(new Point(e.X, e.Y))).Node;
if (tagretNode == null || draggedNode == null) return;
if (tagretNode[treeListColumn3].ToString() == "File")
{
if (tagretNode.ParentNode == draggedNode.ParentNode)
return;
MoveInFolder(draggedNode, tagretNode.ParentNode);
}
else
{
MoveInFolder(draggedNode, tagretNode);
}
e.Effect = DragDropEffects.None;
}
void MoveInFolder(TreeListNode sourceNode, TreeListNode destNode)
{
Tree.MoveNode(sourceNode, destNode);
if (sourceNode == null) return;
FileSystemInfo sourceInfo = sourceNode[treeListColumn5] as FileSystemInfo;
string sourcePath = sourceInfo.FullName;
string destPath;
if (destNode == null)
destPath = rootPath + sourceInfo.Name;
else
{
DirectoryInfo destInfo = destNode[treeListColumn5] as DirectoryInfo;
destPath = destInfo.FullName + "\\" + sourceInfo.Name;
}
if (sourceInfo is DirectoryInfo)
Directory.Move(sourcePath, destPath);
else
File.Move(sourcePath, destPath);
sourceNode[treeListColumn5] = new DirectoryInfo(destPath);
}
#endregion
#region Executing
private void treeList1_DoubleClick(object sender, EventArgs e)
{
if ((sender as TreeList).FocusedNode[treeListColumn3].ToString() == "File")
Process.Start(((sender as TreeList).FocusedNode[treeListColumn5] as FileSystemInfo).FullName, null);
}
#endregion
}
These two lines are null:
TreeListNode draggedNode = e.Data.GetData(typeof(TreeListNode)) as TreeListNode;
TreeListNode tagretNode = Tree.ViewInfo.GetHitTest(Tree.PointToClient(new Point(e.X, e.Y))).Node;
How to fix this?

Bind GridView on Button Click Event with Pagination

I'm new to asp.net and needs some help. I have a gridview with paging for every 20 records per page, I have a search button outside the gridview. What I need to do is when I click the search button, the results must be bind to gridview(which is happening now), however when the records are more than the pagesize and I need to go to the next page of the grid, the binding is lost and the binded records are the ones form the page on load event. below is my code sample.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
public void BindData()
{
{
List<EventFile> eventFile = new List<EventFile>();
eventFile = CoMailAssociationDAL.GetUploadFileUnAssigned(0, "", "", "U");
if (gvwAssociation.DataSource == null)
{
gvwAssociation.DataSource = eventFile;
gvwAssociation.DataBind();
}
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
int uFlag = 0;
string uploadFlag = this.ddlUploadDate.SelectedValue;
string fileName = this.txtSearchText.Text;
string uploadDt = this.txtDate.Text;
string status = this.ddlStatus.SelectedValue.ToString();
bt = true;
if (status == "Un-Assigned")
{
status = "U";
}
else if (status == "Assigned")
{
status = "A";
}
else
{
status = "B";
}
if ((uploadFlag == "On") && (uploadDt == ""))
{
uFlag = 0;
}
else if (uploadFlag == "On")
{
uFlag = 1;
}
else if (uploadFlag == "OnorBefore")
{
uFlag = 2;
}
else
{
uFlag = 3;
}
fileSearch = CoMailAssociationDAL.SearchFile(uFlag, fileName, uploadDt, status);
gvwAssociation.DataSource = fileSearch;
gvwAssociation.DataBind();
}
protected void gvwAssociation_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
//SaveSelectedValues();
gvwAssociation.PageIndex = e.NewPageIndex;
//BindData();
//PopulateSelectedValues();
}
First of all you should have the following event handler for paging
protected void gvwAssociation_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvwAssociation.PageIndex = e.NewPageIndex;
bindGridWithFilter();
}
Then, move your search/ filter logic within the search button to a private method (say "bindGridWithFilter")
TIP: Try to combine both BindData and bindGridWithFilter so when there's no filter you display all records
UPDATE
Here's some refactored code for you to get an idea what I meant above.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindGridWithFilter();
}
}
protected void gvwAssociation_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvwAssociation.PageIndex = e.NewPageIndex;
bindGridWithFilter();
}
protected void btnSearch_Click(object sender, EventArgs e)
{
bindGridWithFilter();
}
private void bindGridWithFilter()
{
List<EventFile> eventFile = new List<EventFile>();
eventFile = CoMailAssociationDAL.GetUploadFileUnAssigned(0, "", "", "U");
if (gvwAssociation.DataSource == null)
{
// If you don't have a filter you show all records
gvwAssociation.DataSource = eventFile;
gvwAssociation.DataBind();
}
else
{
// This is same as the logic in your search button
// display only the filtered records
int uFlag = 0;
string uploadFlag = this.ddlUploadDate.SelectedValue;
string fileName = this.txtSearchText.Text;
string uploadDt = this.txtDate.Text;
string status = this.ddlStatus.SelectedValue.ToString();
bt = true;
if (status == "Un-Assigned")
{
status = "U";
}
else if (status == "Assigned")
{
status = "A";
}
else
{
status = "B";
}
if ((uploadFlag == "On") && (uploadDt == ""))
{
uFlag = 0;
}
else if (uploadFlag == "On")
{
uFlag = 1;
}
else if (uploadFlag == "OnorBefore")
{
uFlag = 2;
}
else
{
uFlag = 3;
}
List<EventFile> fileSearch = CoMailAssociationDAL.SearchFile(uFlag, fileName, uploadDt, status);
gvwAssociation.DataSource = fileSearch;
gvwAssociation.DataBind();
}
}
This should work.

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");
}
}

Webpage hangs after the On_Unload event

Need your help guys.
I have a web application which hangs after clicking a checkbox which is set to autopostback. This checkbox is supposed to do some process.
It didn't fire the OnPreLoad and the OnLoad events.
Below are the codes
protected override void BindReference()
{
BindComboBox(ref rcbPortfolioId, CNPL_Portfolio.GetPortfolioDicWithAll());
BindComboBox(ref rcbProductId, CNPL_Product.GetProductDicWithAll());
BindComboBox(ref rcbNewAgencyId, CNPL_Agency.GetAgencyDicWithAll());
BindComboBox(ref rcbPreviousAgencyId, CNPL_Agency.GetAgencyDicWithAll());
BindComboBox(ref rcbAccountStatusId, CNPL_AccountStatus.GetStatusDic());
BindComboBox(ref rcbAgencyHeader, CNPL_Agency.GetAgencyDic());
}
protected override void SetViewStates()
{
ViewState["ETemp"] = eTemp;
ViewState["AgencyIDRgTemp"] = _AgencyIDRgTemp;
ViewState["PreviousIDRgTemp"] = _PreviousIDRgTemp;
ViewState["ProductIDRgTemp"] = _ProductIDRgTemp;
ViewState["IsRetainedRgTemp"] = _IsRetainedRgTemp;
}
protected override void GetViewStates()
{
if (ViewState["ETemp"] != null)
{
eTemp = (List<CNPL_EndorsementTemp>)ViewState["ETemp"];
}
if (ViewState["AgencyIDRgTemp"] != null)
{
_AgencyIDRgTemp = (int)ViewState["AgencyIDRgTemp"];
}
if (ViewState["PreviousIDRgTemp"] != null)
{
_PreviousIDRgTemp = (int)ViewState["PreviousIDRgTemp"];
}
if (ViewState["ProductIDRgTemp"] != null)
{
_ProductIDRgTemp = (int)ViewState["ProductIDRgTemp"];
}
if (ViewState["IsRetainedRgTemp"] != null)
{
_IsRetainedRgTemp = (bool)ViewState["IsRetainedRgTemp"];
}
}
protected void chkEndorseAuto_OnCheckChange(object sender, EventArgs e)
{
DirectDBAccess db = new DirectDBAccess();
SqlCommand cmd = new SqlCommand("dbo.Proc_UpdateIsIncludedEndorsementTemp");
Int32 _AgencyID=0;
Int32 _PreviousAgencyID=0;
Int32 _IsRetained=0;
Int32 _ProductID=0;
Int32 _IsIncluded=0;
Int32 _NewIsIncluded = 0;
CheckBox cBox = (sender as CheckBox);
GridDataItem item = (cBox.Parent.Parent as GridDataItem);
if (!Int32.TryParse(item["AgencyID"].Text, out _AgencyID))
throw new Exception("Endorsement: Error in parsing");
if (!Int32.TryParse(item["PreviousAgencyID"].Text, out _PreviousAgencyID))
throw new Exception("Endorsement: Error in parsing");
if (!Int32.TryParse(item["ProductID"].Text, out _ProductID))
throw new Exception("Endorsement: Error in parsing");
if (item["IsRetained"].Text.ToLower() == "true")
_IsRetained = 1;
else if (item["IsRetained"].Text.ToLower() == "false")
_IsRetained = 0;
else
throw new Exception("Endorsement: Error in parsing");
if (cBox.Checked)
{
_NewIsIncluded = 1;
_IsIncluded = 0;
}
else
{
_NewIsIncluded = 0;
_IsIncluded = 1;
}
cmd.CommandTimeout = 9500;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#AgencyID",_AgencyID));
cmd.Parameters.Add(new SqlParameter("#PreviousAgencyID", _PreviousAgencyID));
cmd.Parameters.Add(new SqlParameter("#IsRetained", _IsRetained));
cmd.Parameters.Add(new SqlParameter("#ProductID", _ProductID));
cmd.Parameters.Add(new SqlParameter("#IsIncluded", _IsIncluded));
cmd.Parameters.Add(new SqlParameter("#NewIsIncluded", _NewIsIncluded));
db.Open();
db.CommandExecuteNonQuery(cmd,CommandType.StoredProcedure);
db.Close();
}
void rcbPortfolioId_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
{
Int32 _PortfolioID;
_PortfolioID = Int32.Parse(rcbPortfolioId.SelectedValue);
if(_PortfolioID >0)
BindComboBox(ref rcbProductId, CNPL_Product.GetProductDicWithAll(_PortfolioID));
else
BindComboBox(ref rcbProductId, CNPL_Product.GetProductDicWithAll());
}
private void InitializeEndorsementDate()
{
int curingDays;
if (!Int32.TryParse(CNPL_DataSettings.GetSettingValue("CuringPeriod").ToString(), out curingDays))
curingDays = 120;
rdpEndorsementDateFrom.SelectedDate = DateTime.Now;
rdpEndorsementDateTo.SelectedDate = DateTime.Now.AddDays(curingDays - 1);
}
private void InitializeGrids()
{
rgEndorsements.DataSource = new List<CNPL_EndorsementTemp>();
rgEndorsements.DataBind();
//Added by Ryan Estandarte 11/2/2010
rgEndorsements.AllowPaging = true;
rgEndorsements.PageSize = 10;
rgEndorsementTemp.DataSource = new List<CNPL_EndorsementTemp>();
rgEndorsementTemp.DataBind();
}
public Dictionary<int, string> PopulateRgAgencyId()
{
return CNPL_Agency.GetAgencyDic();
}
void btnSearch_Click(object sender, EventArgs e)
{
AssignAccountToEndorsementTemp();
RadAjaxManager1.Alert("finished automatic distribution");
}
private void BindRgEndorsements()
{
rgEndorsements.DataSource = CNPL_EndorsementTemp.GetGroupedEndorsementTemp();
rgEndorsements.DataBind();
}
private void ClearTotals()
{
rntbTotalAccounts.Text = "";
rntbTotalPrincipal.Text = "";
rntbTotalPenalty.Text = "";
rntbTotalInterest.Text = "";
rntbTotalOutstandingBalance.Text = "";
}
private void ShuffleAgencies(ref List<CNPL_Agency> agencyToShuffle)
{
int N = agencyToShuffle.Count;
Random random = new System.Random();
for (int index = 0; index < N; ++index)
{
int randomIndex = index + (int)(random.Next(N - index));
CNPL_Agency _agencyTemp = agencyToShuffle[randomIndex];
agencyToShuffle[randomIndex] = agencyToShuffle[index];
agencyToShuffle[index] = _agencyTemp;
}
}
private void AssignAccountToEndorsementTemp()
{
DirectDBAccess db = new DirectDBAccess();
SqlCommand cmd = new SqlCommand();
string sql;
InitializeGrids();
sql = "dbo.Proc_AssignAccountsForEndorsement";
cmd.CommandText = sql;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 59500;
cmd.Parameters.Add(new SqlParameter("#PortfolioID_Criteria",Int32.Parse(rcbPortfolioId.SelectedValue)));
cmd.Parameters.Add(new SqlParameter("#ProductID_Criteria",Int32.Parse(rcbProductId.SelectedValue)));
cmd.Parameters.Add(new SqlParameter("#NewAgencyID_Criteria",Int32.Parse(rcbNewAgencyId.SelectedValue)));
cmd.Parameters.Add(new SqlParameter("#PreviousAgencyID_Criteria",Int32.Parse(rcbPreviousAgencyId.SelectedValue)));
db.Open();
db.CommandExecuteNonQuery(cmd,CommandType.StoredProcedure);
db.Close();
BindRgEndorsements();
}
void rgEndorsements_ItemCommand(object source, GridCommandEventArgs e)
{
if (e.CommandName == "btnDetails")
{
int pageSize = 10;
if (chkPagingManual.Checked == true)
{
rgEndorsementTemp.AllowPaging = true;
Int32.TryParse(rntbPageSizeManual.Text, out pageSize);
rgEndorsementTemp.PageSize = pageSize;
}
else
rgEndorsementTemp.AllowPaging = false;
_AgencyIDRgTemp = Int32.Parse((e.Item as GridDataItem)["AgencyId"].Text);
_PreviousIDRgTemp = Int32.Parse((e.Item as GridDataItem)["PreviousAgencyId"].Text);
_ProductIDRgTemp = Int32.Parse((e.Item as GridDataItem)["ProductID"].Text);
_IsRetainedRgTemp = Boolean.Parse((e.Item as GridDataItem)["IsRetained"].Text);
BindRgEndorsementTemp();
}
else if (e.CommandName == "btnChange")
{
IList<CNPL_EndorsementTemp> endorsementTemps = new List<CNPL_EndorsementTemp>();
RadComboBox rcbAgencyId = (RadComboBox)(e.Item as GridDataItem).FindControl("rcbAgency");
int _AgencyID = Int32.Parse(rcbAgencyId.SelectedValue);
UpdateEndorsement(e.Item as GridDataItem);
Helper.SaveList(endorsementTemps,this.Web.CurrentUser.LoginName);
//rebind rgEndosements
BindRgEndorsements();
//rebind RgEndorsementTemp w/ respect to agencyid being edited
_AgencyIDRgTemp = Int32.Parse((e.Item as GridDataItem)["AgencyId"].Text);
_PreviousIDRgTemp = Int32.Parse((e.Item as GridDataItem)["PreviousAgencyId"].Text);
BindRgEndorsementTemp();
RadAjaxManager1.Alert("Updated");
}
}
protected void chkEndorseAutoHeader_OnCheckChange(object sender, EventArgs e)
{
CheckBox chk = new CheckBox();
CheckBox chkHeader = sender as CheckBox;
foreach (GridDataItem item in rgEndorsements.Items)
{
chk = (CheckBox)item.FindControl("chkEndorseAuto");
chk.Checked = chkHeader.Checked;
}
IncludeAll(chkHeader.Checked);
}
private void IncludeAll(Boolean chk)
{
DirectDBAccess db = new DirectDBAccess();
string sql;
if(chk == true)
sql = "update CNPL_EndorsementTemp set IsIncluded='True'";
else
sql = "update CNPL_EndorsementTemp set IsIncluded='False'";
SqlCommand cmd = new SqlCommand(sql);
db.Open();
db.CommandExecuteNonQuery(cmd, CommandType.Text);
db.Close();
}
private IList<CNPL_EndorsementTemp> UpdateEndorsement(GridDataItem tempGridDataItem)
{
//update endorsementtemp to database
IList<CNPL_EndorsementTemp> endorsementTemps = new List<CNPL_EndorsementTemp>();
RadComboBox rcbAgencyId = (RadComboBox)tempGridDataItem.FindControl("rcbAgency");
Int32 _AgencyID = Int32.Parse(tempGridDataItem["AgencyID"].Text);
Int32 _PreviousAgencyID = Int32.Parse(tempGridDataItem["PreviousAgencyID"].Text);
string _IsRetained = tempGridDataItem["IsRetained"].Text;
Int32 _ProductID = Int32.Parse(tempGridDataItem["ProductID"].Text);
string filter = string.Format("Where AgencyID={0} And PreviousAgencyID={1} And IsRetained='{2}' And ProductID={3}", _AgencyID, _PreviousAgencyID, _IsRetained, _ProductID);
endorsementTemps = CNPL_EndorsementTemp.GetAllWithFilter(filter);
foreach (CNPL_EndorsementTemp endorsementTemp in endorsementTemps)
{
endorsementTemp.AgencyID = Int32.Parse(rcbAgencyId.SelectedValue);
}
return endorsementTemps;
}
private IList<CNPL_EndorsementTemp> UpdateEndorsementAllChecked(GridDataItem tempGridDataItem)
{
//update endorsementtemp to database
IList<CNPL_EndorsementTemp> endorsementTemps = new List<CNPL_EndorsementTemp>();
Int32 _AgencyID = Int32.Parse(tempGridDataItem["AgencyID"].Text);
Int32 _PreviousAgencyID = Int32.Parse(tempGridDataItem["PreviousAgencyID"].Text);
string filter = string.Format("Where AgencyID={0} And PreviousAgencyID={1}", _AgencyID, _PreviousAgencyID);
endorsementTemps = CNPL_EndorsementTemp.GetAllWithFilter(filter);
foreach (CNPL_EndorsementTemp endorsementTemp in endorsementTemps)
{
endorsementTemp.AgencyID = Int32.Parse(rcbAgencyUpdateAuto.SelectedValue);
}
return endorsementTemps;
}
void btnUpdateAutoAll_Click(object sender, EventArgs e)
{
List<CNPL_EndorsementTemp> endorsementTemps = new List<CNPL_EndorsementTemp>();
//IList<CNPL_EndorsementTemp> temps = new List<CNPL_EndorsementTemp>();
foreach (GridDataItem item in rgEndorsements.Items)
{
CheckBox chk = new CheckBox();
chk = (CheckBox)item.FindControl("chkEndorseAuto");
if (chk.Checked == true)
{
endorsementTemps.AddRange(UpdateEndorsementAllChecked(item));
}
}
if (endorsementTemps.Count > 0)
Helper.SaveList(endorsementTemps, this.Web.CurrentUser.LoginName);
BindRgEndorsements();
_AgencyIDRgTemp = 0;
_PreviousIDRgTemp = 0;
BindRgEndorsementTemp();
RadAjaxManager1.Alert("Updated");
}
void btnEndorse_Click(object sender, EventArgs e)
{
EndorseToAgencies();
RadAjaxManager1.Alert("finished endorsement");
}
private void EndorseToAgencies()
{
DirectDBAccess db = new DirectDBAccess();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "dbo.Proc_EndorseToAgencies";
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 59500;
cmd.Parameters.Add(new SqlParameter("#User", Web.CurrentUser.LoginName));
cmd.Parameters.Add(new SqlParameter("#EndorsementDateFrom", rdpEndorsementDateFrom.SelectedDate));
cmd.Parameters.Add(new SqlParameter("#EndorsementDateTo", rdpEndorsementDateTo.SelectedDate));
db.Open();
db.CommandExecuteNonQuery(cmd, CommandType.StoredProcedure);
db.Close();
BindRgEndorsements();
_AgencyIDRgTemp = 0;
_PreviousIDRgTemp = 0;
BindRgEndorsementTemp();
}
private IList<CNPL_EndorsementDetail> ConvertEndorsementTempToDetails()
{
IList<CNPL_EndorsementTemp> temps = new List<CNPL_EndorsementTemp>();
IList<CNPL_EndorsementDetail> details = new List<CNPL_EndorsementDetail>();
temps = CNPL_EndorsementTemp.GetAll();
details.Clear();
foreach (CNPL_EndorsementTemp temp in temps)
{
CNPL_EndorsementDetail detail = new CNPL_EndorsementDetail();
CNPL_Account _account = new CNPL_Account();
_account = CNPL_Account.GetByID(temp.AccountID);
detail.Account = _account;
detail.Account.IsCurrentlyEndorsed = true;
if (detail.Account.NewAgencyID != 0)
{
detail.Account.PreviousAgencyID = detail.Account.NewAgencyID;
}
detail.Account.EndorsementDateTo = rdpEndorsementDateTo.SelectedDate;
detail.Account.EndorsementDateFrom = rdpEndorsementDateFrom.SelectedDate;
detail.Account.NewAgencyID = temp.AgencyID;
detail.AccountID = temp.AccountID;
detail.AgencyID = temp.AgencyID;
detail.CreatedBy = this.Web.CurrentUser.LoginName;
detail.CreatedDate = DateTime.Now;
details.Add(detail);
}
return details;
}
void rgEndorsementTemp_ItemCommand(object source, GridCommandEventArgs e)
{
if (e.CommandName == "btnChange")
{
RadComboBox rcbAgencyId = (RadComboBox)(e.Item as GridDataItem).FindControl("rcbAgency");
int _AgencyID = Int32.Parse(rcbAgencyId.SelectedValue);
UpdateEndorsementTemp(e.Item as GridDataItem);
BindRgEndorsements();
_AgencyIDRgTemp = Int32.Parse((e.Item as GridDataItem)["OldAgencyID"].Text);
BindRgEndorsementTemp();
RadAjaxManager1.Alert("Updated");
}
}
private void BindRgEndorsementTemp()
{
rgEndorsementTemp.DataSource = CNPL_EndorsementTemp.GetDetailsEndorsementTemp(_AgencyIDRgTemp,_PreviousIDRgTemp,_ProductIDRgTemp,_IsRetainedRgTemp);
rgEndorsementTemp.DataBind();
}
private void UpdateEndorsementTemp(GridDataItem tempGridDataItem)
{
CNPL_EndorsementTemp _EndorsementTemp = new CNPL_EndorsementTemp();
Int32 _ID = Int32.Parse(tempGridDataItem["EndorsementTempID"].Text);
_EndorsementTemp = CNPL_EndorsementTemp.GetByID(_ID);
RadComboBox rcbAgencyId = (RadComboBox)tempGridDataItem.FindControl("rcbAgency");
_EndorsementTemp.AgencyID = Int32.Parse(rcbAgencyId.SelectedValue);
_EndorsementTemp.AccountID = Int32.Parse(tempGridDataItem["AccountID"].Text);
_EndorsementTemp.Save();
}
protected void chkEndorseManualHeader_OnCheckChange(object sender, EventArgs e)
{
CheckBox chk = new CheckBox();
CheckBox chkHeader = sender as CheckBox;
foreach (GridDataItem item in rgEndorsementTemp.Items)
{
chk = (CheckBox)item.FindControl("chkEndorseManual");
chk.Checked = chkHeader.Checked;
}
}
void rgEndorsementTemp_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
{
rgEndorsementTemp.DataSource = CNPL_EndorsementTemp.GetDetailsEndorsementTemp(_AgencyIDRgTemp, _PreviousIDRgTemp, _ProductIDRgTemp, _IsRetainedRgTemp);
}
void btnUpdateManualAll_Click(object sender, EventArgs e)
{
IList<CNPL_EndorsementTemp> temps = new List<CNPL_EndorsementTemp>();
foreach (GridDataItem item in rgEndorsementTemp.Items)
{
CheckBox chk = new CheckBox();
chk = (CheckBox)item.FindControl("chkEndorseManual");
if(chk.Checked == true)
{
CNPL_EndorsementTemp _EndorsementTemp = new CNPL_EndorsementTemp();
Int32 _ID = Int32.Parse(item["EndorsementTempID"].Text);
_EndorsementTemp = CNPL_EndorsementTemp.GetByID(_ID);
_EndorsementTemp.AgencyID = Int32.Parse(rcbAgencyHeader.SelectedValue);
_EndorsementTemp.AccountID = Int32.Parse(item["AccountID"].Text);
temps.Add(_EndorsementTemp);
}
}
if (temps.Count > 0)
Helper.SaveList(temps, this.Web.CurrentUser.LoginName);
BindRgEndorsements();
BindRgEndorsementTemp();
RadAjaxManager1.Alert("Updated");
}
private void GetAccountPerCollectorRatio()
{
accountCollectorRatios = CNPL_AccountCollectorRatio.GetAll();
}
void btnSearchManualAdd_Click(object sender, EventArgs e)
{
if (rbAccountNoMA.Checked == true)
{
if (txtAccountNoMA.Text.Length > 0)
accounts = CNPL_Account.GetAccountLikeAccountNo(txtAccountNoMA.Text);
else
RadAjaxManager1.Alert("Requires search parameter");
}
else if (rbAccountNameMA.Checked == true)
{
if(txtAccountNameMA.Text.Length > 0)
accounts = CNPL_Account.GetAccountLikeAccountName(txtAccountNameMA.Text);
else
RadAjaxManager1.Alert("Requires search parameter");
}
BindRgManualAdd();
}
private void BindRgManualAdd()
{
rgManualAdd.DataSource = accounts;
rgManualAdd.DataBind();
}
void rgManualAdd_ItemCommand(object source, GridCommandEventArgs e)
{
CNPL_Account _Account = CNPL_Account.GetByID(Int32.Parse((e.Item as GridDataItem)["AccountID"].Text));
if (e.CommandName == "btnAdd")
{
CNPL_EndorsementTemp _EndorsementTemp = new CNPL_EndorsementTemp();
List<CNPL_EndorsementTemp> _EndorsementTemps = (List<CNPL_EndorsementTemp>)CNPL_EndorsementTemp.GetAll();
_EndorsementTemp.AccountID = _Account.Id;
_EndorsementTemp.ProductID = _Account.ProductID;
_EndorsementTemp.CurrentBalance = _Account.CurrentBalance;
_EndorsementTemp.AgencyID = _Account.NewAgencyID; Int32.Parse((e.Item as GridDataItem)["NewAgencyID"].Text);
_EndorsementTemp.PreviousAgencyID = _Account.NewAgencyID; Int32.Parse((e.Item as GridDataItem)["PreviousAgencyID"].Text);
_EndorsementTemp.IsRetained = _Account.IsCurrentlyEndorsed==true?true:false;
_EndorsementTemp.IsIncluded = true;
if (_EndorsementTemps.Exists(delegate(CNPL_EndorsementTemp temp) { return temp.AccountID == _EndorsementTemp.AccountID; }))
{
RadAjaxManager1.Alert(_Account.AccountName + " already exists");
}
else
{
_EndorsementTemp.Save(Web.CurrentUser.LoginName);
BindRgEndorsements();
}
}
}
void chkUseManualAdd_CheckedChanged(object sender, EventArgs e)
{
if (!CNPL_EndorsementTemp.DeleteEndorsementTemp())
throw new Exception("endorsement: cannot clear temporary table");
if (chkUseManualAdd.Checked == true)
{
pnlManualAdd.Visible = true;
btnSearch.Enabled = false;
BindRgEndorsements();
BindRgManualAdd();
}
else
{
pnlManualAdd.Visible = false;
btnSearch.Enabled = true;
}
}
protected override void OnInit(EventArgs e)
{
try
{
rcbPortfolioId.SelectedIndexChanged += new RadComboBoxSelectedIndexChangedEventHandler(rcbPortfolioId_SelectedIndexChanged);
btnSearch.Click += new EventHandler(btnSearch_Click);
btnEndorse.Click += new EventHandler(btnEndorse_Click);
tnUpdateManualAll.Click += new EventHandler(btnUpdateManualAll_Click);
rgEndorsements.ItemCommand += new GridCommandEventHandler(rgEndorsements_ItemCommand);
rgEndorsements.NeedDataSource += new GridNeedDataSourceEventHandler(rgEndorsements_NeedDataSource);
rgEndorsementTemp.ItemCommand += new GridCommandEventHandler(rgEndorsementTemp_ItemCommand);
rgEndorsementTemp.NeedDataSource += new GridNeedDataSourceEventHandler(rgEndorsementTemp_NeedDataSource);
rgEndorsements.ItemEvent += new GridItemEventHandler(rgEndorsements_ItemEvent);
btnSearchManualAdd.Click += new EventHandler(btnSearchManualAdd_Click);
rgManualAdd.ItemCommand += new GridCommandEventHandler(rgManualAdd_ItemCommand);
chkUseManualAdd.CheckedChanged += new EventHandler(chkUseManualAdd_CheckedChanged);
btnViewDistributed.Click += new EventHandler(btnViewDistributed_Click);
btnPullout.Click += new EventHandler(btnPullout_Click);
base.OnInit(e);
}
catch (Exception ex)
{
string message = ex.Message;
}
}
protected void UpdateAgency(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
{
int newAgencyID = 0;
RadComboBox newAgencyDropdown = sender as RadComboBox;
foreach (GridDataItem item in rgEndorsements.Items)
{
newAgencyDropdown = (RadComboBox)item.FindControl("rcbAgency");
Int32 _AgencyID = Int32.Parse(item["AgencyID"].Text);
newAgencyID = int.Parse(newAgencyDropdown.SelectedValue);
if (_AgencyID != newAgencyID)
{
Int32 _PreviousAgencyID = Int32.Parse(item["PreviousAgencyID"].Text);
string _IsRetained = item["IsRetained"].Text;
Int32 _ProductID = Int32.Parse(item["ProductID"].Text);
DirectDBAccess db = new DirectDBAccess();
string sqlEndorse = string.Format("UPDATE CNPL_EndorsementTemp SET AgencyID={0} Where AgencyID={1} And PreviousAgencyID={2} And IsRetained='{3}' And ProductID={4}", newAgencyID, _AgencyID, _PreviousAgencyID, _IsRetained, _ProductID);
SqlCommand cmd = new SqlCommand(sqlEndorse);
db.Open();
db.CommandExecuteNonQuery(cmd, CommandType.Text);
db.Close();
break;
}
}
BindRgEndorsements();
}
protected override void OnUnload(EventArgs e)
{
try
{
base.OnUnload(e);
Locker.inUse = false;
Locker.isCompleted = true;
Locker.user = "";
}
catch (Exception ex)
{
string message = ex.Message;
}
}
protected override void OnLoad(EventArgs e)
{
try
{
Server.ScriptTimeout = 9500;
if (Locker.inUse == true && Locker.isCompleted == false && Locker.user.ToLower() != this.Web.CurrentUser.LoginName.ToLower())
{
Response.Redirect("error.aspx?innerException=Another User is already accessing endorsement&pageFrom=Endorsement To Agency"); //throw new Exception("Another user is already processing endorsement");
}
Locker.inUse = true;
Locker.isCompleted = false;
Locker.user = this.Web.CurrentUser.LoginName;
security = new Security(this.Web.CurrentUser);
userGroups = security.GetUserGroups();
if (userGroups.Contains(SecurityGroups.Star))
{
;
}
else if (userGroups.Contains(SecurityGroups.Agency))
{
Response.Redirect("Error.aspx?innerException=" + "Unauthorized Access." + "&pageFrom=AgencyProfile");
}
else if (userGroups.Contains(SecurityGroups.TeamCollector))
{
Response.Redirect("Error.aspx?innerException=" + "Unauthorized Access." + "&pageFrom=AgencyProfile");
}
else
Response.Redirect("Error.aspx?innerException=" + "Unauthorized Access." + "&pageFrom=AgencyProfile");
if (!Page.IsPostBack)
{
BindReference();
InitializeGrids();
InitializeEndorsementDate();
rbAccountNoMA.Checked = true;
chkUseManualAdd.Checked = false;
pnlManualAdd.Visible = false;
}
else
{
GetViewStates();
}
base.OnLoad(e);
}
catch (Exception ex)
{
string message = ex.Message;
}
}
protected override void OnPreRender(EventArgs e)
{
try
{
ComputeEndorsementTotals();
SetViewStates();
base.OnPreRender(e);
}
catch (Exception ex)
{
string message = ex.Message;
}
}
}
There is an error somewhere in your OnInit
Try placing try catch blocks around each step and step into (not over) each function in there to see if you have any problems.
My guess is you have a try...catch with an empty catch statement - otherwise you'd have an exception to deal with.
We really need to see the code behind, its probably obvious to some of us here when we see the code.
I found the answer to my problem.
There's one event that is not used, and it is this.
rgEndorsements.ItemEvent += new GridItemEventHandler(rgEndorsements_ItemEvent);
It seems that we must check if all the events that are "instantiated" are being used. Thanks for your suggestions! Highly appreciate it.

Categories