Drag und Drop innerhalb eines TreeViews

  • im Beispiel wird eine TreeNode innerhalb des TreeViews verschoben
  • als erstes ist das Ereignis ItemDrag zu behandeln:
private void TreeView1_ItemDrag(object sender, ItemDragEventArgs e)
{
    TreeView tv = sender as TreeView;

    if (tv != null)
    {
        if (tv.SelectedNode != null)
        {
            tv.DoDragDrop(tv.SelectedNode, DragDropEffects.Copy);
        }
    }
}
  • beim TreeView muss die Eigenschaft AllowDrop = True gesetzt sein
  • zusätzlich sind die Ereignisse DragOver und DragDrop zu behandeln:
private void TreeView1_DragOver(object sender, DragEventArgs e)
{
    e.Effect = DragDropEffects.None;

    // Quellnode
    TreeNode tns = e.Data.GetData(typeof(TreeNode)) as TreeNode;
    // akt. Zielnode unter dem Mauspfeil
    TreeNode tnd = TreeView1.GetNodeAt(TreeView1.PointToClient(new Point(e.X, e.Y)));

    if ((tns != null) && (tnd != null))
    {
        // hier im Beispiel die Verschiebung nur zulassen, wenn ChildNodes (Level == 1)
        // auf andere Parent-/Rootnodes (Level == 0) gezogen werden.
        if ((TreeView1.SelectedNode.Level == 1) && (tnd.Level == 0) && (tnd != tns.Parent))
        {
            e.Effect = DragDropEffects.Copy;
        }
    }
}

private void TreeView1_DragDrop(object sender, DragEventArgs e)
{
    // Quellnode
    TreeNode tns = e.Data.GetData(typeof(TreeNode)) as TreeNode;
    // akt. Zielnode unter dem Mauspfeil
    TreeNode tnd = TreeView1.GetNodeAt(TreeView1.PointToClient(new Point(e.X, e.Y)));

    if ((tns != null) && (tnd != null))
    {
        // neue TreeNode aus Clone der Quellnode erstellen
        TreeNode tnnew = (TreeNode)tns.Clone();
        tnd.Nodes.Add(tnnew);
        tnd.Expand();

        // alte Quell-TreeNode entfernen
        TreeNode cat = tns.Parent;
        cat.Nodes.Remove(tns);
    }
}

[C#][OleDB] Daten aus MSAccess in einem DataGridView darstellen

string sOleConnStr = string.Empty;
string sMDBFile = @"c:\Test.mdb";
string sUser = "user";
string sPassword = "password";
string sSQL = "SELECT * FROM table";

if (sMDBFile.Contains(".mdb"))
{
    sOleConnStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sMDBFile + ";User ID=" + sUser + ";Jet OLEDB:Database Password=" + sPassword;
}
else
    if (sMDBFile.Contains(".accdb"))
    {
        sOleConnStr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sMDBFile + ";User ID=" + sUser + ";Jet OLEDB:Database Password=" + sPassword;
    }

if (string.IsNullOrEmpty(sOleConnStr))
{
    MessageBox.Show("Sie haben eine nicht unterstützte MS Access Datenbankdatei ausgewählt.", AssemblyInfo.AssemblyProduct, MessageBoxButtons.OK, MessageBoxIcon.Warning);
    return;
}

OleDbConnection olecon = null;
OleDbDataReader olereader = null;

try
{
    olecon = new OleDbConnection(sOleConnStr);
    olecon.Open();

    OleDbCommand cmd = new OleDbCommand(sSQL, olecon);
    olereader = cmd.ExecuteReader();

    BindingSource bSource = new BindingSource();
    bSource.DataSource = olereader;

    // Datagridview auf einem Formular zum anzeigen der Daten
    dgvData.DataSource = bSource;
}
catch (Exception eole)
{
    MessageBox.Show(eole.Message, AssemblyInfo.AssemblyProduct, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
    // aufräumen
    if (olereader != null) olereader.Close();
    if (olecon != null) olecon.Close();
}

[OleDB] Tabellen einer MSAccess Datenbank auslesen

string sOleConnStr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\Test.accdb;User ID=;Jet OLEDB:Database Password=";

OleDbConnection olecon = new OleDbConnection(sOleConnStr);
olecon.Open();

DataTable dbSchemaTable = olecon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });

foreach (DataRow row in dbSchemaTable.Rows)
{
    Console.WriteLine(row["TABLE_NAME"].ToString());
}

[C#] Farbmodelle umwandeln (HSV, RGB)

using System;
using System.Drawing;

/// <summary>
/// freeware helper class for converting color schemes
/// (W) 2011 by admin of codezentrale.6x.to
/// </summary>
public static class ColorConvert
{
    public struct HSV
    {
        /// <summary>
        /// Hue, Farbton [0.0° .. 360.0°]
        /// </summary>
        public double hue;
        /// <summary>
        /// Saturation, Sättigung [0.0 .. 1.0]
        /// </summary>
        public double saturation;
        /// <summary>
        /// Value, Helligkeit [0.0 .. 1.0]
        /// </summary>
        public double value;

        public HSV(double h, double s, double v)
        {
            hue = h;
            saturation = s;
            value = v;
        }
    }
    public struct RGB
    {
        /// <summary>
        /// red, Rot [0 .. 255]
        /// </summary>
        public int red;
        /// <summary>
        /// green, Grün [0 .. 255]
        /// </summary>
        public int green;
        /// <summary>
        /// blue, Blau [0 .. 255]
        /// </summary>
        public int blue;

        public RGB(int r, int g, int b)
        {
            red = r;
            green = g;
            blue = b;
        }
    }
    /// <summary>
    /// converts Color to HSV
    /// </summary>
    /// <param name="c">Color</param>
    /// <returns>HSV struct</returns>
    public static HSV ColorToHSV(Color c)
    {
        int max = Math.Max(c.R, Math.Max(c.G, c.B));
        int min = Math.Min(c.R, Math.Min(c.G, c.B));

        double h = c.GetHue();
        double s = (max == 0) ? 0.0 : 1.0 - (1.0 * (double)min / (double)max);
        double v = (double)max / 255.0;

        return new HSV(h, s, v);
    }
    /// <summary>
    /// converts HSV to Color
    /// </summary>
    /// <param name="hsv">HSV struct to convert</param>
    /// <returns>Color</returns>
    public static Color HSVToColor(HSV hsv)
    {
        Color c = Color.Black;

        int hi = (int)(Math.Floor(hsv.hue / 60.0)) % 6;
        double f = hsv.hue / 60.0 - Math.Floor(hsv.hue / 60.0);

        hsv.value = hsv.value * 255.0;

        int v = (int)hsv.value;
        int p = (int)(hsv.value * (1.0 - hsv.saturation));
        int q = (int)(hsv.value * (1.0 - f * hsv.saturation));
        int t = (int)(hsv.value * (1.0 - (1.0 - f) * hsv.saturation));

        switch (hi)
        {
            case 0: c = Color.FromArgb(255, v, t, p); break;
            case 1: c = Color.FromArgb(255, q, v, p); break;
            case 2: c = Color.FromArgb(255, p, v, t); break;
            case 3: c = Color.FromArgb(255, p, q, v); break;
            case 4: c = Color.FromArgb(255, t, p, v); break;
            default: c = Color.FromArgb(255, v, p, q); break;
        }

        return c;
    }
    /// <summary>
    /// converts Color to RGB
    /// </summary>
    /// <param name="c">Color</param>
    /// <returns>RGB struct</returns>
    public static RGB ColorToRGB(Color c)
    {
        return new RGB(c.R, c.G, c.B);
    }
    /// <summary>
    /// converts RGB to Color
    /// </summary>
    /// <param name="rgb">RGB struct</param>
    /// <returns>Color</returns>
    public static Color RGBToColor(RGB rgb)
    {
        return Color.FromArgb(rgb.red, rgb.green, rgb.blue);
    }
}

[C#] Benutzung des Backgroundworker-Objektes

using System.Threading;

BackgroundWorker bw = new BackgroundWorker();

private void btnStartWorker_Click(object sender, EventArgs e)
{
    if (!bw.IsBusy)
    {
        bw.WorkerReportsProgress = true;
        bw.WorkerSupportsCancellation = true;
        bw.DoWork += new DoWorkEventHandler(worker_DoWork);
        bw.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
        bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
        bw.RunWorkerAsync();

        btnStartWorker.Text = "Abbruch";
        this.Cursor = Cursors.Wait;
    }
    else
    {
        bw.CancelAsync();
    }
}

private void worker_DoWork(object sender, DoWorkEventArgs e)
{
    for (int i = 0; i < 10000; i++)
    {
        if (bw.CancellationPending)
        {
            e.Cancel = true;
            return;
        }

        // irgendwas rechnen
        int iPc = (int)(((double)i / 10000.0) * 100);

        // Fortschrittswert melden
        bw.ReportProgress(iPc);

        // BackgroundWorker schlafen schicken
        Thread.Sleep(100);
    }
}

private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
	this.BeginInvoke((MethodInvoker)delegate
	{
		pbProgressBar.Value = e.ProgressPercentage;
	});
}

private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    // hier Dinge erledigen, die auftreten, wenn Backgroundworker fertig ist
    this.Cursor = Cursors.Arrow;
    
    if (e.Cancelled)
    {
        btnStartWorker.Text = "Start";
    }
    
    if (e.Error != null)
    {
        MessageBox.Show(e.Error.Message);
    }
}

[C#][ODBC] Daten aus einer Tabelle in einem DataGridView anzeigen

// dgvGrid == DataGridView auf dem Formular
private void btnOpen_Click(object sender, EventArgs e)
{
    OdbcConnection conn = null;
    OdbcDataReader reader = null;

    try
    {
        // Verbindung herstellen
        conn = new OdbcConnection(@"dsn=MyDSN;UID=user;PWD=password;");
        conn.Open();

        // SQL-Kommando abschicken
        OdbcCommand cmd = new OdbcCommand("SELECT Names FROM MyTable", conn);
        // Daten einlesen
        reader = cmd.ExecuteReader();

        // Bindingsource erstellen
        BindingSource bSource = new BindingSource();
        // Reader an Source binden
        bSource.DataSource = reader;

        // Source an DataGridView übergeben
        dgvData.DataSource = bSource;
    }
    catch (Exception)
    {
    }
    finally
    {
        // aufräumen
        if (reader != null) reader.Close();
        if (conn != null) conn.Close();
    }
}
  • Weiterführender Link: Link

[ODBC] Zugriff auf SQL Server

using System.Data;
using System.Data.Odbc;

// Username
string sUID = @"user";
// Passwort
string sPW = @"password";
// Server
string sServer = @"127.0.0.1";
// Database
string sDB = @"DatabaseName";
// SQL-String
string sSql = @"SELECT Names FROM MyTable";

OdbcConnection conn = null;
OdbcDataReader reader = null;

try
{
    // Verbindung herstellen
    conn = new OdbcConnection("Driver={SQL Server};Server=" + sServer + ";UID=" + sUID + ";PWD=" + sPW + ";Database=" + sDB + ";");
    conn.Open();

    // SQL-Kommando abschicken
    OdbcCommand cmd = new OdbcCommand(sSql, conn);
    reader = cmd.ExecuteReader();

    // Daten auslesen und anzeigen
    while (reader.Read())
    {
        Console.WriteLine(reader["Names"]);
    }
}
catch (Exception ex)
{
    Console.WriteLine("Error: " + ex);
}
finally
{
    // aufräumen
    if (reader != null) reader.Close();
    if (conn != null) conn.Close();
}