Teme64 215 Veteran Poster

Passing data between forms has been asked many times. The easiest way is to use a custom property to pass data or a reference to control to hold the data.

public partial class Form3 : Form // This is your Form1
{
    public Form3()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 oForm; // This is your Open & Load Excel form

        oForm = new Form2();
        oForm.ExcelView = this.dataGridView1; // Pass this form's DGV to be filled
        oForm.ShowDialog();
        oForm = null; // Dispose Excel form
    }
}

// This is your Form2

    public partial class Form2 : Form
{
    public DataGridView ExcelView { get; set; }

    public Form2()
    {
        InitializeComponent();
    }

    // Add code to open Excel file and load data to ExcelView

    private void button1_Click(object sender, EventArgs e)
    {
        this.Close(); // Return to calling form
    }
}

I hope this helps.

Teme @ windevblog.blogspot.com

Teme64 215 Veteran Poster

I have been a Windows user since version 2.0 and I have never seen "checking for a solution to the problem" to provide any solution. I guess that is a feature, not any actual problem solver ;)

Teme64 215 Veteran Poster

JamesCherrill is correct about O(N).

Worst case happens when a binary tree with N nodes is fully biased to left (or right). In your code, null check is always same, that is, it takes a constant time and therefore recursive call to rSize(node.right) takes a constant time. Recursive call rSize(node.left) (or rSize(node.right)) traverses to the "bottom node" i.e. that makes it O(N) to reach the leaf node. You can ignore constant values mentioned above because they are just some constant value c and O(cN) is equal to O(N).

The best case with N nodes is not O(1). You have the "fastest" binary search tree when N nodes are evenly distributed. That means that the height of the binary search three is as small as possible. In this case, to traverse from root node to any leaf node takes O(log N) time because O(log N) is also the height of the binary tree.

HTH

Teme64 215 Veteran Poster

Why you use the second combobox???

Simply

    string[] lineOfContents = File.ReadAllLines(comboBox1.Text);
    this.richTextBox1.Lines = lineOfContents;

or

    // Now you have a file content in a single string
    string lineOfContents = File.ReadAllText(comboBox1.Text);
    // Split string to tokens
    string[] tokens = lineOfContents.Split(',');
    // Now tokens is an array of all strings from the file w/o commas
    this.richTextBox1.Lines = tokens;

I may have missed some point but I hope this helps.

Teme64 215 Veteran Poster

You have done keyboard hook with SetWindowsHookEx() API call, right?
When your keyboard delegate gets keycode for S-key, it replaces it with D-key's keycode (for some reason I do not understand), right?
You do know that Ctrl+S sends two separate keycodes, one for Ctrl-key and one for S-key, right?
Now if you press Ctrl+S, your keyboard delegate handles Ctrl-key and then replaces S-key's code with D-key's code, right?
Now if you press Ctrl+S in the Notepad it gets Ctrl+D and Ctrl+D does not save the document, right?

You solve this problem by not replacing S-key with D-key in your keyboard delegate. Right?

HTH

Teme64 215 Veteran Poster

The origin of the problem is the Random object itself. Suppose our Random object outputs only 0's and 1's (just like tossing a coin gives only heads and tails). Ideally Random object would somehow output a sequence that meets the conditions

  1. probability of 0 is equal to the probability of 1 ("fair coin")
  2. given any output sequence of 0's and 1's the probability of getting next a '0' is equal to the probability of getting a '1'. That is, knowing any number of previously outputted 0's and 1's does not change the predictability of the next output. On the other words, Random object does neither "remember" what the previous output was nor does it use any previous output to generate next output. This would make Random object stateless (like a coin).

So, how does this Random object "produce" these random 0's and 1's? The answer is: it does not produce anything random. It produces pseudo-random 0's and 1's.

The computers are deterministic like they should be. Algorithms ("computer programs") are deterministic by definition. This is why our Random object is also deterministic and not "random" in statistical sense. When someone wrote the actual code for our Random object, he or she chose an algorith that "mimics" randomness i.e. the outputted values have as uniform distribution as possible and knowing any number of previously outputted values keeps the predictability of the next output as small as possible.

This applies to C#, Java or any programming language which has some sort …

Teme64 215 Veteran Poster

When tossing a coin we can (and will) make following assumptions:
1. the result will allways only be tails or heads
2. the coin is fair i.e. the probability of tails is the same as heads, P(T) <=> P(H)
3. the coin tossing is stateless operation i.e. the coin does not and can not "remember" last result
4. from the previous assumptions follows that given any sequence of coin tossing results, the next toss has the probability P(T) <=> P(H)

Let's say that player A chooses a sequence T, T and T. Tossing this sequence has, according classic probability theory, likelihood P(T) * P(T) * P(T), (or 1/2 * 1/2 * 1/2 = 1/(2^3) = 1/8 because P(T) <=> P(H) and the coin is fair as stated above).

Using the given strategy player B chooses a sequence: H, T and T. Tossing this sequence has the probability
P(H) * P(T) * P(T) or 1/2 * 1/2 * 1/2 = 1/(2^3) = 1/8 which is exactly the same as the probability of the player A's sequence.

From this follows that
1. using the strategy, how to choose the sequence, does not increase the probability of that sequence
2. to always choose second does not help i.e. increase the probability of the sequence

Am I right?

Teme64 215 Veteran Poster

First you have to extract the embedded resourse itself to a some temporary file. Then you read and unzip temporary file to the final file.

I grabbed these code snippets from a setup program I wrote. It shows how to output an embedded resource and how to deflate (unzip) a zipped file. The embedded resource has name "packet" so change it to match whatever names you are using.

    // Namespaces for file streams and compressed streams handling
    using System.IO;
    using System.IO.Compression;

    public void extractResource(string outputFileName)
    {
        // Extract a resource named "packet" to a file
        File.WriteAllBytes(outputFileName, Properties.Resources.packet);
    }

    public void extractFile(string fileName, FileStream defStream)
    {
        FileStream fs;
        DeflateStream fromStream;
        byte[] buffer;
        int bufSize;
        int byteCount;

        bufSize = 4096;
        buffer = new byte[bufSize];
        // Deflate ("unzip") a filestream to a file
        try
        {
            fromStream = new DeflateStream(defStream, CompressionMode.Decompress, true);  // Deflate
            fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None);
            byteCount = 0;
            while (byteCount >= 0)
            {
                byteCount = fromStream.Read(buffer, 0, bufSize); // Read and decompress data from the stream
                if (byteCount > 0)
                {
                    fs.Write(buffer, 0, byteCount); // Write data to a new file
                }
                else
                {
                    byteCount = -1;
                }
            }
            fs.Close();
            fs.Dispose();
        }
        catch
        {
        }
    }

    public void extractZippedFile(string outputFileName)
    {
        FileStream fs;

        try
        {
            extractResource(@"temp.fil"); // Extract resource to a temp file
            fs = new FileStream(@"temp.fil", FileMode.Open, FileAccess.Read, FileShare.None); // Open temp file for reading
            extractFile(outputFileName, fs); // Decompress temp file to a new file
        }
        catch
        {
        }
        finally
        {
            fs.Close();
            fs = null;
        }
    }

HTH

Teme64 215 Veteran Poster

This can be done with a simple Excel formula so you don't need any VBA scripting for this.

First you have to figure out how the column number is related to input value (1-5). I used MOD() function to find out when a row "matches" the input value. Cell range (A8:AD8) starts from the column 1 so I calculate MOD(1; <input value>). With the given input range 1-5 column numbers which should have SUM() formula are MOD(<column num>; <input value>) = 1 for input values 2-5. Input value 1 is a "special case" so I used a separate test if it is 1.

Some formulas you need are:
- COLUMN() which gives the column number of the current column
- MOD() to calculate modulus
- IF() to output sum value or "-"

I try to attach a few pictures how the final result looks and how the formulas look.

But here is the formula:
- in the cell A8 (actually every cell in the range (A8:AD60): =IF(AND($A$5 >= 1; $A$5 <= 5); (IF(OR($A$5 = 1; MOD(COLUMN(); $A$5) = 1); SUM($O$2:$T$2); "-")); "")
the first (outer) IF() formula is just for testing that the input value is valid. The second (inner) IF() formula does the actual testing if this column should have a SUM() or "-". I used absolute references in the SUM() formula and filled cell range (O2:T2) with values 1, 2, 3, ..., 6.

I changed the cell range (O17:T17) to (O2:T2) because cell …

Teme64 215 Veteran Poster

I've tried deleting everything in the release folder, to no avail

Have you deleted also app.config file from your source code/project folder?

Teme64 215 Veteran Poster

Setting panel.BackColor = Color.Transparent does not work like you already noticed. The trick is to use transparency of the form as ddanbe hinted.

Here's two overlapping panels on a form. First one is a green square which is drawn behind the "transparent" panel. Second panel is the "transparent" panel. I set its BackColor to Red which will be the transparent color.

The last line sets form's TransparencyKey to Red color. This turns also the second panel transparent.

    // A green panel ("background panel") which gets behind the invisible panel
    panel2.Location = new System.Drawing.Point(50, 50);
    panel2.Size = new Size(100, 100);
    panel2.BackColor = Color.Green;
    panel2.ForeColor = Color.Black;
    panel2.Visible = true;
    MessageBox.Show("Press Ok to continue"); // Just to pause between steps

    // Invisible panel which covers the smaller green panel
    panel1.Location = new System.Drawing.Point(0, 0);
    panel1.Size = new Size(200, 200);
    panel1.BackColor = Color.Red; // Red is used as a "transparent" color
    panel1.ForeColor = Color.Black;
    panel1.Visible = true;
    MessageBox.Show("Press Ok to continue"); // Just to pause between steps

    // Set the *forms* TransparencyKey property to Red
    this.TransparencyKey = Color.Red;

HTH

Teme64 215 Veteran Poster

ExecuteScalar() method is the correct choice. However returning identity value is not done correctly.
Here's a rewritten code. I also replaced questionmarks with parameter names.

    private bool EventLog(int userNumber, int userID, UserEventTypes eventType, out int recordID)
    {
        string ConnectionString;
        object scalarObject; // Identity value to be returned

        // Return '0' if something goes wrong
        recordID = 0;

        ConnectionString = @"Server=ANGELINA\SQLEXPRESS;Database=BlogTest;User Id=xxxxxxxx;Password=yyyyyyyy";

        SqlConnection Conn = new SqlConnection(ConnectionString);

        // Question marks are replaced with parameter names
        SqlCommand EventCommand = new SqlCommand("INSERT INTO EventLog " +
        " (UserNumber, UserID, EventType, DateTime) Values(@UserNumber,@UserID,@EventType,@DateTime);" +
        "SELECT @@IDENTITY AS 'EventRecordID';", Conn);
        // @@IDENTITY function returns last identity value which is assigned to EventRecordID name

        EventCommand.Parameters.Add("@UserNumber", SqlDbType.Int).Value = userNumber;
        EventCommand.Parameters.Add("@UserID", SqlDbType.NVarChar, 50).Value = userID.ToString();
        EventCommand.Parameters.Add("@EventType", SqlDbType.NVarChar, 50).Value = eventType.ToString();
        EventCommand.Parameters.Add("@DateTime", SqlDbType.DateTime).Value = DateTime.Now;
        try
        {
            Conn.Open();
            // ExecuteScalar() returns an object so assign it to a variable which is of type object
            scalarObject = EventCommand.ExecuteScalar();
            // If the returned object is of integer type convert it to an integer
            // You could/should check that scalarObject variable is not null value
            if (int.TryParse(scalarObject.ToString(), out recordID))
            {
                // Now recordID has identity field's value which will be returned. The 
                // messagebox is just for debugging
                MessageBox.Show("Inserted record with ID value: " + recordID.ToString());
            }
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            // Finally close the connection
            if (Conn.State != ConnectionState.Closed)
            {
                Conn.Close();
            }
            // If you don't re-use connection and command objects you should dispose them
            EventCommand = null;
            Conn = null;
        }
        return true; // …
Teme64 215 Veteran Poster

Here is a one solution

    TimeSpan timeSpan;
    string timeStr;
    int totalHours;
    int totalMinutes;

    // 1 day, 6 hrs, 32 mins, 0 secs, 0 msecs
    timeSpan = new TimeSpan(1, 6, 32, 0, 0); 
    // Get hours and minutes
    // TotalHours is of type double, cast it to integer (truncate to integer)
    totalHours = (int)timeSpan.TotalHours;
    // Remove totalHours hours from the timeSpan to avoid rounding error
    timeSpan = timeSpan.Subtract(new TimeSpan(totalHours, 0, 0)); // hours, 0 mins, 0 secs
    // TotalMinutes is of type double, cast it to integer (truncate to integer)
    totalMinutes = (int)timeSpan.TotalMinutes;
    // Convert to a string
    timeStr = string.Format("{0:d2}:{1:d2}", totalHours, totalMinutes);
    // Display result
    MessageBox.Show(timeStr);

Notice that I created timespan with explicit seconds and milliseconds. You may have got this one wrong. I subtracted (total) hours from the timespan. After that it has only minutes (and seconds and mseconds) left. To format with two digits you can use for example "d2".

HTH

Teme64 215 Veteran Poster

Before doing any coding you have to consider what will be the environment where your application will be used:
- is Office (i.e. Excel) installed
- is Office (i.e. Excel) installed with .NET programming support
- is reading Excel file(s) all you really need
- is there a possibility you will need to "do more Excel" like create Excel files, format cells etc.

Assuming all you need is to read Excel file(s), there are at least two ways to do it. First one is to threat Excel file as a database which has multiple tables (Excel sheets). The second one is to handle Excel file (almost) like you would do in the Excel application. The latter one requires that you do have Excel installed. The former one is simpler and it works weather Excel is installed or not. Both approaches do require some data access components which you may (or may not) have installed.

I wrote examples for both cases. I wrote them first with CSharp and then converted to VB.NET so there may be some oddities in these examples. I used VS Express 2010 version for programming with 64-bit version of Windows 7 and .NET 4.0 and I had 32-bit Office 2010 installed. For testing I used a very short and simple Excel file in 2010's native XLSX-format. Examples should work with newer Office version too. For the older Excel file formats you have to change a bit the connectionstring in the first example (OleDb-version).

Teme64 215 Veteran Poster

I think that Application.ExecutablePath should also work.

ddanbe commented: Indeed! :) +15
Teme64 215 Veteran Poster

The easiest way to get system information is through Windows Management Instrumentation (WMI). There's a Win32_UserAccount class which provides information about user accounts including SID and Name properties which you asked for. I've been using WMI Code Creator utility to create "code skeletons" and then modified the code to match what I've needed. You can download WMI Code Creator from here. There are other WMI utilities too but I have found this one easy to use and it generates code for C#, VB.Net and VBScript.

Here's a sample code which gets user accounts' SID and name:

    Imports System
    Imports System.Management
    Imports System.Windows.Forms

    ' Code created with WMI Code Creator
    ' https://www.microsoft.com/en-us/download/details.aspx?id=8572

    Namespace WMISample

        Public Class MyWMIQuery

            Public Overloads Shared Function Main() As Integer

                Try
                    Dim searcher As New ManagementObjectSearcher("root\CIMV2", "SELECT * FROM Win32_UserAccount") 

                    For Each queryObj As ManagementObject in searcher.Get()

                        Console.WriteLine("-----------------------------------")
                        Console.WriteLine("Win32_UserAccount instance")
                        Console.WriteLine("-----------------------------------")
                        Console.WriteLine("Name: {0}", queryObj("Name"))
                        Console.WriteLine("SID: {0}", queryObj("SID"))
                    Next
                Catch err As ManagementException
                    MessageBox.Show("An error occurred while querying for WMI data: " & err.Message)
                End Try
            End Function
        End Class
    End Namespace

If you are not familiar with WMI, search Microsoft's TechNet and MSDN for more information about WMI and how you can use it (and why you should use it).

HTH

Teme64 215 Veteran Poster

Here's another solution. It has some advantages:
- user can open context menu over any cell in DGV
- you get both column index and row index if you need to remove/add rows too

Context menu creation is inside button click handler but probably should be in the code which initializes DGV.

    private void button4_Click(object sender, EventArgs e)
    {
        ToolStripMenuItem newItem;

        // Create a context menu
        newItem = new ToolStripMenuItem();
        newItem.Text = "Remove";
        newItem.Name = "contextRemove";
        // contextMenuItem_Click handles menu click
        newItem.Click += new EventHandler(contextMenuItem_Click);
        contextMenuStrip1.Items.Add(newItem);

        newItem = new ToolStripMenuItem();
        newItem.Text = "Add";
        newItem.Name = "contextAdd";
        // contextMenuItem_Click handles menu click
        newItem.Click += new EventHandler(contextMenuItem_Click);
        contextMenuStrip1.Items.Add(newItem);

        // Attach context menu to the DGV
        dataGridView1.ContextMenuStrip = contextMenuStrip1;
        // Add handler to capture context menu opening
        dataGridView1.MouseDown += new MouseEventHandler(dataGridView1_MouseDown);
    }

    // Global variable to hold mouse position coordinates
    internal Point contextMenuClickPosition;

    private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
    {
        // Context menu opens with right mouse button
        if (e.Button == System.Windows.Forms.MouseButtons.Right)
        {
            // User opened context menu, save this (x,y) position
            contextMenuClickPosition = e.Location;
        }   
    }

    private void contextMenuItem_Click(object sender, EventArgs e)
    {
        DataGridView.HitTestInfo hitPosition;
        Point cellIndex;

        // User has opened context menu. Use DGV's HitTest method to find 
        // the cell where user opened menu i.e. row index and column index.
        // Here the saved mouse coordinates are needed
        hitPosition = dataGridView1.HitTest(contextMenuClickPosition.X, contextMenuClickPosition.Y);
        // User has to open context menu over a cell
        if (hitPosition.Type == DataGridViewHitTestType.Cell)
        {
            // Now we know row and column indices
            // Notice …
Teme64 215 Veteran Poster

Rows and Columns are collections in datagridview control. Both collections have Clear method:

    dataGridView1.Rows.Clear();
    dataGridView1.Columns.Clear();

Now you should have an "empty" datagridview control.

HTH

Teme64 215 Veteran Poster

One solution would be to use FileSystemWatcher class which would raise an event when the folder content has changed. After that you would scan the files.

BackgroundWorker should be fine for scanning the folder. I didn't test this idea but you could raise ProgressChanged event from your BackgroundWorker thread and handle that event in your UI thread (i.e. main form or similar). Event handler would just call Application.DoEvents() to keep UI thread's "message pump" processing and that would avoid "Not Responding" message.

If this didn't help you should post your code. Especially how you trigger folder scanning every tenth second, the code that actually does folder scanning and all the other code related to BackgroundWorker.

HTH

Teme64 215 Veteran Poster

StartInfo class has Arguments property where you can pass parameters. In your case it is the name of the file you want to open.

Add following line after line 5
.StartInfo.Arguments = "O:\Revenue Management\RM -- Specialty Select Brands\Analytics\Tableau Extracts\Pace\SSB_FR_FUTURE_PACE_LOC.twbx"

Now "O:\Revenue Management\RM -- Specialty Select Brands\Analytics\Tableau Extracts\Pace\SSB_FR_FUTURE_PACE_LOC.twbx" is passed as an argument to "tableau.exe" application.

HTH

Teme64 215 Veteran Poster

Line 14 should be: Dim raw_col As Integer = 6 'column # of raw data

Column ordinals are zero-based so indices are as follows
- id = 0
- doc_name = 1
- created_by = 2
- date_uploaded = 3
- client_name = 4
- description = 5
- raw_file (mediumblob) = 6
- file_format = 7
Your code read the file_format column and gave the error.

HTH

Teme64 215 Veteran Poster

First

but I thought with the qualifier of FileSystemWatcher

FileSystemWatcher is a type, not a qualifier. When you use foreach loop, your loop variable's type has to match with the collection item's type. So when you loop this.Controls collection you're dealing with a type Control.

Here's a sample how to loop all controls of the type 'Button' in your form:

    foreach (Control oneControl in this.Controls)
    {
         if (oneControl.GetType() == typeof(Button))
         {
            // It's a button
         }
    }

Objects of the type FileSystemWatcher are not controls and you won't find them in the form's Controls collection. Since you create FileSystemWatcher objects in your code you can save them in a way you can access them later.

The easiest solution that came in to my mind is to use a List collection. Here's the code with comments:

    // This list holds a reference to all watchers that are created
    private List<FileSystemWatcher> listOfFileSystemWatchers = new List<FileSystemWatcher>();

    // Event handler which is called when a change occurs
    private void myWatcher_Changed(object sender, FileSystemEventArgs e)
    {
        // Here we do something
        MessageBox.Show(e.FullPath + " changed");
    }

    // I used a button to create new FileSystemWatchers. You may use some other way
    private void button3_Click(object sender, EventArgs e)
    {
        FileSystemWatcher newFSysWatcher;

        // Create a very basic FileSystemWatcher object
        newFSysWatcher = new FileSystemWatcher(@"D:\Temp", @"*.txt");
        newFSysWatcher.EnableRaisingEvents = true;
        newFSysWatcher.Changed += new FileSystemEventHandler(myWatcher_Changed);

        // Add watcher to the list to access it later
        listOfFileSystemWatchers.Add(newFSysWatcher);
    }

    // Second button calls Dispose methods for each …
zachattack05 commented: Thanks! +6
Teme64 215 Veteran Poster

I do not know any way to do it with pure .NET code. You have to use an API call instead. I used an example from http://www.pinvoke.net/default.aspx/user32.MoveWindow

I also added System.Diagnostics namespace to simplify code a bit. System.Runtime.InteropServices namespace is required to make API calls.

    using System.Diagnostics;
    using System.Runtime.InteropServices;


    // See http://www.pinvoke.net/default.aspx/user32.MoveWindow
    [DllImport("user32.dll", SetLastError = true)]
    internal static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);

    internal struct RECT
    {
        public int left;
        public int top;
        public int right;
        public int bottom;
    }

    private void button1_Click(object sender, EventArgs e)
    {

        System.Diagnostics.ProcessStartInfo startInfo; // Data for the process
        Process startedProc; // Created process object
        IntPtr hProc; // Handle to main window of the process
        RECT sizeRect; // Size information for the window

        startInfo = new System.Diagnostics.ProcessStartInfo();
        startInfo.FileName = "opera.exe";
        startInfo.Arguments = "http://google.com";

        // Get the new process object
        startedProc = Process.Start(startInfo);
        // Get the handle of it's window
        hProc = startedProc.MainWindowHandle;
        // Set the size of the window. Size and position information is stored in RECT structure
        sizeRect = new RECT();
        // Upper left corner
        sizeRect.top = 0;
        sizeRect.left = 0;
        // Width comes from the screen size
        sizeRect.right = Screen.PrimaryScreen.Bounds.Width;
        // Height is hardcoded in here. Value should be checked to be less or equal to Screen.PrimaryScreen.Bounds.Height
        sizeRect.bottom = 200; // 200 pixels

        // Resize the process window with the data collected above
        MoveWindow(hProc, sizeRect.top, sizeRect.left, sizeRect.right, sizeRect.bottom, true);
    }

Code has no error checking …

Teme64 215 Veteran Poster

ProcessStartInfo class has WindowStyle property:

System.Diagnostics.ProcessStartInfo startInfo;

startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.FileName = "opera.exe";
startInfo.Arguments = "http://google.com";
// Set WindowStyle property for the new process
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Maximized;

System.Diagnostics.Process.Start(startInfo);

HTH

Teme64 215 Veteran Poster

Here's a simple example how to create a custom autocomplete collection:

    ' Declare a collection
    public autoComp As AutoCompleteStringCollection

    ' Create a new collection instance
    autoComp = new AutoCompleteStringCollection()
    ' Or clear existing collection
    autoComp.Clear()

    ' Add your items to the collection
    autoComp.Add("first")
    autoComp.Add("fish")
    autoComp.Add("fast")

    ' Set these two properties for custom autocomplete to work
    textBox1.AutoCompleteMode = AutoCompleteMode.Suggest
    textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource

    ' Finally, use your autocomplete collection
    textBox1.AutoCompleteCustomSource = autoComp

I hope you get the idea...

HTH

Teme64 215 Veteran Poster

Hi Jez! That "1001" was a hardcoded id to db-table. In your example it was "0001" and I copied it wrong :)

Your code updates (decrases) stocksretail twice. First update is caused by For-Next loop which loops Items.Count times i.e. through all the records. Second loop is While acsdr.Read() which also loops all the records and contains the actual update.

If LVCart.Items contains the db id-values you want to update, drop the While acsdr.Read() part from your code. Array variable LVCart.Items(a) selects a single record and you update that single record.

So the code goes something like this:

    For a = 0 To LVCart.Items.Count - 1
      sql = "select * from ItemProduct  WHERE CODE = '" & LVCart.Items(a).ToString() & "'"
      Dim cmd = New OleDb.OleDbCommand(sql, conn)
      acsdr = cmd.ExecuteReader() ' Get a single record
      acsdr.Read() ' Get a single record
      Dim STOCKSWSRt As Integer = CInt(acsdr("numexpected")) ' Cast Object to Integer 

      sql = "UPDATE ItemProduct SET stocksretail = stocksretail - @pnumExpected WHERE CODE = '" & LVCart.Items(a).ToString() & "'" ' Named params
        cmd = New OleDbCommand(sql, conn)
        cmd.Parameters.AddWithValue("@pnumExpected", STOCKSWSRt)
        cmd.ExecuteNonQuery()
    Next 

HTH

Teme64 215 Veteran Poster

Your code is not messy :)

You are using positional parameters (?) so I would change cmd as follows:

Dim STOCKSWSRt As Integer = 24 ' Hardcoded value ("numexpected" from the db)

Sql = "UPDATE ItemProduct SET stocksretail = stocksretail - ? WHERE CODE = ?" ' Positional params
cmd = New OleDbCommand(Sql, conn)

cmd.Parameters.Add(STOCKSWSRt)
cmd.Parameters.Add("1002") ' Hardcoded value here too, should be LVCart.Items(a).Text
cmd.ExecuteNonQuery()

Or with named parameters:

Sql2 = "UPDATE ItemProduct SET stocksretail = stocksretail - @pstockretail WHERE CODE = @pCODE" ' Named params
cmd2 = New OleDbCommand(Sql2, conn)

cmd2.Parameters.AddWithValue("@pstockretail", STOCKSWSRt)
cmd2.Parameters.AddWithValue("@pCODE", "1002")
cmd2.ExecuteNonQuery()

HTH

Santanu.Das commented: Nice supportings +5
Teme64 215 Veteran Poster

Here's a more complete code. Initializing controls should be done only once and before you do anything else. I added private void InitForm() which handles initialization when the (main) form is created. I also made the "NO"-field to use a global variable, I think that's what you want.

So here's the code with a lot of comments :)

    public Form1()
    {
        InitializeComponent(); // This line is generated by Visual Studio, do not remove it!
        // 
        InitForm(); // Here's the call to form's custom initialization
    }

    // Class variable(s)
    private int subTitleLineNumber;

    /// <summary>
    /// Set up main form and controls. Initialize global/class variables
    /// </summary>
    private void InitForm()
    {
        // Customize datetimepicker control
        dateTimePicker1.Format = DateTimePickerFormat.Custom;
        dateTimePicker1.CustomFormat = "HH:mm:ss"; // Notice that mm has to be lower case for minutes
        dateTimePicker1.ShowUpDown = true;
        dateTimePicker1.Text = "00:00:00"; // Display "zero time". Remove this line if not needed

        // Customize listview control
        listView1.View = View.Details;
        // Add two columns first. Here column headers have an optional width
        // 
        listView1.Columns.Add("NO", 80);
        listView1.Columns.Add("Text", 250);

        // Richtextbox control. Just make sure it's empty
        richTextBox1.Clear();

        // Initialize variable(s)
        subTitleLineNumber = 0;
    }

    /// <summary>
    /// Button1 moves lines from the rt-box to listview i.e. updates listview
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void button1_Click(object sender, EventArgs e)
    {
        ListViewItem newLineObject;
        string[] newLineStrings = new string[2]; // For two columns!

        // Add data items for two columns from rt-box to listview control
        foreach (string line in richTextBox1.Lines)
        {
            subTitleLineNumber++; // Increment line …
Teme64 215 Veteran Poster

Here's an answer to "the other thing". Instead of NumericUpDown control you can customize DateTimePicker control

dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "HH:MM:ss";
dateTimePicker1.ShowUpDown = true;

And here's for the first part of the question

private void button1_Click(object sender, EventArgs e)
{
    listView1.View = View.Details;
    // Add two columns first. Here column headers have an optional width
    listView1.Columns.Add("NO", 80);
    listView1.Columns.Add("Text", 250);
    // Add data items for two columns to listview control
    for (int i = 0; i < richTextBox1.Lines.Length; i++)
    {
        ListViewItem lvi = new ListViewItem(i.ToString());
        lvi.SubItems.Add(richTextBox1.Lines[i]);
        listView1.Items.Add(lvi);
    }
}

HTH

Teme64 215 Veteran Poster

First, read Exception and Error Handling in Visual Basic
to understand the basics. After that you can start the actual coding with the help of Try...Catch...Finally Statement (Visual Basic)

HTH

Teme64 215 Veteran Poster

Maybe you should post your code.

Have you checked PDF Viewer SDK they are also offering?

HTH

Teme64 215 Veteran Poster

this code not work for me!

Your code does not work because
1) you collect all div-elements and
2) elementsByTagName[num].OuterHtml.Contains("URaP8 Kf Pf b-K b-K-Xb") can match with multiple div-elements

Some solutions could be
1) If HTML-element has an id-attribute, use that because it is unique in your web-page:
HtmlElement textBox = this.WebBrowser1.Document.GetElementById("Id for this element");

2) If the element has a name-attribute, try to use it:
if (elementsByTagName[num].Name == "Name of this element")

3) Instead of collection all the div-elements, try to narrow your search. For example, if your textbox is an input-element then get only page's input-tags:
HtmlElementCollection elementsByTagName = this.WebBrowser1.Document.Body.GetElementsByTagName("input");
and narrow results further with element's attributes:
if (elementsByTagName[num].GetAttribute("type") == "text")
Now you would get all the HTML-elements similar to <input type="text"></input>

HTH

Teme64 215 Veteran Poster

Do you design that database structure too or is it 'fixed'? I assume that you are having only multiple choise questions.

The database structure should be similar to this:

tbl_ECM_Questionnaire:
QuestionID  QuestionText    CorrectQuestionOptionID
1           "Why..."        2
2           "Where..."      1
3           "When...        2



tbl_ECM_QuestionnaireOptions:
QuestionID  QuestionOptionID    QuestionOptionText  AnswerValue
1           1                   "Because..."        "A"
1           2                   "Because..."        "B"
2           1                   "In..."             "A"
2           2                   "In..."             "B"
3           1                   "It was...          "A"
3           2                   "It was...          "B"

Table tbl_ECM_Questionnaire has the questions, each with an unique QuestionID, and a column for the correct answer option.

The second table tbl_ECM_QuestionnaireOptions has answer options. Table's unique key is the combination of the QuestionID and QuestionOptionID.

Tables are related in the following way:
1. QuestionID field makes a relation between a question and all the question's answer choises (QuestionOptionID).
2. Each question's QuestionOptionID (in the latter table) is unique. One of the QuestionOptionID is the correct answer and that correct QuestionOptionID can be found from the CorrectQuestionOptionID field in the questions table.

Here is how you get all the question's answer options for the question number one:

"SELECT QuestionOptionText, AnswerValue FROM tbl_ECM_Questionnaire, tbl_ECM_QuestionnaireOptions WHERE tbl_ECM_Questionnaire.QuestionID = tbl_ECM_QuestionnaireOptions.QuestionID AND tbl_ECM_Questionnaire.QuestionID = 1"

Here is how you get the correct answer option for the question number one:

"SELECT AnswerValue FROM tbl_ECM_Questionnaire, tbl_ECM_QuestionnaireOptions WHERE tbl_ECM_Questionnaire.QuestionID = tbl_ECM_QuestionnaireOptions.QuestionID AND tbl_ECM_Questionnaire.QuestionID = 1 AND tbl_ECM_Questionnaire.CorrectQuestionOptionID = tbl_ECM_QuestionnaireOptions.QuestionOptionID"

This doesn't answer your question about how to get something from the database to an array. I …

Teme64 215 Veteran Poster

a variable approaches infinity

You're right and that 'variable' is the number of elements. For example sorting algorithms are a well studied area of algorithms. Given N elements to sort, Bubble sort is an O(N x N) algorithm while Quick sort is an O(N x log(N)) algorithm.

some terms will be dropped

Ordo notation removes any constant factor from the algorithm. For example you could have an algorithm which takes 3xN operations and second algorithm which takes 70xN operations for N elements. Former algorithm would be more efficient in practise but in theory both are O(N) algorithms i.e. equally 'efficient' theoretically.

HTH

Teme64 215 Veteran Poster

Wikipedia had a really professional explanation about ordo i.e. I didn't understand the math :) But check the references and external links which this article has.

Teme64 215 Veteran Poster

I think almost every computer science book has it. Especially books about algorithms. You could try to find some online course material about algorithms. Check also Wikipedia.

HTH

Teme64 215 Veteran Poster

You have a databound combobox, right? Use

cboUsers.SelectedValue.ToString()

instead.

HTH

Teme64 215 Veteran Poster

You have to set first datetimepicker's format property to 'Custom' like this:

dtmPicker.Format = DateTimePickerFormat.Custom
dtmPicker.CustomFormat = "HH"

HTH

Teme64 215 Veteran Poster

If you simply try to detect when the app is closing, use the advice darkagn gave you.

Otherwise you have to use Windows API calls. I used this search engine and found this code. It should be a good starting point.

HTH

Teme64 215 Veteran Poster

If you simply try to detect when the app is closing, use the advice darkagn gave you.

Otherwise you have to use Windows API calls. I used this search engine and found this code. It should be a good starting point.

HTH

Teme64 215 Veteran Poster

Do not use 'window.location'. It navigates to a new page i.e. your popup window.

To show a popup, use

var strWindowFeatures = "menubar=no,location=yes,resizable=no,scrollbars=no,status=yes";
var windowObjectReference = window.open("http://popup.url/", "Popup Name", strWindowFeatures);

See for more details about window object. You may also check window.openDialog method.

HTH

Teme64 215 Veteran Poster

No. Download 32-bit driver from HP's Support Site

Teme64 215 Veteran Poster

Hi Benjamin! You could impress your teacher with this (needs using System.Linq at the start):

public bool isPalindrome(string aString)
{
return aString.Contains(new string(aString.Reverse<char>().ToArray<char>()));
}

Seriously. A string is an array of characters. Loop that array (i.e. string) by comparing first and last characters, then second character and second last character. As long as they are the same, you have a palindrome. When you encounter a mismatch, the string is not a palindrome.

HTH

Teme64 215 Veteran Poster

When you insert a new record you don't have an existing FacultyID value. I suppose you've declared FacultyID as Identity/Autonumber value so you shouldn't try to insert in that field anything.

Move line 37 between lines 29 - 30. After that your code accesses FacultyID only when the record exists and therefore that field does have a value.

HTH

Teme64 215 Veteran Poster

Use a loop to add multiple files:

    With AxVLCPlugin21
    .CtlVisible = True
    .playlist.items.clear()

    ' Loop until user presses Cancel button and
    ' add files to the playlist. The code _does not_ check the type of the file!
    Do Until OpenFileDialog1.ShowDialog() <> Windows.Forms.DialogResult.OK
       .playlist.add(OpenFileDialog1.FileName)
    Loop

    .playlist.play()
    .Toolbar = True
    .Show()
    End With

(Sorry about missing syntax coloring. I still haven't found how to do it!!!)
(Never mind :) It seems to come by itself...)

Teme64 215 Veteran Poster

Does it work if you add a semicolon after User ID:
"Provider=MSDAORA;Data Source=xe;Persist SecurityInfo=True;Password=me;User ID=cj;"

Teme64 215 Veteran Poster

Use Path class:
Dim dbpath As String = Path.GetDirectoryName(FileName)

HTH

Teme64 215 Veteran Poster

Here's a thread-safe way to assign text to the (UI-thread) control:

    Delegate Sub SetTextCallback(newString As String)

    Private Sub SetText(ByVal newString As String)

        ' Calling from another thread? -> Use delegate
        If Me.TextBox1.InvokeRequired Then
            Dim d As New SetTextCallback(AddressOf SetText)
            ' Execute delegate in the UI thread, pass args as an array
            Me.Invoke(d, New Object() {newString})
        Else ' Same thread, assign string to the textbox
            Me.TextBox1.Text = newString
        End If
    End Sub

Now, in your code line 29 becomes: SetText(indata)
Procedure SetText checks if the call comes from another thread: Me.TextBox1.InvokeRequired and calls the delegate if it does. Otherwise call comes from the same thread and the text can be assigned in a normal way.

HTH

(I checked "Markdown Syntax: Formatting Help" but I didn't find a way to use syntax formatting for the code part. I really miss BBCODEs... :) )

Teme64 215 Veteran Poster

In the line 17 you set a connection object to a command object: myCommand.Connection = conn
In the line 18 you create a new command object which destroys previous command instance: myCommand = New MySqlCommand(comm)
and this new command object doesn't have an open connection.

Solution: swap lines 17 and 18 i.e. first create a command object and then set it's properties.

HTH

Teme64 215 Veteran Poster

First, use Try...Catch...End Try to catch the error. It helps to solve the problem. And secondly, everything you do with the web is always more or less error prone.

Basic problem in your code is understanding how communication works between server and the client. In the code above you request something from the server and the server sends you a response.

I dropped the progressbar from your code because ContentLength does not return the filesize (actually reading ContentLength causes an error). You should request Ftp.GetFileSize and read the response. Second change I made is reading incoming data in a blocks and dumping blocks to a file. Reading a large file one byte at a time can be really slow. Anyway, here's my code:

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    '
    Dim buffer(1023) As Byte ' Allocate a read buffer of 1kB size
    Dim bytesIn As Integer ' Number of bytes read to buffer
    Dim totalBytesIn As Integer ' Total number of bytes received (= filesize)
    Dim output As IO.Stream ' A file to save response

    Try
        Dim FTPRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://ftp.microsoft.com/Softlib/" & "README.TXT"), System.Net.FtpWebRequest)

        ' No credentials needed in this case. Usually you need to provide them. Catch the appropriate error if/when credentials are wrong!
        FTPRequest.Credentials = New System.Net.NetworkCredential("", "")
        ' Send a request to download a file
        FTPRequest.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
        ' FTP server return a _response_ to your request
        Dim stream As System.IO.Stream = FTPRequest.GetResponse.GetResponseStream

        ' If you need the length …