JerryShaw 46 Posting Pro in Training

The SQL Column type you are looking for is either Text or nText. This is a blob field that allows any content you want.

Inorder to populate or download from this type of field, use the byte[] array and stream classes. The are ample examples on DaniWeb, CodeProject, and Google on how to do this.

If you still can't find an example, let me know some specifics about the server, database name and column name, and I can write a quick example for you using your own environment criteria (saves on confusion factor).

// Jerry

JerryShaw 46 Posting Pro in Training

Please mark as Solved
Thanks

JerryShaw 46 Posting Pro in Training

That SQL message can occur for a number of reasons. It is a generic message. You have to look at the innermessage and sometimes the innermessage.innermessage to see the real reason.

The connection string I sent uses windows authentication, and is pointing to my server. Make sure you are passing the name of your server, and catalog (aka database) in your own connection string.

If the message takes 30 seconds to appear, it is because you connection string is pointing to the wrong server/database. If it comes back immediately, it means that it sees the server, but either your database name is wrong, the authentication type is wrong, or the credentials are wrong.

Tell me the name of your server, database name, authentication mode, and credentials, and I will send you the correct connection string.

// Jerry

JerryShaw 46 Posting Pro in Training

Place a debug-bookmark on the line that places strline.ToString() into sw. Run under debug and see if that line is ever executed. I think you will find that it is not.
In order for it to fall into that conditional statement the text line (after split) must have atleast (4) elements, and the text has to match. You can use the deguger to see why the condition fails.

IOW, it is not the streamwriter that has the problem.

// Jerry

JerryShaw 46 Posting Pro in Training

using System.IO;

JerryShaw 46 Posting Pro in Training

Make sure that you have atleast 4 tokens on the target line in each file, since you are checking to see if there are MORE than 3 in your code.

Next, make sure you Close() all the files when you are done. Closing it is what causes it to write to the disk. I suggest that you also Flush() the output file prior to closing it.

I copied/pasted your code into a workbench, created some text files with 4 tokens, and it worked fine as long as there were 4 tokens, and I flushed and closed the output file, otherwise..... you get a zero byte output file.

// Jerry

JerryShaw 46 Posting Pro in Training

Basically, it is just a matter of first, make sure the sender is a button type, then cast sender as a button, then you have the originating button at your disposal.

Looking for something like this ?

private void button1_Click(object sender, EventArgs e)
        {
            if (sender is Button)
            {
                Button btn = (Button)sender;
                MessageBox.Show(btn.Name + " pressed");

                btn.Text = "MeHo";
                if (btn == button2) // something special if it was from button2
                    btn.Text += "-2";
            }
        }

//Jerry

JerryShaw 46 Posting Pro in Training

Charlie,

That is some messed up code you have there.
Looks like maybe you were trying to convert a VB app to C#.

I rarely write console apps, so there maybe some shortcuts, but the version below works.
I took the liberty of loading the players account with 10 bucks, and charging a buck to play a round.

Hope this helps:

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static Random rgen = new Random();

        static void Main(string[] args)
        {
            double cash = 10.0;
            int player;
            int dealer;
            double betAmount = 1.0;

            while( betAmount <= cash )
            {
                Console.WriteLine("Press Enter to draw a card.");
                Console.ReadLine();
                player = rgen.Next(2, 15);
                displayCard(player);
                Console.WriteLine("Press Enter to see dealer's card");
                Console.ReadLine();
                dealer = rgen.Next(2, 15);
                displayCard(dealer);

                if (Evaluate(player, dealer))
                {
                    Console.WriteLine("name(), you win!");
                    cash += (betAmount * 2);
                }
                else
                {
                    Console.WriteLine("you loose");
                    cash -= betAmount;
                }

                if (cash > 0)
                {
                    Console.WriteLine( string.Format("You have ${0} cash in hand",cash));
                    Console.WriteLine("play again? (yes/no) ");
                    string more = Console.ReadLine();
                    if (more == null || more.Length == 0 || more.Substring(0,1).ToLower() != "y" )
                        break;
                }
                else
                    break;
                
            }

            if (betAmount > cash)
            {
                Console.WriteLine("You do not have enough cash for that bet.");
                Console.WriteLine(string.Format("Cash: {0}", cash));
            }
            Console.WriteLine("Thanks for playing");

        }

        public static void displayCard(int card)
        {
            switch (card)
            {
                case 14: Console.WriteLine("Ace"); break;
                case 13: Console.WriteLine("King"); break;
                case 12: Console.WriteLine("Queen"); break;
                case 11: Console.WriteLine("Jack"); break;
                default:
                    if (card >= 2 && card <= 10)
                        Console.WriteLine(card);
                    else
                        Console.WriteLine("error: …
JerryShaw 46 Posting Pro in Training

Maybe posting this to the (C++) forum will help.
If you want to do it in C#, then I suggest that you load a second array with unique integers from the first array, then sum the second array.

JerryShaw 46 Posting Pro in Training

Instead of mangling the SQL statement (embedding CRLF), just iterate through the rows and columns, and populate the text box.
Here is a simple example:

private void toolStripButton1_Click(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection("Data Source=SHAWHP;Initial Catalog=SalonWiz;Integrated Security=True");
            conn.Open();
            DataSet ds = new DataSet();
            SqlDataAdapter adapter = new SqlDataAdapter(
                          "SELECT top 10 * from Employee",conn);
            adapter.Fill(ds);
            foreach(DataRow row in ds.Tables[0].Rows)
            {
                for(int i=0;i< ds.Tables[0].Columns.Count;i++)
                    textBox1.Text += row[i].ToString()+Environment.NewLine;

                textBox1.Text += Environment.NewLine;
            }
        }

// Jerry

JerryShaw 46 Posting Pro in Training
Ok that worked. I thought that .Split only accepted char and not strings, so why does it allow a string array like that? (More of a curious question than anything)

The reason is that tokens come in all shapes and sizes. For example, some Help files use 4 inline characters to desingnate the end of a topic. In order to handle something like
"&*%^" as a token they provided the string array as well as a string of values to satisfy that requirement.

// Jerry

JerryShaw 46 Posting Pro in Training

The code below returns the 6 parts you were looking for.
The seps var is now a string array instead of char array.
Using the string array in Spit with the remove emptry entries option.

string str = "while if for, public class do.";
            string[] seps = { " ", ".", "," };
            string[] parts = str.Split(seps,StringSplitOptions.RemoveEmptyEntries);
            string c = "";
            foreach(string z in parts)
                c += z+Environment.NewLine;
            MessageBox.Show(c,string.Format("{0} elements",parts.Length));

If this works for you (as it does for me), pleaase mark this thread as solved.
Thanks,
Jerry

JerryShaw 46 Posting Pro in Training

Another approach is to use Generics.
List<int> x = new List<int>();

x.Add(0); x.Add(1); ..... as many as you want, as often as you want.
When/If you ever need to use it as an array, you can always do this:

int[] z = x.ToArray();


The advantage here is that you can use the List for anything you can do with an array, only you have the added benefit of removing items, and adding items at will without dealing with redimensioning issues like copying the data from the old array into the newly sized array.

IMHO, Lists are far superior to the old style array.

// Jerry

JerryShaw 46 Posting Pro in Training

It appears that it does it correctly because the space after the comma is also a token.
You can either add a new sep ", " (with a space) or break the string into multipe Splits, and combine them later.

JerryShaw 46 Posting Pro in Training

A better approach is to see if it exists through sysObjects, and create it there, catch any errors on that.

IF  NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Country_Master]') AND type in (N'U'))

CREATE TABLE [dbo].[Country_Master](
	[County_id] [int] IDENTITY(1,1) NOT NULL,
	[CountryName] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
)

Then in c# run an Execute non query. Place that into a try catch

JerryShaw 46 Posting Pro in Training

Maybe setting the first enum as an Error so when they do not give a value then you can tell they didn't supply a value.

JerryShaw 46 Posting Pro in Training

Each time you use the ReadLine method, it will move the poistion marker in the stream to the next line. so you can keep using the same method to populate the other text boxes.

textBox1.Text = streamreader1.ReadLine();
textBox2.Text = streamreader1.ReadLine();
textBox3.Text = streamreader1.ReadLine();
// and so on.

JerryShaw 46 Posting Pro in Training

Hi Ramy,

Hope your trip to Cairo was all good.
As for the TimeStamp DataGridView column issue. I found that if the AutoGenerateColumns property is true (default), then the column will get bound, and you cannot do anything with it, other than drop that column, and add it back manually as a DataGridTextBoxColumn.
The Microsoft C# team says that once a column has been added to a grid, its type can not be changed. You have to delete it, and add it back as the other type. There is one caveat to this. You can exchange type between Combo and Text classes. Can't change between Image (aka Byte[]) and TextBox columnn types.

Once in the TextBoxColumn type, then you can to handle it in the CellFormatting event handler. Concat the bytes to hex into the args. e.Value property.

To just prevent the grid from blowing up, you can create a handler for the DataError event. Interestingly you don't need to add code to this handler. Its presence is all that is needed.

Obviously setting the Visible property to false also works, but the idea was to show all column values in a readonly grid.

So... (after all that hot wind), I am going to tackle creating all the columns at runtime based on the dataset, and schema.
BTW: I finally ran across a code snipet that allows you to find out what the REAL sql type is for a DataTable column. If …

JerryShaw 46 Posting Pro in Training

You cannot use an integer for money. It is a decimal type, and so just change your PayRate declaration to decimal or double instead of Int.

Also change your WeeklyPay variable
to decimal or double instead of string. You can always output (just about anything) as a string, but making assignments needs to be with compatible types.

BTW: normally use the Convert.To___() to cast between types.
Outputing as a string is as simple as appending the ToString() method to your variable:
decimal payrate = 40 * 7.50;
string WeeklyPay = payrate.ToString();

// Jerry

JerryShaw 46 Posting Pro in Training

Another hint for you,

Your assignment says to compute the rate at 7.5 for the first 40 hours, and 11.25 for each additional hour.

Your condition is only checking for if the hours equal exactly 40 hours then use 7.50, else use 11.25. So with your condition, if worked any hours other than exactly 40, then all of it is at 11.25.

Should be something like this.
in TotalHours = nnn
if( TotalHours <= 40 ) pay all hours at 7.50
else
pay at ( 40 * 7.50 ) + ( (TotalHours -40) * 11.25)

Hope that helps...

JerryShaw 46 Posting Pro in Training

Well I guess it is my turn to ask a question, since most of the time I spend answering questions on DaniWeb.

The Problem: DataViewGrid throws a "System.ArgumentException parameter is not valid..."
when the dataset contains an SQL 2005 TimeStamp type column.

The error occurs in System.Drawing.FromStream... da da da
It is because a TimeStamp is a Byte[8] unique value that my grid thinks is an image.

I am creating a type of Query Analyzer form. A simple select * from mytable is given to an adapter...

QueryDataSet.Tables.Clear();
                SqlDataAdapter adapter = new SqlDataAdapter(Query, conn);
                adapter.Fill(QueryDataSet,"Table");
                DataResultsGrid.DataSource = QueryDataSet.Tables[0];
                QueryBindingSource = new BindingSource(QueryDataSet, "Table");
                DataResultsGrid.DataSource = QueryBindingSource;

The dataset reads the schema when I set its datasource to this table, later I set it to the bindingsource to get it hooked. I can pass any SQL statement and it works fine... until the schema contains a TimeStamp column and the datagrid is scrolled to the right where the timerstamp column would be visible.. then this exception is thrown for each row.

Any ideas ?

// Jerry

JerryShaw 46 Posting Pro in Training

Is your service setup to interact with the users desktop ?
If not, the program will launch and will show up in task manager under processes, but the user will not see it.

JerryShaw 46 Posting Pro in Training

try changing the colon to a period

JerryShaw 46 Posting Pro in Training

First step would be to log the error message to the event log so you know what went wrong.
Does this code work from a standard app ?

JerryShaw 46 Posting Pro in Training

You should probably have a date field in the table, otherwise all you can do is assume a new record was added each day, and get the most recent.
Your question is a bit ambigious. Databases do not automatically get the next row, they store data. It is up to your application to poll the database for new data, or setup notification services (doesn't sound like you need to go down that path).
Without noting all the possible assumptions I can think of, maybe it would be better for you to provide a better description of what you are trying to do.

// Jerry

JerryShaw 46 Posting Pro in Training

I guess I need to understand the objective.
If you want to determine which radio button was checked, then you can send the checked radio button or just its Text in as a param.

You will have to obviously change the class to accept the string or RadioButton variable. I will assume you are going to send the string.

private List<BurstKlasse> Burst = new List<BurstKlasse>();
.
.
.
private void button1_click(object sender, EventArgs e)
{
int i = Convert.ToInt32( textBox1.Text);
string s = "";
if (rb_CPUburst.Checked)
   s = rb_CPUburst.Text;
else if(rb_IOburst.Checked)
  s = rb_IOburst.Text;

Burst.Add( new BurstKlasse(i,s) );
listBox1.DataSource = null;
listBox1.DataSource = Burst;
}

// Jerry
bk = new BurstKlasse( i,s);

JerryShaw 46 Posting Pro in Training

k,

Did you really intend on abstracting the IOBurst class ? that should only be used on the base class, and causes it to not be a class that you can instantiate. You should remove it.

I don't see anything that indicates a reason for subclassing these two classes from BurstKlasse. There are no inherited methods, or properties being used (that I can tell).

To instantiate either of these "subclasses" you do not need to preface them with BurstKlasse.

IOBurst ib = new IOBurst(value);
textBox1.Text = ib.ToString();


It is hard to tell what you intend (sorry I am missing it). Maybe you want the BurstKlasse class to have two properties. One of CPUBurst and one of IOBurst, and want the BurstKlasse instance to tell you which one you are using.

public class BurstKlasse
    {
        public int lengte;
        private CPUBurst cpub = null;
        private IOBurst iob = null;

        public BurstKlasse(int l,CPUBurst cpuBurst)
        {
            Id = l;
            this.cpub = cpuBurst;
        }
        public BurstKlasse(int l, IOBurst ioBurst)
        {
            Id = l;
            this.iob = ioBurst;
        }


        public int Id
        {
            get
            {
                return lengte;
            }
            set
            {
                lengte = value;
            }
        }

        public override string ToString()
        {
            string uit = "Lengte: " + lengte + " ";
            if(cpub != null)
                uit += cpub.ToString();
            if(iob != null)
                uit += iob.ToString();
            return uit;
        }
    }

    public class CPUBurst
    {
        private String soort = "CPU-Burst";

        public CPUBurst(String soort)
        {
            base.ToString();
            //super(lengte);
            Id = soort;
        }

        public String Id …
JerryShaw 46 Posting Pro in Training

I think it would be best if you posted the 3 classes source code. To get ToString() from a class, I assume you have override'n the ToString() method ?

I am thinking that the two subclasses are simple classes inside your base class ? or do they inherit from the base class ?
If inherited, did you instantiate them or the base class ?

// Jerry

JerryShaw 46 Posting Pro in Training

I am not real sure on what you are trying to do.
However, maybe this will help.

Each time that you instantiate a new Burst collection variable, then assign it a value, and then set the datasource of the list box to the new Burst collection (discarding the old one). This means that the listbox will use the new Burst as its datasource which only has the one item.
If you want to have it add multiple items, then you have to move the instantiation of the Burst collection outside of the methods, and add to it from a method:

private List<BurstKlasse> Burst = new List<BurstKlasse>();

 private void button2_Click(object sender, EventArgs e)
        {
            
            int lengt = int.Parse(lengte.Text);
            string CPU_Burst;
            if (radioButton1.Checked)
                CPU_Burst = radioButton1.Text;
            else
                CPU_Burst = radioButton2.Text;

            Burst.Add(new BurstKlasse(lengt, CPU_Burst));
            listBox2.DataSource = null;
            listBox2.DataSource = Burst;
        }

Note that you have to set the DataSource to null before reassigning it. This forces the component to re-evaluate the schema.

I am sure you have a good reason for setting the listbox datasource that was not provided in your message. But, if you don't you could just as easily have added the data directly to the listbox without using the datasource method at all.

Hope this helps,
Jerry

JerryShaw 46 Posting Pro in Training

I tried answering this morning, but the network connection failed. Sorry for being late :)

The Insert statement does not allow a Where clause.
I will assume that your Employee table has a column named "EmployeeName" or some place to put the name value. It would not make sense to place a task against an employee without also telling the database which employee the task is assigned.

I have revised the proc for you below.

Regards,
Jerry

create PROCEDURE [dbo].[AssignAndStore] 
	@name varchar(50),
@TaskAssigned nvarchar(50),
@TimeAssigned nvarchar(50)
AS
BEGIN
 
insert into Employee(EmployeeName,TaskAssigned,TimeAssigned)
values (@name,@TaskAssigned,@TimeAssigned)

END
JerryShaw 46 Posting Pro in Training

Okay, then if I can assume that the buttons already exist on the form, then simply have all the buttons point to the same event handler, and examine the object sender to determine which button was pressed.

Button btn = sender as Button;
Now btn is the button thas was pressed, and you can take whatever action you want on it.

If the button has a payload in the Tag property you can use that to determine how to send &*^%$ to the other PC.

Summary: The form contains the array of buttons, they all can share the same event handler, and perform actions based on some criteria of the button properties.

Does this help ?

Jerry

JerryShaw 46 Posting Pro in Training

Gaurav,

Its been awhile since I worked with SQL7, but it doesn't matter, they are almost all the same, except for the connection string.
The easiest way to find out what the connection string should be is to use Visual Studio's
Data menu then Add New Data Source... option.
Select Database, then click the New Connection... button.
When the dialog comes up, select to change the datasource (it defaults to Microsoft Sql Server). Select the <other> option, and select the OLE DB provider. This will bring you back to the former dialog. Now you can drop down the Combobox, and locate the Microsoft OLE DB provider for SQL Server. Fill out the rest of the info like the database server, database, user authentication, etc. and test the connection.

Once you get a good connection, press ok, and you get back to the first dialog.
Now, you can either let Visual Studio create a full blown class for this data source that will manage the server by pressing next (pick you name and objects), or you can just get the connection string from the bottom of the dialog, and copy/paste that into your code after pressing cancel.

Provider=SQLOLEDB.1;Data Source=SHAWHP;Persist Security Info=True;User ID=sa;Initial Catalog=Northwind

Now add the Data and OLE namespaces to your code:

using System.Data;
using System.Data.OleDb;

Now you can get your connection working by first instantiating a connection.

OleDbConnection conn = new OleDbConnection("Provider=SQLOLEDB.1;Data Source=SHAWHP;Persist Security Info=True;User ID=sa;Initial Catalog=Northwind");

Hopefully you …

JerryShaw 46 Posting Pro in Training

Do you mean ReadLn ?
Forgive me if there are syntax errors, typing this is off the top of my head.

StreamReader reader = File.OpenText("C:\\MyFile.txt");
            string line = reader.ReadLine();
            while (line != null )
            {
                // do something with the line. Assume a delimiter of Tab
                string Name = line.Split('\t')[0];
                string Account = line.Split('\t')[1];
                line = reader.ReadLine();
            }
            reader.Close();
            reader.Dispose();
JerryShaw 46 Posting Pro in Training

It is not real clear as to what you want to do.
Since you are using SQL, and you have a login screen, I assume you are using SQL authentication instead of Windows authentication. Next you want to get some data from the database, but you have not said how you want it displayed (Grid, components, etc).

Basic approach is getting the user name and password, then setting up the SqlConnection with the connection information. Load up a DataSet or just a DataTable, and bind the data to the display component of choice. If you are also going to allow editing, then additional code is used to marshal the changes back to the database.

Maybe on your 17th try you can post your code instead of deleting it. This website is all about helping new coders, so do not be ashamed of your code. No one's code is perfect.

Jerry

JerryShaw 46 Posting Pro in Training

Yes, I think I see your problem.
At the top of the file you are establishing the public Microsoft.Office.Interop.Excel.Workbook wbWPR = null variable.

Then later on, you do the same thing (again) in frmWTGTrack_Load.
Now what is happening, is you are creating a locally scoped variable in the frmWTGTrack_Load method. This means the one at the top is not being used, but rather the local variable is set. Once you leave the frmWTGTrack_Load method, that local variable goes away, and now other methods see the original, which was never changed from null to a value.

To correct the problem. Simply remove the type declaration from within the frmWTGTrack_Load method.

Change frmWTGTrack_Load method from:
Microsoft.Office.Interop.Excel.Workbook wbWPR = ExcelObj.Workbooks.Open...

TO:
wbWPR = ExcelObj.Workbooks.Open...


Have fun,
Jerry

JerryShaw 46 Posting Pro in Training

Maybe posting some of your code will help us help you.

JerryShaw 46 Posting Pro in Training

Sounds impossible. Can you post some code ? maybe there is s syntax error or something else.

JerryShaw 46 Posting Pro in Training

"Give same Code ??"
Do you mean giving them all the same event handler ? then let the event handler determine the button that was used ?

JerryShaw 46 Posting Pro in Training

I tried them out in 2008, and the directory browser's path does not react correctly. You can add some text boxes to your form that are populated with the new path from this component as you select or even double click around on the dir component... It fails 90% of the time to update it own Path property.
I would look for an alternative solution.

// Jerry

JerryShaw 46 Posting Pro in Training

ClarkKent,
Sorry I can not be of more help. Maybe you can get some help from the mongrel user group.
It appears that the Mongrel_Rail program has the built in service information that it passes on to the actual server via the comand line parameters. If you can get it to work manually, then automating it from C# should be possible.

Good luck on your adventure,
Jerry

JerryShaw 46 Posting Pro in Training

I have no experience with Mongrel, however I write Windows Service programs in C#.

When a Windows service is installed, it registers a Service Name (as declared in the installed service application). From that point on, you call upon the service using its registered name. In this case, the mongrel website states that you use mongrel_service as the service name when starting stopping, etc.

It states that if you want to change the registered service name you can use the Mongrel_Rails program with the -D parameter to change it.

I think that the actual service file is GemPlugin, and you can use the mongrel_rails application to communicate with the windows service.

You have probably already seen this site, but http://mongrel.rubyforge.org/wiki/Win32 does explain it fairly well. I think the answer to your "how to associate" is in there too.

// Jerry

JerryShaw 46 Posting Pro in Training

AMINIT,

If your project requires that you "must" use the System.Timer.Timer class, then you can set the timer's SynchronizingObject property to the form or component to take care of that cross-threading error. That will also eleveate the issue of invoking delegates.

From MSDN:::

If you use the Timer with a user interface element, such as a form
or control, assign the form or control that contains the Timer to 
the SynchronizingObject property, so that the event is marshaled to 
the user interface thread.

:::

This type of timer runs in its own thread. If you drop a timer component onto your form, then it will automatically set the SynchronizingObject property for you.

BTW: Since _rockbaer opened the topic of using threaded techniques, I re-wrote your project (inluding the save controls to text methods you requested) using a thread and no timers. The code length was chopped to less than 50% of what you currently have. If you are interested, and ready to delve into threads, I can send you the updated project. It will also show you how you can use the DateTime and TimeSpan classes instead of all those time decoding methods.

//Jerry

JerryShaw 46 Posting Pro in Training

Rockbaer,

Obviously you misread. The Timer class he is using will issue a cross-thread error because it is running in its own thread (nature of that timer class). That is why in your code response, you are using a delegate where he is not. Your delegate allows the code to work with components in the main thread.

The TimerClock class does not have a readonly attribute, so you are wrong in that appraisal.
The use of this TimerClock class IS the problem if the coder does not go through the process of creating delegates, and invoke the delegate when touching main thread non-thread safe components, as is quite evident in the cross thread error he received.

All that being said, introducing threading techniques at his level is not the right approach. Using a simple timer gets the job done. In fact, you built on his example code allowing the timer to control other objects in the main class, and then making two delegate calls to account for the non-thread safe textbox. IOW you are just perpetuating the use of an errant design, and probably doing more harm to his learning experience. If you want to give him a lesson in using threads, then provide him with a total re-write of the project, and explain the delegate and invoke techniques so he knows why and how they should be used.

If I were to write this program, I wouldn't be using a timer at all. I …

JerryShaw 46 Posting Pro in Training

Are you trying to start it as a service ?
Have you tried using a shell command "net start mongrel_service" or use a ServiceController component to launch it ?

// Jerry

JerryShaw 46 Posting Pro in Training

AMINIT,

This looks like the same program you sent to me earlier this week that I fixed for you.
Did you not get the zip file I sent back ?
The problem is the way you declare the out of class timer. The way it is defined, means it will run in its own thread. Threads can not adjust non-thread safe components in other threads (like this main thread).

private System.Timers.Timer timerClock = new System.Timers.Timer();

Above is the line that is causing your error.
Comment out that line, drag a timer component onto the form, and re-wire it to use the onTick event instead of the onTimer event (different args).

If you need me to re-post the program for you let me know. Otherwise please mark this post as solved.

Thanks,
Jerry

JerryShaw 46 Posting Pro in Training

Once you get all the stuff Ramy told you to do on your form, use the CellClick event of the grid to get at the data on that row.
You must check to be sure the user has selected a valid row. Row header, and Column headers return a value of -1 and therefore not a valid indexer.
This example expects a column named "MyData", however if you know the ordinal column you want to pull data from, then you can use that value.

private void MyGrid_CellClick(object sender, DataGridViewCellEventArgs e)
{
     if(e.RowIndex > -1)
        textBox1.Text = MyGrid.Rows[e.RowIndex].Cells["MyData"].Value.ToString();
}

Because you are a beginner, and we try to help beginners come up to speed fast on DaniWeb, I should point out that anytime you see an event handler that uses something other than the EventArgs type, it usually means it contains helpful data relevant to the event handler. In this case, the DataGridViewCellEventArgs type contains the Row and Column the user clicked.

Now in a full blown application, the author may want to hide some cells or not have them present at all in the grid, and you need to get at the bound data. In that case, you can still use the Row index to get to the underlying data in the Data table.

private void MyGrid_CellClick(object sender, DataGridViewCellEventArgs e)
{
     if(e.RowIndex > -1)
     {
            BindingSource bs = (BindingSource)MyGrid.DataSource;
            DataRowView drv = (DataRowView)bs.CurrencyManager.Current;
            textBox1.Text = drv[1].ToString();
     }
}

OR you can use a short-cut, which …

Ramy Mahrous commented: Deserve to be Master poster :) +2
JerryShaw 46 Posting Pro in Training

The Start method syntax allows you to pass a string array to the onStart event handler of the windows service:

string[] args = new string[2]{"Hello","World"};
            serviceController1.Start(args);
JerryShaw 46 Posting Pro in Training

The reason is that the compiler can see that there is the possibility that the condiotnal statement could be false, and therefore it can fall through to the next case statement.. which is illigal. So to fix the problem, always be sure that the case either returns, or does a break; as the last statement in each case statement.

JerryShaw 46 Posting Pro in Training

Pretty straight forward. Some vars for holding the amount of time. You can adjust these as needed in and reset the TimeSpan vars.
In the Tick event handler, evaluate if it is time to run that task, and then reset its Last time ran var.

You can also get creative and call those tasks as a new thread so that the timer can service the other tasks without waiting.

int Task1Timeout = 10; // seconds
int Task2Timeout = 10; // minutes
DateTime LastTask1 = DateTime.Now;
DateTime LastTask2 = DateTime.Now;

TimeSpan timerTask1 = new TimeSpan(0, 0, Task1Timeout); 
TimeSpan timerTask2 = new TimeSpan(0,Task2Timeout,0);

//// _Tick(..)
if( DateTime.Now - LastTask1 >= timerTask1)
{
   DoTask1();
  LastTask1 = DateTime.Now;
}

if( DateTime.Now - LastTask2 >= timerTask2)
{
   DoTask2();
  LastTask2 = DateTime.Now;
}
JerryShaw 46 Posting Pro in Training

Sounds like a Timing issue <no pun intended>
First I dislike the use of timers for the very reason you have stated. Instead I prefer to use threads... but that is just me.

I suggest that you use the single timer to do all the work since it is all in the main thread anyway. Setup some TimeSpan vars to determine when an action should occur, and let the single timer act on it.

Jerry