Click here to Skip to main content
15,888,461 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have developed a Windows Forms Application in C#. The Form has one Button. And When that button is clicked it is connecting to an SQL Database and executing a Query. And it is showing the output of Query in a Message Box. Now what i need is, I need to auto generate the message box, that means i need to auto execute the Query with out clicking on Button. When the application is opened, it should start executing the Query and it should show me the result in the Message Box without clicking any button. And when we press "OK" on the message Box it will get closed. And it should again Execute SQL Query and display the output in the Message Box for every 30 Seconds.

The code which i have is:-

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace LocationFinder
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }
        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {

        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            About_LocationFinder formhelp = new About_LocationFinder();
            formhelp.Show();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string connetionString = null;
            SqlConnection conn;
            SqlCommand cmd;
            string sql = null;
            SqlDataReader reader;

            connetionString = "server=(local);database=modelDb;user id=sa;pwd=123456";
            sql = "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.ApplicationTime FROM Alarms INNER JOIN Routetable ON Routetable.Location BETWEEN FLOOR(@VALUE)-1 AND CEILING(@VALUE)+1 WHERE AlarmDefinitionId=139 ORDER BY EventTime DESC";

            conn = new SqlConnection(connetionString);
            try
            {
                conn.Open();
                cmd = new SqlCommand(sql, conn);
                reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    MessageBox.Show("Leak Location" + " |    " + "Latitude" + "     |  " + "Longitude" + "    | " + "Leak Occured Time" + Environment.NewLine +  "        " + reader.GetValue(0) + "         | " + reader.GetValue(1) + "  |  " + reader.GetValue(2) + " |   " + reader.GetValue(3));
                }
                reader.Close();
                cmd.Dispose();
                conn.Close();
            }
            catch (Exception)
            {
                MessageBox.Show("Cannot Open Connection...! ");
            }
        }
        private void Form1_Shown(Object sender, EventArgs e)
        {
            button1.PerformClick();
        }
    }
}
Posted

instead of
C#
button1.PerformClick();
you can call
C#
button1_Click(sender,e);


YOu can then add a timer and add button1_Click directly to the tick-event of the timer. but each timer-tick/query will open a new messagebox on top of the former...
 
Share this answer
 
Comments
Krishna Chaitanya Bezawada 16-Apr-15 4:22am    
Yes, I have tried both what you said. But it is not doing anything, if i click manually only, then it is executing.
Florian Braun 16-Apr-15 4:29am    
did you enable the timer?
Krishna Chaitanya Bezawada 16-Apr-15 4:44am    
Yes, I have enabled it. Below Mr.Praveen has modified the code right, which he has modified is working Perfect.

And

Now is it possible to store the value of Reader[0] in any variable?

And can we compare the reader[0] value of 1st Execution With reader[0] value of 2nd Execution for checking whether any change of Value?
You can add it in Form Load event and put it into a loop. Check below code.
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
 
namespace LocationFinder
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }
        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
 
        }
 
        private void MainForm_Load(object sender, EventArgs e)
        {
        //While true is actually not suggested, this will lead to an endless loop, but your requirement says to put while true. You can use a for loop and put some counter condition also.
		string old_reader_val = "";//global variable to store the reader[0] value
            while(true)
            {
            string connetionString = null;
            SqlConnection conn;
            SqlCommand cmd;
            string sql = null;
            SqlDataReader reader;
 
            connetionString = "server=(local);database=modelDb;user id=sa;pwd=123456";
            sql = "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.ApplicationTime FROM Alarms INNER JOIN Routetable ON Routetable.Location BETWEEN FLOOR(@VALUE)-1 AND CEILING(@VALUE)+1 WHERE AlarmDefinitionId=139 ORDER BY EventTime DESC";
 
            conn = new SqlConnection(connetionString);
            try
            {
                conn.Open();
                cmd = new SqlCommand(sql, conn);
                reader = cmd.ExecuteReader();
                while (reader.Read())
                {

		    if(old_reader_val== reader.GetValue(0))//comparing old reader value with new reader value
			{
				//No change
			}
			else
			{
				//New reader has a new value.
			}			
		    old_reader_val = reader.GetValue(0);//assigning new reader value to old reader value again, so that again it can compare with new one.
			

                    MessageBox.Show("Leak Location" + " |    " + "Latitude" + "     |  " + "Longitude" + "    | " + "Leak Occured Time" + Environment.NewLine +  "        " + reader.GetValue(0) + "         | " + reader.GetValue(1) + "  |  " + reader.GetValue(2) + " |   " + reader.GetValue(3));
                }
                reader.Close();
                cmd.Dispose();
                conn.Close();
            }
            catch (Exception)
            {
                MessageBox.Show("Cannot Open Connection...! ");
            }
        System.Threading.Thread.Sleep(30 * 1000);
        //This will put a 30 second sleep.
        }//while loop ends ehere
        }
 
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            About_LocationFinder formhelp = new About_LocationFinder();
            formhelp.Show();
        }
 
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
 
        }
        private void Form1_Shown(Object sender, EventArgs e)
        {
 
        }
    }
}
 
Share this answer
 
v2
Comments
Krishna Chaitanya Bezawada 16-Apr-15 4:37am    
Your code was Working Perfect. It was displaying a pop up for every 30 Seconds.

Now is it possible to store the value of Reader[0] in any variable?

And can we compare the reader[0] value of 1st Execution With reader[0] value of 2nd Execution for checking whether any change of Value?
Praveen Kumar Upadhyay 16-Apr-15 5:21am    
Yes absolutely you can. First if the solution has solved your problem which you have mentioned in your question, then please accept the solution.
Krishna Chaitanya Bezawada 16-Apr-15 5:29am    
Can you please tell me how can we do it?
Praveen Kumar Upadhyay 16-Apr-15 5:50am    
Thank you for accepting my answer. Check the updated solution.
Krishna Chaitanya Bezawada 16-Apr-15 6:07am    
Yes I have Checked it Bro.

The Last time where you are getting new Reader value into "Old_reader_val", That statement is returning an error.

The error it was showing is:-

"Only assignment, call, increment, decrement and new object instruments can be used as statement"

And if Loop also returning an Error, The error was:-

"Possible Unintended reference Comparison; to get a value comparison, cast the right hand side to type String"

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