Passing data between different windows application forms

I have developed two forms, first form for scanning Bluetooth devices and second form to browse and select a folder. I want to pass data of device name and it's Bluetooth address from first form to second form and store it in database. I tried this but the database takes entries only from one form at a time and neglects the  data entered in other form. Plz provide a solution to my query.
IMG_20180124_141234034.jpg
IMG_20180124_141234034.jpg
Abhishek ModakStudentAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ryan ChongBusiness Systems Analyst , ex-Senior Application EngineerCommented:
since you got database, why not using it as the medium to store the data and share between your forms?
0
sarabandeCommented:
you already have the blootooth form as a parent dialog which invokes the folder browse dialog as a modal dialog. so you could make a constructor of the folder browser dialog where you pass the needed data as arguments. after ok returned, you would get the data to store in database from the folder browse form 'Fbd', which is still a valid object as long as it doesn't go out of scope. then store the combined data to the SQL 'con' there.

Sara
1
Abhishek ModakStudentAuthor Commented:
When I try to open and connect to a database connection from Bluetooth form it stores the device name and device address to database,then I close  the database connection from Bluetooth form and start connection in folder browse form.But the folder path entry doesn't get stored in database.
0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Abhishek ModakStudentAuthor Commented:
Also I tried to open a database connection first from folder browser form and then I have created public string variables in Bluetooth form to store device name and device address .Then I created an object of Bluetooth form in folder browse form and tried to store these information along with the folder path,but then also only folder path gets saved,no entry gets stored for device name and address
0
Ryan ChongBusiness Systems Analyst , ex-Senior Application EngineerCommented:
how these 2 forms were being opened? is your program multi-threaded ?
0
Abhishek ModakStudentAuthor Commented:
I have created four forms in total and each form is linked to another form using objects. Like after I get all information in Bluetooth form ,the form gets hidden the using an object for folder browse form I display the folder browse form and then select a particular folder and then hide it to open another form for entering password
0
käµfm³d 👽Commented:
Are these forms all in the same Visual Studio solution? If so:  https://www.experts-exchange.com/articles/4322/How-to-Pass-Data-Between-Forms-in-NET.html

If not, then you need something like .NET remoting, a self-hosted web service in each app, or the Win API.
0
Ryan ChongBusiness Systems Analyst , ex-Senior Application EngineerCommented:
from your code image (can you repost it as codes instead?) it seems that your Bluetooth form bt was not opened modally?
0
Abhishek ModakStudentAuthor Commented:
How to open bluetooth form bt modally?
0
Abhishek ModakStudentAuthor Commented:
bluetooth form code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Sockets;

namespace Folder_Security
{
    public partial class Bluetooth_App_Form : Form
    {
        List<string> items;
        List<string> paired_items;
        public String Dev_Address, Dev_Name;
        public Bluetooth_App_Form()
        {
            items = new List<string>();
            paired_items = new List<string>();
            InitializeComponent();
        }

        private void btn_Scan_Devices_Click(object sender, EventArgs e)
        {
            startScan();
        }
        private void startScan()
        {
            Discovered_Devices_List.DataSource = null;
            Discovered_Devices_List.Items.Clear();
            items.Clear();
            Thread bluetoothScanThread = new Thread(new ThreadStart(scan));
            bluetoothScanThread.Start();
        }
        BluetoothDeviceInfo[] devices;
        private void scan()
        {
            updateUI("Starting Scan..");
            BluetoothClient client = new BluetoothClient();
            devices = client.DiscoverDevicesInRange();
            updateUI("Scan completed");
            updateUI(devices.Length + " devices discovered");

           
            foreach (BluetoothDeviceInfo d in devices)
            {
                items.Add(d.DeviceName);

                //trial

                Dev_Name = d.DeviceName;
                Dev_Address = d.DeviceAddress + "";
                //select where deviceaddress!=d.deviceaddress

            }
           
            updateDeviceList();
        }
        Guid mUUID = new Guid("2DA0CC0E-1927-4CE8-A6BF-1B7DAF4BB9D4");

        private void updateUI(string message)
        {
            Func<int> del = delegate ()
            {
                tbOutput.AppendText(message + System.Environment.NewLine);
                return 0;
            };
            Invoke(del);
        }
        private void updateDeviceList()
        {
            Func<int> del = delegate ()
            {
                Discovered_Devices_List.DataSource = items;
                Paired_Devices_List.DataSource = paired_items;

                return 0;
            };
            Invoke(del);
        }
        BluetoothDeviceInfo deviceInfo;

        private void Discovered_Devices_List_Doublelick(object sender, EventArgs e)
        {
            deviceInfo = devices.ElementAt(Discovered_Devices_List.SelectedIndex);
            updateUI(deviceInfo.DeviceName + " was selected , attempting connect");

            if (pairDevice())
            {
                updateUI("device paired..");
                updateUI("starting connect thread");
                Thread bluetoothClientThread = new Thread(new ThreadStart(ClientConnectThread));
                bluetoothClientThread.Start();
            }
            else
            {
                updateUI("Pair failed");

            }
        }
        private void ClientConnectThread()
        {
            BluetoothClient client = new BluetoothClient();
            updateUI("attempting connect..");
            client.BeginConnect(deviceInfo.DeviceAddress, mUUID, new AsyncCallback(BluetoothClientConnectCallback), client);

        }

        private void BluetoothClientConnectCallback(IAsyncResult result)
        {
            if (result.IsCompleted)
            {
                updateUI("Device is now connected");
            }
        }
        string myPin = "";


        private bool pairDevice()
        {
            if (!deviceInfo.Authenticated)
            {
                if (!BluetoothSecurity.PairRequest(deviceInfo.DeviceAddress, myPin))
                {
                    return false;
                }
            }
            return true;
        }

        private void btn_View_Paired_Devices_Click(object sender, EventArgs e)
        {
            startScan_paired();
        }
        private void startScan_paired()
        {
            Paired_Devices_List.DataSource = null;
            Paired_Devices_List.Items.Clear();
            paired_items.Clear();
            Thread bluetoothScanThread = new Thread(new ThreadStart(paired_scan));
            bluetoothScanThread.Start();
        }
        BluetoothDeviceInfo[] paired_devices;
        private void paired_scan()
        {
            updateUI("Retreving paired device list...");
            BluetoothClient client = new BluetoothClient();
            paired_devices = client.DiscoverDevicesInRange();
            updateUI("Retrevied paired device list.");
           
            foreach (BluetoothDeviceInfo d in paired_devices)
            {
                if (d.Remembered == true)
                    paired_items.Add(d.DeviceName);
                Dev_Name = d.DeviceName;
                Dev_Address = d.DeviceAddress + "";
               
            }
         
            updateDeviceList();
        }

        private void Paired_Devices_List_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (Paired_Devices_List.SelectedIndex >= 0)
            {
                btn_Proceed.Enabled = true;
            }
            else
            {
                btn_Proceed.Enabled = false;
            }
        }

        private void btn_Proceed_Click(object sender, EventArgs e)
        {
            this.Hide();
            AddFilesForEncryption file1 = new AddFilesForEncryption();
            file1.Show();
        }
    }
}
0
Abhishek ModakStudentAuthor Commented:
Folder Browse code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace Folder_Security
{
    public partial class AddFilesForEncryption : Form
    {
       
        public AddFilesForEncryption()
        {
            InitializeComponent();
        }

        private void btn_Browse_Click(object sender, EventArgs e)
        {
            Bluetooth_App_Form bt = new Bluetooth_App_Form();
            FolderBrowserDialog Fbd = new FolderBrowserDialog();
            SqlConnection con = new SqlConnection(@"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\HP\Documents\Visual Studio 2015\Projects\Folder_Security\Folder_Security\Database1.mdf; Integrated Security = True");
            con.Open();
            if (Fbd.ShowDialog() == DialogResult.OK)
            {
                txt_File_Path.Text = Fbd.SelectedPath;
                 

                MessageBox.Show("Your Folder has been selected for encryption");
                SqlCommand cmd = new SqlCommand("INSERT INTO Devices(DeviceAddress,DeviceName,File_Path,Password) VALUES('"+bt.Dev_Address+"','"+bt.Dev_Name+"','" + txt_File_Path.Text + "','dsgg')", con);

               cmd.ExecuteNonQuery();
                btn_Proceed.Enabled = true;
            }

            else
            {
                MessageBox.Show("Please select a folder to proceed");
                btn_Proceed.Enabled = false;
            }
            con.Close();

        }

        private void btn_Open_Click(object sender, EventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start(txt_File_Path.Text);
            }
            catch
            { }
        }

        private void btn_Proceed_Click(object sender, EventArgs e)
        {
            this.Hide();
            SetPwd pwd = new SetPwd();
            pwd.Show();
        }
    }
}
0
Abhishek ModakStudentAuthor Commented:
Now i have provided the codes for both the forms. Now can someone please suggest me the exact commands to be inserted in both the forms so that the entries from both the forms get inserted and stored in the database 'devices' after the execution of both the forms!
0
Chris StanyonWebDevCommented:
Don't forget that your forms are just objects, so you can pass data between them the same as you can with any objects. You could either add a public property to the AddFilesForEncryption form and set that to the relevant info, or you could override / overload the AddFilesForEncryption constructor and pass in the values when you creae the form. @sarabande has already alluded to this.

In your AddFilesForEncryption form, overload the constructor to receive the relevant data. Add in a couple of private fields to store the info:

private string devName;
private string devAddress;

public AddFilesForEncryption(string devName, string devAddress)
{
    InitializeComponent();
    this.devName = devName;
    this.devAddress = devAddress;
}

Open in new window

Now in the Proceed method on your BlueTooth form, just pass the values in the ctor:

AddFilesForEncryption file1 = new AddFilesForEncryption(Dev_Name, Dev_Address);
file1.Show();

Open in new window

The values passed in will be available in your AddFileForEncryption form as the private fields devName and devAddress, so you can use them in your Database query.
0
Abhishek ModakStudentAuthor Commented:
@chris stanyon ,your solution worked.
0
Abhishek ModakStudentAuthor Commented:
@chris stanyon ,your solution worked.
0
Abhishek ModakStudentAuthor Commented:
Can someone please tell me how can I check using an SQL query whether an already scanned device address is already stored in the database? If it's stored then insert query should not execute , otherwise if no entry of the scanned device is found in database then only the insert query should run.
0
Chris StanyonWebDevCommented:
Excellent.

One way to avoid duplicates is to make sure your DB column is set to a unique constraint. Then when you try to insert a duplicate record an error (exception) is thrown and you can catch it. Something along the lines of:

try
{
     cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
    if (ex.Number == 2627 || ex.Number = 2601) { // unique constraint or unique index violation
        // duplicate found !!
    }
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
sarabandeCommented:
txt_File_Path.Text = Fbd.SelectedPath;

that is the crucial statement. if the database record doesn't contain a file path, it means that you forgot to store the selected file path into SelectedPath member of the folder browse dialog.
Bluetooth_App_Form bt = new Bluetooth_App_Form();
FolderBrowserDialog Fbd = new FolderBrowserDialog();

Open in new window


this code was in 'private void btn_Browse_Click(object sender, EventArgs e)' which was a function of class AddFileForEncryption

public partial class AddFilesForEncryption : Form

Open in new window


that doesn't make much sense. the new FolderBrowserDialog should be a child dialog of the Bluetooth_App_Form. that way you could pass device data when creating the FolderBrowserDialog via constructor.

currently you create a thread in bluetooth form when the 'proceed' button was clicked.

        private void btn_Proceed_Click(object sender, EventArgs e)
        {
            this.Hide();
            AddFilesForEncryption file1 = new AddFilesForEncryption();
            file1.Show();
        }

Open in new window


in the AddFilesForEncryption form you have a button 'browse'. when it was clicked you create again an empty bluetooth form (hidden) and a folder browser dialog. of course you don't have a chance to exchange any data between forms if you create always new objects whatt actually is a mess of objects.

bluetooth-form -> creates thread -> creates add-files-for-encryption - > creates bluetooth form and folder-browser-dialog


in my opinion you don't need threading. if the data to store is more than the one sql insert, you could put the sql execution into a thread. never create forms in a thread. especially when the form in the main thread is not waiting but has a still active gui.

so do:

- instead of the proceed button put the browser button into bluetooth form
- add a constructor to the folder browser dialog which has the device data you want to pass to the folder browser dialog as arguments. store the arguments to members of the folder browser dialog.
- if the browser button was clicked create a folder browser dialog  with the new constructor directly in the OnClick handler.
- call the Fbd.ShowDialog what would call the folder browser dialog as a modal dialog.
- in the Folder browser dialog store the selected path into SelectedPath what should be a public member if you want to access it from bluetooth form.
- when Fbd returned with ok, check with the debugger that Fbd.SelectedPath is not empty. if that is true, you can execute the sql with the data and it should work.

Sara
1
Abhishek ModakStudentAuthor Commented:
I have made device address in Bluetooth form as the primary key and I would like to check the SQL exception for insert query using either devAddress or devName
0
Abhishek ModakStudentAuthor Commented:
How to check whether a paired Bluetooth device is in range or not according to the code provided in my Bluetooth form?
0
Chris StanyonWebDevCommented:
These are 2 different questions to the original so they should be raised as new questions in the relevant forums. This question was in regard to passing data between forms which has already been answered.
1
Abhishek ModakStudentAuthor Commented:
Thanks for the assistance.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.