Click here to Skip to main content
15,885,032 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
HI, I have a C# Windows Console Application Which will execute an SQL Query and display the output in the console. I need to implement the same program in Windows Forms Application. So that the Query should execute in the Background and the output should be given in the windows Form and Message box as well.

The console application which i have is:-
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace LeakLocationFinder
{
 class Program
 {
     public static void sleep(int ms)
     {
         DateTime startTime_loc = DateTime.Now;
         DateTime stopTime_loc;
         TimeSpan duration_loc;
         do
         {
             stopTime_loc = DateTime.Now;
             duration_loc = stopTime_loc - startTime_loc;
         } while ((duration_loc.TotalMilliseconds < ms) && (!Console.KeyAvailable)); ;
     }
  static void Main(string[] args)
  {
   // Create the connection to the resource!
   // This is the connection, that is established and
   // will be available throughout this block.
     
          using (SqlConnection conn = new SqlConnection())
          {
              // Create the connectionString
              // Trusted_Connection is used to denote the connection uses Windows Authentication
              conn.ConnectionString = "server=(local);database=modelDb;user id=sa;pwd=Esi2008*";
              conn.Open();

              // Create the command
              SqlCommand command = new SqlCommand("DECLARE @var varchar(1000) = (SELECT TOP 1 Text FROM Alarms WHERE AlarmDefinitionId=139 ORDER BY EventTime DESC) DECLARE @start_position int, @end_position int SELECT @start_position = PATINDEX('% at%', @var) SELECT @end_position = PATINDEX('%kilometers%', @var) DECLARE @VALUE VARCHAR(10) = (Select SUBSTRING(@var, @start_position+5,5)) Select Top 1 @VALUE,RouteTable.Latitude,Routetable.Longitude,Alarms.EventTime FROM Alarms INNER JOIN Routetable ON Routetable.Location BETWEEN FLOOR(@VALUE)-1 AND CEILING(@VALUE)+1 WHERE AlarmDefinitionId=139 ORDER BY EventTime DESC", conn);

              /* Get the rows and display on the screen! 
               * This section of the code has the basic code
               * that will display the content from the Database Table
               * on the screen using an SqlDataReader. */
              do
              {
                  using (SqlDataReader reader = command.ExecuteReader())
                  {
                      Console.WriteLine("Leak Location\t\t  Latitude\t\t Longitude\t\t Leak Occured Time");
                      while (reader.Read())
                      {
                          Console.WriteLine(String.Format("{0}\t\t |\t{1}\t|\t{2}\t|\t{3}", reader[0], reader[1], reader[2], reader[3]));
                      }
                  }
                  sleep(5000);
                  Console.Clear();
              }
              while (!Console.KeyAvailable);
              {
                 Console.ReadKey(false);
              }
          }
          }
      }
    }
Posted
Comments
BulletVictim 13-Apr-15 1:51am    
What is the problem?
We cannot help you if we do not know what you are struggling with?
With regards to the query executing in the background, I'm Assuming it might cause the application to lock up for a bit? Try using threading for this,(will help with the application locking up during the execution of the query).
Krishna Chaitanya Bezawada 13-Apr-15 2:54am    
Actually, I need a Pop Up Window, Like Message Box functions. So i need to convert my console application to Windows Forms Application.
BillWoodruff 13-Apr-15 3:38am    
I suggest you start by studying the 'BackGroundWorker thread facility in .NET; it's easy to implement.
Florian Braun 13-Apr-15 3:40am    
do you want the query result in your popup? Or the popup when the query is done?

To display the query not in console but in a form you can add a listbox to a Form and put each line into the listbox instead using console.writeline.

To get the query into background you can use backgroundworker
Krishna Chaitanya Bezawada 13-Apr-15 5:00am    
I need the Result in the Popup

1 solution

I'd suggest the follwing steps:

1) create a new c# winforms applikation.
2) if you need to manualy start or stop the query add a button to do so.
3) add a timer and a backgroundworker to your form.
4) set the timmerintervall to 30 seconds and start the backgroundworker each timer the timer ticks.
5) put the query inside the backgroundworker and put each line into a List<string>
6) add the backgroundworker.RunWorkerCompleted - event.
7) add a new form on which you put a listbox for the result.
8) add a button to your second form to close it or a timer for autoclose
9) now you have some different ways to get the query result into your second form. maybe it's the easiest if you make the listbox in second form public.
10) your code in your primary form might be sth like this:
C#
void Button1Click(object sender, EventArgs e)
{
	backgroundWorker1.RunWorkerAsync()
}

void BackgroundWorker1DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
	List<string> liste=new List<string>();
	using (SqlConnection conn = new SqlConnection())
  	{
          // Create the connectionString
          // Trusted_Connection is used to denote the connection uses Windows Authentication
          conn.ConnectionString = "server=(local);database=modelDb;user id=sa;pwd=Esi2008*";
          conn.Open();

          // Create the command
          SqlCommand command = new SqlCommand("DECLARE @var varchar(1000) = (SELECT TOP 1 Text FROM Alarms WHERE AlarmDefinitionId=139 ORDER BY EventTime DESC) DECLARE @start_position int, @end_position int SELECT @start_position = PATINDEX('% at%', @var) SELECT @end_position = PATINDEX('%kilometers%', @var) DECLARE @VALUE VARCHAR(10) = (Select SUBSTRING(@var, @start_position+5,5)) Select Top 1 @VALUE,RouteTable.Latitude,Routetable.Longitude,Alarms.EventTime FROM Alarms INNER JOIN Routetable ON Routetable.Location BETWEEN FLOOR(@VALUE)-1 AND CEILING(@VALUE)+1 WHERE AlarmDefinitionId=139 ORDER BY EventTime DESC", conn);
          do
          {
              using (SqlDataReader reader = command.ExecuteReader())
              {
                  liste.Add("Leak Location\t\t  Latitude\t\t Longitude\t\t Leak Occured Time");
                  while (reader.Read())
                  {
                      liste.Add(String.Format("{0}\t\t |\t{1}\t|\t{2}\t|\t{3}", reader[0], reader[1], reader[2], reader[3]));
                  }
              }
          }
	 }
	e.Result=liste;			 
}
		
void BackgroundWorker1RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
		{

			Form2 form2=new Form2();
			form2.Show();
			foreach(string s in (List<string>e.Result) form2.listBox1.Items.Add(s);			
		}

where Form2 is your second Form and liste the List<string> with all the lines from query result. This would open a new popup form each time the query runs.
 
Share this answer
 
v2
Comments
Florian Braun 13-Apr-15 9:45am    
* in this example the query is started when you push the button, change that to a timer. (just to show how you can start the Backgroundworker)
* I put the whole sql-query and connection inside the backgroundworker. I guess there are many ways to create an object with the connection and comman and hand that one to the backgroundworker

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900