Link to home
Start Free TrialLog in
Avatar of Abhishek Modak
Abhishek ModakFlag for India

asked on

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
Avatar of Ryan Chong
Ryan Chong
Flag of Singapore image

since you got database, why not using it as the medium to store the data and share between your forms?
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
Avatar of Abhishek Modak

ASKER

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.
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
how these 2 forms were being opened? is your program multi-threaded ?
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
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.
from your code image (can you repost it as codes instead?) it seems that your Bluetooth form bt was not opened modally?
How to open bluetooth form bt modally?
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();
        }
    }
}
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();
        }
    }
}
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!
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.
@chris stanyon ,your solution worked.
@chris stanyon ,your solution worked.
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.
ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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
How to check whether a paired Bluetooth device is in range or not according to the code provided in my Bluetooth form?
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.
Thanks for the assistance.