Release used memory after closing a form - c#

I have ribbon form that contain DevExpress Tabbed View.
When I start the program in the task manager, I am getting 118.6 MB of used memory
Now when I open new form "FrmWeldingProduction" on Tabbed View
I get these results (Used Memory) when I open and close form "FrmWeldingProduction"
First open 274.4 MB First close 272.1 MB
Second open 403.9 MB Second close 401.6 MB
Third open 564.9 MB Third close 562.2 MB
This is the code behind the form
public partial class FrmWeldingProduction : XtraForm, IDisposable
{
readonly CLS_Welding welding = new();
readonly CLS_User us = new();
private RepOptionsFirstLastTime firstLastTime = new();
private readonly CultureInfo cultureInfo = CultureInfo.CurrentCulture;
private readonly string WeldingProduction = Application.StartupPath + "\\WeldingProduction.xml";
private readonly string LayoutWeldingProduction = "LayoutWeldingProduction";
private readonly int IDScreen = 19;
public FrmWeldingProduction() { InitializeComponent(); }
private async Task Permission()
{
using(DataTable Dt = await us.ApplayPermission(Program.UserID, IDScreen).ConfigureAwait(true))
{
if(Dt.Rows[0][1].ToString() == "False" || string.IsNullOrEmpty(Dt.Rows[0][1].ToString()))
{
repItemCreationDate.ReadOnly = true;
}
if(Dt.Rows[0][2].ToString() == "False" || string.IsNullOrEmpty(Dt.Rows[0][2].ToString()))
{
btnDelete.Enabled = false;
btnDeleteNoir.Enabled = false;
}
}
}
private void FrmWeldingProduction_FormClosed(object sender, FormClosedEventArgs e)
{
workspaceManager1.CaptureWorkspace(LayoutWeldingProduction, true);
workspaceManager1.SaveWorkspace(LayoutWeldingProduction, WeldingProduction, true);
DisposeFrm();
}
public void DisposeFrm()
{
us.Dispose();
firstLastTime.Dispose();
this.Load -= FrmWeldingProduction_Load;
gridView1.FocusedRowChanged -= gridView1_FocusedRowChanged;
repItemCreationDate.DrawItem -= RepItemCreationDate_DrawItem;
btnRefresh.Click -= btnRefresh_Click;
this.KeyDown -= FrmWeldingProduction_KeyDown;
btnProductionProject.ItemClick -= btnProductionProject_ItemClick;
gridView1.CellValueChanged -= GridView1_CellValueChanged;
Dispose(true);
GC.SuppressFinalize(this);
}
private async void gridView1_FocusedRowChanged(
object sender,
DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
{
if(e.FocusedRowHandle > 0)
{
using(DataTable EmployeeWeldingByProduction = await welding.GetEmployeeWeldingByProduction(
Convert.ToInt32(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "FK_ShiftTime"), cultureInfo),
Convert.ToDateTime(
gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "Date de fabrication"),
cultureInfo)
.ToString("MM/dd/yyyy", cultureInfo),
Convert.ToInt32(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "FK_idPartShip"), cultureInfo),
Convert.ToInt32(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "OrderNumber"), cultureInfo))
.ConfigureAwait(true))
{
gridControl2.DataSource = EmployeeWeldingByProduction;
}
}
}
private async void btnRefresh_Click(object sender, EventArgs e)
{
using(DataTable WeldingProduction = await welding.GetWeldingProduction().ConfigureAwait(true))
{
gridControl1.DataSource = WeldingProduction;
}
using(DataTable WeldingPaintProduction = await welding.GetWeldingPaintProduction().ConfigureAwait(true))
{
gridControl3.DataSource = WeldingPaintProduction;
}
using(DataTable WeldingPaintFabRest = await welding.GetWeldingPaintFabRest().ConfigureAwait(true))
{
gridControl4.DataSource = WeldingPaintFabRest;
}
using(DataTable WeldingPaintStatusCHProject = await welding.GetWeldingPaintStatusCHProject()
.ConfigureAwait(true))
{
gridControl5.DataSource = WeldingPaintStatusCHProject;
}
using(DataTable ProductionCharpent = await welding.GetProductionCharpent().ConfigureAwait(true))
{
gridControl6.DataSource = ProductionCharpent;
}
using(DataTable StatusSupportsBS = await welding.GetStatusSupportsBS().ConfigureAwait(true))
{
gridControl7.DataSource = StatusSupportsBS;
}
if(gridView1.FocusedRowHandle > 0)
{
using(DataTable EmployeeWeldingByProduction = await welding.GetEmployeeWeldingByProduction(
Convert.ToInt32(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "FK_ShiftTime"), cultureInfo),
Convert.ToDateTime(
gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "Date de fabrication"),
cultureInfo)
.ToString("MM/dd/yyyy", cultureInfo),
Convert.ToInt32(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "FK_idPartShip"), cultureInfo),
Convert.ToInt32(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "OrderNumber"), cultureInfo))
.ConfigureAwait(true))
{
gridControl2.DataSource = EmployeeWeldingByProduction;
}
}
}
private async void FrmWeldingProduction_Load(object sender, EventArgs e)
{
KeyPreview = true;
btnRefresh_Click(sender, e);
foreach(GridColumn columnDateEdit in gridView1.Columns)
columnDateEdit.OptionsColumn.AllowEdit = false;
gridView1.Columns["Date de fabrication"].OptionsColumn.AllowEdit = true;
//pivotGridControl1.DataSource = await welding.GetProductionCharpent().ConfigureAwait(true);
workspaceManager1.TargetControl = this;
workspaceManager1.SaveTargetControlSettings = true;
if(workspaceManager1.LoadWorkspace(LayoutWeldingProduction, WeldingProduction, true))
workspaceManager1.ApplyWorkspace(LayoutWeldingProduction);
await Permission().ConfigureAwait(true);
}
private bool IsHoliday(DateTime dt)
{
//the specified date is a Holiday
if(dt.DayOfWeek == DayOfWeek.Friday)
return true;
//New Year's Day
if(dt.Day == 1 && dt.Month == 1)
return true;
//Independence Day
if(dt.Day == 5 && dt.Month == 7)
return true;
//VAlgerian War of Independence
if(dt.Day == 1 && dt.Month == 11)
return true;
//Employees Day
if(dt.Day == 1 && dt.Month == 5)
return true;
return false;
}
private void RepItemCreationDate_DrawItem(
object sender,
DevExpress.XtraEditors.Calendar.CustomDrawDayNumberCellEventArgs e)
{
if(e.View != DevExpress.XtraEditors.Controls.DateEditCalendarViewType.MonthInfo)
return;
//return if a given date is not a holiday
//in this case the default drawing will be performed (e.Handled is false)
if(!IsHoliday(e.Date))
return;
//highlight the selected and hot-tracked dates
bool isHotTracked = e.State == DevExpress.Utils.Drawing.ObjectState.Hot;
if(e.Selected || isHotTracked)
{
e.Graphics.FillRectangle(e.Style.GetBackBrush(e.Cache), e.Bounds);
}
//the brush for painting days
Brush brush = (e.Inactive ? Brushes.LightPink : Brushes.Red);
//specify formatting attributes for drawing text
using(StringFormat strFormat = new StringFormat
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
})
{
//draw the day number
e.Graphics.DrawString(e.Date.Day.ToString(), e.Style.Font, brush, e.Bounds, strFormat);
}
//no default drawing is required
e.Handled = true;
}
private void FrmWeldingProduction_KeyDown(object sender, KeyEventArgs e)
{
try
{
if(e.KeyCode == Keys.F5)
{
btnRefresh_Click(sender, e);
}
} catch
{
}
}
private void btnProductionProject_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
if(firstLastTime == null || firstLastTime.IsDisposed)
firstLastTime = new RepOptionsFirstLastTime();
firstLastTime.Show();
firstLastTime.OK.Click += ProductionProject_Click;
}
private async void ProductionProject_Click(object sender, EventArgs e)
{
using(RepWeldingProductionSumm report = new())
{
// Create a new parameter.
Parameter param1 = new();
Parameter param2 = new();
Parameter param3 = new();
// Specify required properties.
param1.Name = "FirstDatepara1";
param1.Type = typeof(DateTime);
param1.Visible = false;
param1.Value = Convert.ToDateTime(firstLastTime.FirstDate.EditValue, cultureInfo)
.ToString("dd/MM/yyyy", cultureInfo);
param2.Name = "lastDatepara2";
param2.Type = typeof(DateTime);
param2.Visible = false;
param2.Value = Convert.ToDateTime(firstLastTime.LastDate.EditValue, cultureInfo)
.ToString("dd/MM/yyyy", cultureInfo);
param3.Name = "shifttime";
param3.Type = typeof(string);
param3.Visible = false;
param3.Value = firstLastTime.cmbShiftTime.Text;
report.Parameters.Add(param1);
report.Parameters.Add(param2);
report.Parameters.Add(param3);
if(firstLastTime.cmbShiftTime.Text == Resources.allDay ||
string.IsNullOrEmpty(firstLastTime.cmbShiftTime.Text))
{
report.DataSource = await welding.RepWeldingProductionSumm(
Convert.ToDateTime(firstLastTime.FirstDate.EditValue, cultureInfo)
.ToString("MM/dd/yyyy", cultureInfo),
Convert.ToDateTime(firstLastTime.LastDate.EditValue, cultureInfo)
.ToString("MM/dd/yyyy", cultureInfo))
.ConfigureAwait(true);
firstLastTime.Close();
report.ShowRibbonPreviewDialog();
} else
{
report.DataSource = await welding.RepWeldingProductionShiftTimeSumm(
Convert.ToDateTime(firstLastTime.FirstDate.EditValue, cultureInfo)
.ToString("MM/dd/yyyy", cultureInfo),
Convert.ToDateTime(firstLastTime.LastDate.EditValue, cultureInfo)
.ToString("MM/dd/yyyy", cultureInfo),
Convert.ToInt32(firstLastTime.cmbShiftTime.EditValue, cultureInfo))
.ConfigureAwait(true);
firstLastTime.Close();
report.ShowRibbonPreviewDialog();
}
}
}
private async void GridView1_CellValueChanged(
object sender,
DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
{
await Permission().ConfigureAwait(true);
if(e.Column.FieldName == "Date de fabrication")
{
await welding.UpdtaeCreationDateWeldingProduction(
Convert.ToInt32(gridView1.GetRowCellValue(e.RowHandle, "id"), cultureInfo),
Convert.ToDateTime(e.Value))
.ConfigureAwait(true);
XtraMessageBox.Show(
Resources.operationAccomplishedSuccessfully,
Resources.Confirmation,
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
}
}

Related

c# Windows Form slow rendering objects

I have spent some time designing my first project using C#, it is a Windows form project with 8 buttons on the side. pressing one of the buttons will open another form within the parent form as a window. On clicking the button the new form loads up about 27 objects mostly Labels, Textboxes, Comboboxes and a few DateTimePickers. For some reason it you can see it drawing the boxes and it looks slow. I have an SQL db included with my project which is tiny and contains only 2 rows of data. It is very dishearting to spend all that time working on it only to see it run like a ZX Spectrum. I am using Microsoft Visual Studio 2019 and is fully updated. I have no errors, no warnings thank god but the performance is horrible. One of the comboBoxes when selected will make visible 3 more textBoxes and even making those visible is really slow. Is there something I am doing wrong or is there a way to have it working faster please?
This is the code of my childForm which opens from the main parentForm, sorry is is a bit long but it is all of it.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace AvianManager.Forms
{
public partial class formMyBirds : Form
{
SqlConnection connection = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Dion\Documents\AvianManager.mdf;Integrated Security=True;Connect Timeout=30");
public formMyBirds()
{
InitializeComponent();
}
private void formMyBirds_Load(object sender, EventArgs e)
{
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
var form = Application.OpenForms["formMyBirdsHelper"]; // Lookup form and check if already open
if (form == null)
{
formMyBirdsHelper MyBirdsHelper = new formMyBirdsHelper(); // Instantiate a FormMyBirdsHelp object.
MyBirdsHelper.Show(); // Show FormMyBirdsHelp and
}
}
private void comboBoxLegBandType_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = this.comboBoxLegBandType.GetItemText(this.comboBoxLegBandType.SelectedItem);
if (selected != "None" || selected == null)
{
textBoxLegBandID.Visible = true;
labelLegBandId.Visible = true;
textBoxLegBandSize.Visible = true;
labelLegBandSize.Visible = true;
}
else
{
textBoxLegBandID.Visible = false;
labelLegBandId.Visible = false;
textBoxLegBandSize.Visible = false;
labelLegBandSize.Visible = false;
}
}
private void comboBoxPrevOwner_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = this.comboBoxPrevOwner.GetItemText(this.comboBoxPrevOwner.SelectedItem);
if (selected != "No")
{
textBoxLastOwnerName.Visible = true;
labelLastOwnerName.Visible = true;
textBoxLastOwnerFone.Visible = true;
labelLastOwnerFone.Visible = true;
textBoxLastOwnerAddr.Visible = true;
labelLastOwnerAddr.Visible = true;
}
else
{
textBoxLastOwnerName.Visible = false;
labelLastOwnerName.Visible = false;
textBoxLastOwnerFone.Visible = false;
labelLastOwnerFone.Visible = false;
textBoxLastOwnerAddr.Visible = false;
labelLastOwnerAddr.Visible = false;
}
}
private void comboBoxVitalStatus_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = this.comboBoxVitalStatus.GetItemText(this.comboBoxVitalStatus.SelectedItem);
if (selected != "Alive")
{
dateTimeDateOfDeath.Visible = true;
labelDateOfDeath.Visible = true;
textBoxCauseOfDeath.Visible = true;
labelCauseOfDeath.Visible = true;
}
else
{
dateTimeDateOfDeath.Visible = false;
labelDateOfDeath.Visible = false;
textBoxCauseOfDeath.Visible = false;
labelCauseOfDeath.Visible = false;
}
}
private void comboBoxRetained_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = this.comboBoxRetained.GetItemText(this.comboBoxRetained.SelectedItem);
if (selected != "Yes")
{
dateTimeRelinquishedDate.Visible = true;
labelRelinquishedDate.Visible = true;
}
else
{
dateTimeRelinquishedDate.Visible = false;
labelRelinquishedDate.Visible = false;
}
}
private void textBoxUid_TextChanged(object sender, EventArgs e)
{
SqlCommand cmd1 = new SqlCommand("select top 1 * from dbMyBirds where db_Uid = '" + textBoxUid.Text + "'", connection);
cmd1.Parameters.AddWithValue("db_Uid", textBoxUid.Text);
SqlDataReader reader1;
connection.Open();
reader1 = cmd1.ExecuteReader();
if (reader1.Read())
{
labelResult.Text = "Found";
textBoxName.Text = reader1["db_Name"].ToString();
textBoxSpecies.Text = reader1["db_Species"].ToString();
comboBoxLegBandType.Text = reader1["db_LegBandType"].ToString();
textBoxLegBandID.Text = reader1["db_LegBandId"].ToString();
textBoxLegBandSize.Text = reader1["db_LegBandSize"].ToString();
comboBoxPrevOwner.Text = reader1["db_PrevOwner"].ToString();
textBoxLastOwnerName.Text = reader1["db_PrevOwnerName"].ToString();
textBoxLastOwnerFone.Text = reader1["db_PrevOwnerFone"].ToString();
textBoxLastOwnerAddr.Text = reader1["db_PrevOwnerAddr"].ToString();
comboBoxIsHybrid.Text = reader1["db_Hybrid"].ToString();
comboBoxRearedBy.Text = reader1["db_RearedBy"].ToString();
textBoxDisformaties.Text = reader1["db_Disformaties"].ToString();
comboBoxVitalStatus.Text = reader1["db_VitalStatus"].ToString();
dateTimeDateOfDeath.Text = reader1["db_DateDied"].ToString();
textBoxCauseOfDeath.Text = reader1["db_CauseOfDeath"].ToString();
comboBoxRetained.Text = reader1["db_Retained"].ToString();
dateTimeRelinquishedDate.Text = reader1["db_RelinquishedDate"].ToString();
dateTimeHatchDate.Text = reader1["db_HatchDate"].ToString();
dateTimeFledgeDate.Text = reader1["db_FledgeDate"].ToString();
comboBoxMaleParentHybrid.Text = reader1["db_MPisHybrid"].ToString();
textBoxMaleParentId.Text = reader1["db_MPUid"].ToString();
textBoxMaleParentSpecies.Text = reader1["db_MPSpecies"].ToString();
comboBoxHenParentHybrid.Text = reader1["db_FPisHybrid"].ToString();
textBoxHenParentId.Text = reader1["db_FPUid"].ToString();
textBoxHenParentSpecies.Text = reader1["db_FPSpecies"].ToString();
textBoxNotes.Text = reader1["db_Notes"].ToString();
}
else
{
resetInputs();
if (textBoxUid.Text == "")
{
labelResult.Text = "Live Search";
}
else
{
labelResult.Text = "Nothing Found";
}
}
connection.Close();
}
//Reset input fields if no results
private void resetInputs()
{
string dt2;
DateTime date2 = DateTime.Now;
dt2 = date2.ToShortDateString(); // display format: 15/07/2021
textBoxName.Text = "";
textBoxSpecies.Text = "";
comboBoxLegBandType.Text = "Select";
textBoxLegBandID.Text = "";
textBoxLegBandSize.Text = "";
comboBoxPrevOwner.Text = "Select";
textBoxLastOwnerName.Text = "";
textBoxLastOwnerFone.Text = "";
textBoxLastOwnerAddr.Text = "";
comboBoxIsHybrid.Text = "Select";
comboBoxRearedBy.Text = "Select";
textBoxDisformaties.Text = "";
comboBoxVitalStatus.Text = "Select";
dateTimeDateOfDeath.Text = dt2;
textBoxCauseOfDeath.Text = "";
comboBoxRetained.Text = "Select";
dateTimeRelinquishedDate.Text = dt2;
dateTimeHatchDate.Text = dt2;
dateTimeFledgeDate.Text = dt2;
comboBoxMaleParentHybrid.Text = "Select";
textBoxMaleParentId.Text = "";
textBoxMaleParentSpecies.Text = "";
comboBoxHenParentHybrid.Text = "Select";
textBoxHenParentId.Text = "";
textBoxHenParentSpecies.Text = "";
textBoxNotes.Text = "";
}
private void buttonInsert_Click(object sender, EventArgs e)
{
}
}
}

WebBrowser Not Firing LoadComplete, but Navigating Firing

I have userControl(wpf)
public WebBrowserControl()
{
InitializeComponent();
_Browser = new WebBrowser();
_pipeClient = new NamedPipeClient<WebMessage>("TestPipe");
_pipeClient.ServerMessage += PipeClientOnServerMessage;
_pipeClient.Error += PipeClientOnError;
_pipeClient.Start();
InternetExplorerBrowserEmulation.SetBrowserEmulationMode();
SuppressScriptErrors(_Browser, false);
SetWebBrowserFeatures();
GridBrrw.Children.Add(_Browser);
_Browser.ObjectForScripting = new ObjectForScripting(_pipeClient);
_Browser.LoadCompleted += new LoadCompletedEventHandler(_Browser_OnLoadCompleted);
_Browser.Navigating += _Browser_OnNavigating;
var th = new Thread(ExecuteInForeground);
th.Start();
}
private void ExecuteInForeground()
{
int i = 0;
while (i<=9)
{
Thread.Sleep(1000);
_pipeClient.PushMessage(new WebMessage() {Actions = "allo"});
i++;
}
}
private void _Browser_OnNavigating(object sender, NavigatingCancelEventArgs e)
{
if (IsClick)
{
var mes = new WebMessage { Actions = "OpenUrl" };
mes.Url = e.Uri.AbsoluteUri;
_pipeClient.PushMessage(mes);
e.Cancel = false;
}
return;
e.Cancel = false;
}
private void _Browser_OnLoadCompleted(object sender, NavigationEventArgs e)
{
try
{
var br = sender as WebBrowser;
if (br?.Source != null && br.Source.AbsoluteUri != e.Uri.AbsoluteUri)
{
MessageBox.Show($"Source = {br.Source.AbsoluteUri},\r\n AbsoluteUri = {e.Uri.AbsoluteUri}");
return;
}
Document = (HTMLDocument)br.Document;
if (!string.IsNullOrEmpty(FindElement))
{
var node = HtmlNode.CreateNode(FindElement);
while (GetElement(node) == null)
{
System.Windows.Forms.Application.DoEvents();
}
}
if (WaitAjax)
{
ConnectToAjax();
return;
}
if (Sleep > 0)
{
var time = TimeSpan.FromSeconds(Sleep);
Thread.Sleep(time);
}
var mes = new WebMessage { Actions = "Load" };
mes.Title = Document.title;
mes.Url = br.Source.AbsoluteUri;
mes.Domain = br.Source.Host.Replace("http", "").Replace("http://", "").Replace("https://", "").Replace("https", "");
mes.Fovicon = $"http://www.google.com/s2/favicons?domain={mes.Domain}";
if (Document != null)
{
var htmls = Document.getElementsByTagName("html");
if (htmls != null && htmls.length > 0)
{
var html = htmls.item(0) as IHTMLElement;
mes.Html = html.outerHTML;
}
}
_pipeClient.PushMessage(mes);
}
catch (Exception ex)
{
throw ex;
}
}
Event Navigating firing, ExecuteInForeground sends messages, but LoadCompleted event is not firing. Could this be due to the settings window - Property = "ResizeMode" Value = "NoResize". What am I doing wrong?

Master/Details ASP.NET C# DataGrid?

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

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.

Categories