Login Login
MORE

WIDGETS

Widgets

Wanted articles
Who is online?
Article tools

CSharp:WindowsForm Soluzioni varie

From Aino Wiki

Jump to: navigation, search

UI

UserInterface

Elementi

DataGridView

Binding

Dopo aver aggiunto al Form l'oggetto ecco come avviene semplicemnte il binding:

//..
private System.Windows.Forms.DataGridView DTGrdV_SourceData;
//..
DataTable dtFromCSV = new DataTable();
//..
DTGrdV_SourceData.DataSource = dtFromCSV;

Selezione

Verifica selezione:

if (DtGrd_TaskList.SelectedRows.Count != 0)
{
	DataGridViewRow row = this.DtGrd_TaskList.SelectedRows[0];
	taskCode = row.Cells["TaskCode"].Value.ToString();
 
	//...
}

Handler evento selezione:

// Nella partial class del file di Designer.cs
this.DtGrd_TaskList.SelectionChanged += DtGrd_TaskList_SelectionChanged;
 
//Nel file del Form, l'handler è:
private void DtGrd_TaskList_SelectionChanged(object sender, System.EventArgs e)
{
	string strErrorMsg = string.Empty;
	string taskCode = string.Empty;
	try
	{
		DataGridViewRow row = this.DtGrd_TaskList.SelectedRows[0];
		taskCode = row.Cells["TaskCode"].Value.ToString();
	}
	catch (Exception ex)
	{
		strErrorMsg = string.Format("On task selected '{0}':\r\n{1}", taskCode, ex.Message);
		m_logger.Error(strErrorMsg);
	}
}

Refresh

Consiglio l'uso del metodo .Update() !

private void RefreshDatagrid()
{
	m_DisableGridSelectChng = true;   // Per evitare che si scateni l'evento  _SelectionChanged
	DtGrd_TaskList.DataSource = null; //Per resettare
	DtGrd_TaskList.Update();    // Dovrebbe esser necessario SOLO QUESTO !!!
	DtGrd_TaskList.DataSource = SharedDataModel.LstTasks.OrderBy(x => x.TaskCode).ToArray();
	DtGrd_TaskList.Update();
	m_DisableGridSelectChng = false;
	SS_item_SPO_nr_tasks.Text = SharedDataModel.LstTasks.Count.ToString(); //Conteggio elementi nella Status Bar
}

Filtraggio

 

ComboBox

Ll binding:

Dictionary<string, string> dctCmbBoxTaskType = new Dictionary<string, string>();
 
dctCmbBoxTaskType = new Dictionary<string, string>();
BindingSource bndSrcCmb = new BindingSource(); //??? Serve ???
 
//dctCmbBoxTaskType.Add("Select a type", string.Empty);
dctCmbBoxTaskType.Add("Copy from SPO to File system", EnumTaskType.Copy_SPO_vs_FS.ToString());
dctCmbBoxTaskType.Add("Copy from File system to SPO", EnumTaskType.Copy_FS_vs_SPO.ToString());
 
bndSrcCmb.DataSource = dctCmbBoxTaskType;
CmbTaskType.DataSource = bndSrcCmb;
CmbTaskType.DisplayMember = "Key";
CmbTaskType.ValueMember = "Value";

Costruzione dinamica di un Form

Riempimento di un Panel

L'esempio che segue riempie un panel con n checkbox precedure da una label che identifica il gruppo (è uno stralcio di un esempio reale). Notare che la locazione di ciascun oggetto deve cambiare ed allo scopo si usa la proprietà 'Location' di ciascun controllo da aggiungere al form, le due cordinate sono la ascissa e l'ordinata nell'ordine.

int y = 0;
string companyName = string.Empty;
CheckBox ChkBx = new CheckBox();
Label LblCompayName = new Label();
foreach (KeyValuePair<string, ShipFolderInfo> pair in MultiPrepareKTUpdater.Model.Configuration.DctShipFolderList)
{
	if (companyName != pair.Value.CompanyName)
	{
		LblCompayName = new Label();
 
		companyName = pair.Value.CompanyName;
		LblCompayName.Text = companyName;
		LblCompayName.Location = new Point(25, y);
		PnlShipListToUpdate.Controls.Add(LblCompayName);  
		y = y + 25;
	}
 
	ChkBx = new CheckBox();
	ChkBx.Name = c_MultiCopy_ChkPrefix_Ship + pair.Key;
	ChkBx.AutoSize = true;
	ChkBx.Text = string.Format("{0} {1}", pair.Value.ShipCode, pair.Value.ShipName);
	ChkBx.Location = new Point(25, y);
	ChkBx.Enabled = pair.Value.Enabled;
	PnlShipListToUpdate.Controls.Add(ChkBx);
	y = y + 25;
}

Verifiche sui controlli aggiunti

La seguente restituisce una stringa CSV con gli ID dei checkBox ceccatti i quali son stati aggiunti dinamicamente come da capitolo precedente.
        private bool CheckBeforeCopy(string rootDestinationPath, string[] arrShipFullCode, out string strError)
        {
            bool ok = true;
            string shipCode = string.Empty;
            string destinationPath = string.Empty;
 
            strError = string.Empty;
            try
            {
                foreach (string shipFullCode in arrShipFullCode)
                {
                    if (!string.IsNullOrEmpty(shipFullCode))
                    {
                        destinationPath = GetDestinationPath(shipFullCode);
                        if (Directory.Exists(destinationPath))
                        {
                            ok = false;
                            strError += string.Format("The path:\r\n'{0}'\r\nalready exists for the ship full code: '{1}'.\r\n\r\n",
                                            destinationPath, shipFullCode);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ok = false;
                strError = string.Format("CheckBoxBeforeCopy() {0}", ex.Message);
            }
            return ok;
        }

Handler di un bottone dinamico

Supponendo di aggiungere n bottoni ad un pannello e di avere un unico handler che deve riconoscere quale oggetto ha scatenato l'evento e di conseguenza agire. Il riconoscimento avverrà attraverso la proprietà name.Ecco un esempio:
	Button BtnOpenShipConfigFile = new Button();
	foreach (KeyValuePair<string, ShipFolderInfo> pair in MultiPrepareKTUpdater.Model.Configuration.DctShipFolderList)
	{
		// etc ...
 
		// Aggiunta bottone per aprire il file di configurazione
		BtnOpenShipConfigFile = new Button();
		BtnOpenShipConfigFile.Name = c_MultiCopy_BtnPrefix_OpnShipCfg + pair.Key;
		BtnOpenShipConfigFile.Text = "Open Cfg";
		BtnOpenShipConfigFile.Location = new Point(x + 185, y - 4);
		BtnOpenShipConfigFile.Click += BtnOpenShipConfigFile_Click;
		PnlShipListToUpdate.Controls.Add(BtnOpenShipConfigFile);
	}
 
// Unico handler chiamato. Dal sender trasformato in Button estratto il name e da 
// dopo aver tolto una porzione di stringa dal nome otterrò il codice che identifica il
// bottone... tale codice è in:  pair.Key
private void BtnOpenShipConfigFile_Click(object sender, EventArgs e)
{
	try
	{
		Button b = (Button)sender;
		MessageBox.Show(string.Format("{0}", b.Name), string.Format("BtnOpenShipConfigFile_Click"),
						MessageBoxButtons.OK, MessageBoxIcon.Information);
	}
	catch (Exception ex)
	{
		MessageBox.Show(string.Format("{0}", ex.Message), string.Format("BtnOpenShipConfigFile_Click"),
						MessageBoxButtons.OK, MessageBoxIcon.Error);
	}
}

Passare un parametro all'Handler

Va bene ricavare un codice identificativo dal nome del controllo dinamico ottenuto nell'handler ma se volessi passare parametri tipizzati? Ecco come, usando una lambda expression:
	Button BtnOpenShipConfigFile = new Button();
	foreach (KeyValuePair<string, ShipFolderInfo> pair in MultiPrepareKTUpdater.Model.Configuration.DctShipFolderList)
	{
		// etc ...
 
 
		// Aggiunta bottone per aprire il file di configurazione
		BtnOpenShipConfigFile = new Button();
		BtnOpenShipConfigFile.Name = c_MultiCopy_BtnPrefix_OpnShipCfg + pair.Key;
		BtnOpenShipConfigFile.Text = "Open Cfg";
		BtnOpenShipConfigFile.Location = new Point(x + 185, y - 4);
		//BtnOpenShipConfigFile.Click += BtnOpenShipConfigFile_Click;
		BtnOpenShipConfigFile.Click += (sender, e) => BtnOpenShipConfigFile_Click(sender, e, "parStr1,parStrN");
		PnlShipListToUpdate.Controls.Add(BtnOpenShipConfigFile);
	}
 
 
// Unico handler chiamato con parametro custom in fondo !!!
private void BtnOpenShipConfigFile_Click(object sender, EventArgs e, string csvParams)
{
	try
	{
		Button b = (Button)sender;
		MessageBox.Show(string.Format("{0} --> {1}", b.Name, csvParams), string.Format("BtnOpenShipConfigFile_Click"),
						MessageBoxButtons.OK, MessageBoxIcon.Information);
	}
	catch (Exception ex)
	{
		MessageBox.Show(string.Format("{0}", ex.Message), string.Format("BtnOpenShipConfigFile_Click"),
						MessageBoxButtons.OK, MessageBoxIcon.Error);
	}
}
Altra doc su questa lambda expression (EventHandler with custom arguments [1])

Cambio Stile

Cambiamento del colore

Cambiamento di colore ad un pulsante:
        private string BindInfoVerServiceInstalled(string shipFullCode)
        {
            string strMsgErrorOut = string.Empty;
            Button btnVerDetected = this.Controls.Find(string.Format("{0}{1}", c_MultiCopy_BtnPrefix_ShipVerDetect, shipFullCode), true)
                                    .FirstOrDefault() as Button;
            if (btnVerDetected == null)
            {
                strMsgErrorOut = string.Format("Version control button for ship '{0}' NOT found.\r\n", shipFullCode);
                return strMsgErrorOut;
            }
            if (m_DictDataXMLShipInfoVersion.ContainsKey(shipFullCode))
            {
                btnVerDetected.Text = m_DictDataXMLShipInfoVersion[shipFullCode].ServiceVersion;
                if (m_DictDataXMLShipInfoVersion[shipFullCode].EmptyXMLDataFile)
                {
                    btnVerDetected.ForeColor = System.Drawing.Color.Red;
                }
                btnVerDetected.Enabled = true;
            }
            else
            {
                btnVerDetected.Text = "? V. Not F.";
                btnVerDetected.Enabled = false;
            }
 
            return strMsgErrorOut;
        }

Cambio del font

Cambio del font ad una label, aggiunta dinamicamente, con peso bold:

LblCompayName = new Label();
 
companyName = pair.Value.CompanyName;
LblCompayName.Text = companyName;
LblCompayName.Location = new Point(x, y);
LblCompayName.Font = new Font(LblCompayName.Font, FontStyle.Bold);
PnlShipListToUpdate.Controls.Add(LblCompayName);

Eseguire una applicazione esterna

Usare:
using System.Diagnostics;
Aprire il word:

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "WINWORD.EXE";
startInfo.Arguments = textBox1.Text;
Process.Start(startInfo);

Aprire esplora risorse su una determinata cartella:

private void BtnMultiCopy_OpenSourcePath_Click(object sender, EventArgs e)
{
	ProcessStartInfo startInfo = new ProcessStartInfo();
	startInfo.FileName = "Explorer.EXE";
	startInfo.Arguments = TxtSourcePath.Text.Trim();
	Process.Start(startInfo);
}

Aprire internet explorer su specifico indirizzo:

Process.Start("Chrome.exe", "http://www.bing.com/search?q=C%23+examples");
Process.Start("IExplore.exe", "www.microsoft.com")

Aprire Notepad o qualsiasi altro applicativo passandovi un parametro:

public static void OpenParametrizedApp(string fileExeName, string path)
        {
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = fileExeName;
            startInfo.Arguments = path.Trim();
            Process.Start(startInfo);
        }

Thread

Chiusura non riuscita

Può capitare, in casi in cui ci sono Threads oltre a quello della UI, che chiudendo l'applicazione il processo resti comunque attivo nella lista nel task manager. Ecco un modo per chiudere "bene" l'applicazione.

private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
{
	//if (e.CloseReason == CloseReason.UserClosing)
	//{
		AbortAllThreads();
	//}
	//
	System.Windows.Forms.Application.Exit();
	//Close(); // close main form and kill process
	return;
}
 
private void FrmMain_FormClosed(object sender, FormClosedEventArgs e)
{
	Process.GetCurrentProcess().Kill();
}

Timer

Auto chiusura di un form

Soluzione 1

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace WF_FormAutoclosing
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void BtnStartTimerToClose_Click(object sender, EventArgs e)
        {
            //DateTime now = DateTime.Now;  // avoid race
            //DateTime when = new DateTime(now.Year, now.Month, now.Day, 23, 0, 0);
            //if (now > when)
            //{ 
            //    when = when.AddDays(1);
            //}
            timer1.Interval = int.Parse(TxtSecondsIntervals.Text) * 1000;//(int)((when - now).TotalMilliseconds);
            timer1.Start();
        }
 
        private void timer1_Tick(object sender, EventArgs e)
        {
            int secondToStopClosing = 5;
            if (ChkStopForm.Checked)
            {
                LblEventStop.Text = "Closing";
                Thread.Sleep(secondToStopClosing * 1000);
                if (!ChkStopForm.Checked)
                { 
                    this.Close();
                }
                else
                {
                    LblEventStop.Text = "Abort";
                }
            }
            else
            {
                LblCountDown.Text = (int.Parse(LblCountDown.Text) + 1).ToString();
                LblEventStop.Text = "Ok";
            }
        }
    }
}

Form1.Designer.cs

namespace WF_FormAutoclosing
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;
 
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
 
        #region Windows Form Designer generated code
 
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.BtnStartFormTimerToClose = new System.Windows.Forms.Button();
            this.LblCountDown = new System.Windows.Forms.Label();
            this.timer1 = new System.Windows.Forms.Timer(this.components);
            this.ChkStopForm = new System.Windows.Forms.CheckBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.TxtSecondsIntervals = new System.Windows.Forms.TextBox();
            this.button1 = new System.Windows.Forms.Button();
            this.LblEventStop = new System.Windows.Forms.Label();
            this.ChkStopAutoClosing = new System.Windows.Forms.CheckBox();
            this.SuspendLayout();
            // 
            // BtnStartFormTimerToClose
            // 
            this.BtnStartFormTimerToClose.Location = new System.Drawing.Point(12, 141);
            this.BtnStartFormTimerToClose.Name = "BtnStartFormTimerToClose";
            this.BtnStartFormTimerToClose.Size = new System.Drawing.Size(106, 23);
            this.BtnStartFormTimerToClose.TabIndex = 0;
            this.BtnStartFormTimerToClose.Text = "Start by Form Timer";
            this.BtnStartFormTimerToClose.UseVisualStyleBackColor = true;
            this.BtnStartFormTimerToClose.Click += new System.EventHandler(this.BtnStartTimerToClose_Click);
            // 
            // LblCountDown
            // 
            this.LblCountDown.AutoSize = true;
            this.LblCountDown.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.LblCountDown.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.LblCountDown.Location = new System.Drawing.Point(124, 31);
            this.LblCountDown.Name = "LblCountDown";
            this.LblCountDown.Size = new System.Drawing.Size(25, 25);
            this.LblCountDown.TabIndex = 1;
            this.LblCountDown.Text = "0";
            // 
            // timer1
            // 
            this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
            // 
            // ChkStopForm
            // 
            this.ChkStopForm.AutoSize = true;
            this.ChkStopForm.Location = new System.Drawing.Point(194, 39);
            this.ChkStopForm.Name = "ChkStopForm";
            this.ChkStopForm.Size = new System.Drawing.Size(78, 17);
            this.ChkStopForm.TabIndex = 2;
            this.ChkStopForm.Text = "Close From";
            this.ChkStopForm.UseVisualStyleBackColor = true;
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label1.Location = new System.Drawing.Point(63, 35);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(55, 20);
            this.label1.TabIndex = 3;
            this.label1.Text = "Steps:";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label2.Location = new System.Drawing.Point(12, 74);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(76, 20);
            this.label2.TabIndex = 4;
            this.label2.Text = "Seconds:";
            // 
            // TxtSecondsIntervals
            // 
            this.TxtSecondsIntervals.Location = new System.Drawing.Point(95, 73);
            this.TxtSecondsIntervals.Name = "TxtSecondsIntervals";
            this.TxtSecondsIntervals.Size = new System.Drawing.Size(38, 20);
            this.TxtSecondsIntervals.TabIndex = 5;
            this.TxtSecondsIntervals.Text = "1";
            this.TxtSecondsIntervals.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(143, 140);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 6;
            this.button1.Text = "button1";
            this.button1.UseVisualStyleBackColor = true;
            // 
            // LblEventStop
            // 
            this.LblEventStop.AutoSize = true;
            this.LblEventStop.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.LblEventStop.Location = new System.Drawing.Point(83, 189);
            this.LblEventStop.Name = "LblEventStop";
            this.LblEventStop.Size = new System.Drawing.Size(21, 15);
            this.LblEventStop.TabIndex = 7;
            this.LblEventStop.Text = "ok";
            // 
            // ChkStopAutoClosing
            // 
            this.ChkStopAutoClosing.AutoSize = true;
            this.ChkStopAutoClosing.Location = new System.Drawing.Point(194, 186);
            this.ChkStopAutoClosing.Name = "ChkStopAutoClosing";
            this.ChkStopAutoClosing.Size = new System.Drawing.Size(85, 17);
            this.ChkStopAutoClosing.TabIndex = 8;
            this.ChkStopAutoClosing.Text = "Stop Closing";
            this.ChkStopAutoClosing.UseVisualStyleBackColor = true;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 262);
            this.Controls.Add(this.ChkStopAutoClosing);
            this.Controls.Add(this.LblEventStop);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.TxtSecondsIntervals);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.ChkStopForm);
            this.Controls.Add(this.LblCountDown);
            this.Controls.Add(this.BtnStartFormTimerToClose);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);
            this.PerformLayout();
 
        }
 
        #endregion
 
        private System.Windows.Forms.Button BtnStartFormTimerToClose;
        private System.Windows.Forms.Label LblCountDown;
        private System.Windows.Forms.Timer timer1;
        private System.Windows.Forms.CheckBox ChkStopForm;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.TextBox TxtSecondsIntervals;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Label LblEventStop;
        private System.Windows.Forms.CheckBox ChkStopAutoClosing;
    }
}

Mappa e Links


C# | Windows Form


Visual Studio


Parole chiave:Close, kill, windows form

Author