JerryShaw 46 Posting Pro in Training

chkActive.Checked=(bool)dt.Rows[0];

JerryShaw 46 Posting Pro in Training

MJV,
Run it in debug mode, and see what the InnerException.Messge is telling you. (post it here if you do not understand it)

The syntax of the code looks right. You can have many connections to SqlExpress if that is what you are using. I have applications with many threads hitting an SqlExpress with no issues. MS recommends limiting to 5, but that is only a recommendation. I have never seen it reject a login due to the number of connections( at least on SqlExpress).

Viewing the InnerException should tell you exactly what is going on.

JerryShaw 46 Posting Pro in Training

label1.ForeColor = Color.Red;

JerryShaw 46 Posting Pro in Training

Take a look at the DateTimeOffset struct.
Also the TimeZone class

You should be able to use those and then use the DateTime AddHours method to get the new date you are looking for.

//Jerry

JerryShaw 46 Posting Pro in Training

No you have have many connections.
Can you provide your exact connection string that you are using.

// Jerry
Sorry for the delay, I tried sending you a reply hours ago from a different PC, but for whatever reason, it did not show up here.

JerryShaw 46 Posting Pro in Training

Okay, I see you are getting nowhere, so I will give you the code to do this:

private void DoSomething()
        {
            string ConnectionString = "Data Source={0};Initial Catalog={1};Integrated Security=True";

            int estno; 
            if( int.TryParse(startestnoCB.Text,out estno) )
            {
                SqlConnection conn = new SqlConnection( 
                    string.Format(ConnectionString,".//SqlExpress" // Your Sql Server
                    , "EstimateDataSet" // Your SQL Database
                    ));

                SqlCommand cmd = new SqlCommand("EstimateApproval", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@Estno", estno);
                try
                {
                    conn.Open();
                    #if WantSomethingBack
                    DataTable result = new DataTable();
                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                    adapter.Fill(result);
                    foreach(DataRow row in result.Rows)
                    {

                    }
                    result.Dispose()
                    #else
                    cmd.ExecuteNonQuery();  // If you do not need a return;
                    #endif
                }
                catch (SqlException err)
                {
                    MessageBox.Show(err.Message);
                }
                finally
                {
                    if(conn.State == ConnectionState.Open)
                        conn.Close();
                    conn.Dispose();
                }
            }
        }
JerryShaw 46 Posting Pro in Training

This is what i have tried. I get no errors but the database is not changing as per the stored procedure which does work when run within sql.

private void approveestBN_Click(object sender, EventArgs e)
    {


        int @estno;            
        int.TryParse(startestnoCB.Text,out estno);


        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "EstimateApproval";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("@estno", SqlDbType.Int);            
    } 

end quote.

Where is your SqlConnection assignment to the SqlCommand ?
Where is your value assignment to the cmdParameter ?
Where is your Execute command on cmd ?

JerryShaw 46 Posting Pro in Training

Hopefully this will make more sense to you.
You declare a delegate method with no parameters. You want to assign two instances of this delegate and each will be assigned to a seperate method.

Each method must have the same parameter list as the delegate (which you do have).

Your attempt at assigning an event (+=) is totally wrong. Don't confuse event handlers with delegates. Delegates basically define a method call syntax. You can assign any method that has the same list of parameters to an instance of the delegate.

In the code snipet, I create an instance of Hello to a variable named g1. The delegate takes a single parameter which is the name of the method that will be called.

Then you invoke (call) the instance to cause the assigned method to be executed.

public delegate void Hello();
        public delegate void Hello2(string value);

        static void Main(string[] args)
        {
            // Assign g1 to the Goodmorning() method
            Hello g1 = new Hello(Goodmorning);
            // Assign g2 to the Goodevening() method
            Hello g2 = new Hello(Goodevening);
            Hello2 g3 = new Hello2(Salutations);
            // Invoke both methods through the delegate
            g1();
            g2();
            g3("Good Afternoon");
            // Wait for the user to press a key to exit
            Console.WriteLine("<press any key to exit>");
            Console.ReadKey();
        }

        public static void Goodmorning()
        {
           Console.WriteLine("Good Morning");
        }

        public static void Goodevening()
        {
            Console.WriteLine("Good Evening");
        }
        public static void Salutations(string value)
        {
            Console.WriteLine(value);
        }
ddanbe commented: Good explanation! +4
JerryShaw 46 Posting Pro in Training

Liz,

honeybits already failed the assignment. Asking for information on what went wrong is an appropriate reaction from someone that is interested in learning.

The prior answers in this thread make sense to someone that already has a basic grasp of programming in C#. But it is obvious to me based on the extreme simplicity of the assignment that honeybits is just now getting started.

Hopefully honeybits will actually study it. If not, S/he is doomed (and deservingly so) to fail the entire course.

I have noticed a trend of late by some of us here being over critical and short fused with the newbees. They took the time to ask the question, lets try to give an appropriate response geared towards the level of the student asking the question. I would join any chastising of someone just wanting us to do their homework for them. But asking what they did wrong afterwards… that (IMO) is deserving of an answer.

// Jerry

Antenka commented: nice :) +2
JerryShaw 46 Posting Pro in Training

fi.FullName

JerryShaw 46 Posting Pro in Training

CheckListBox is subclassed from ListBox. The SelectionMode is valid in the ListBox control, but only None and Single in the CheckListBox. It is not a true error! But, the programmer should have overridden the property and used a subset, or just a bool to allow selection or not.

Multi select is not valid due to the way the internal check on click method works with the SelectionMode.

They obviously needed to keep it because they wanted to let the None to be allowed...
// Jerry

JerryShaw 46 Posting Pro in Training

honeybits,

Let me apologize for my colleague’s answers. Often times it is easy to forget that this forum has many students and new-bees. Do not let them discourage you from asking questions here.

static void Main(string[] args)
        {
            string _countStart;
            string _countEnd;
            string _oddEven;
            int _iStart;
            int _iEnd;

            string _runAgain = "y";

            while (_runAgain.ToLower().StartsWith("y"))
            {
                Console.Write("Where do you want to start counting <integer> 0>:");
                _countStart = Console.ReadLine();
                Console.Write("Where do you want to end counting <integer> 0>:");
                _countEnd = Console.ReadLine();
                Console.Write("Display even or odd numbers <e, o>:");
                _oddEven = Console.ReadLine().Substring(0,1).ToLower();

                if (
                    Int32.TryParse(_countStart, out _iStart)
                    && Int32.TryParse(_countEnd, out _iEnd)
                    && "e,o".Contains(_oddEven)
                    )
                {
                    
                    //gives the location of decimal and hex
                    Console.WriteLine("{0} {1,20}", "Decimal", "Hex");
                    for (int i = _iStart; i < _iEnd; i++)
                    {
                        if (_oddEven == "e")
                            if (i % 2 == 0)
                                Console.WriteLine("{0} {1,23}"
                                    , i.ToString().PadLeft(3,'0')
                                    , i.ToString("x").ToUpper().PadLeft(2,'0'));
                        else
                            Console.WriteLine("{0} {1,23}"
                                , i.ToString().PadLeft(3, '0')
                                , i.ToString("x").ToUpper().PadLeft(2, '0'));
                    }
                }
                else
                {
                    Console.WriteLine("Invalid Entry detected");
                }

                //ask the customer do they want to run the program again
                Console.Write("Run again <yes/no>:");
                _runAgain = Console.ReadLine();
            }

        }

Copy this code and then study it.
What they were trying to say is that you need to get the answer from the ReadLine into a variable. Next you need to actually use the values provided by the user, however you must validate their entries.
Then it is just a matter of looping through the numbers and produce the output.

Now, this is your homework, so you need to go …

JerryShaw 46 Posting Pro in Training

Take a look at FileSystemWatcher (a component in the tool box).
It will detect when new files have been added to a directory.

Otherwise, you can use something like this is a timed loop:

DirectoryInfo dirinfo = new DirectoryInfo("C:\\temp");
   foreach (FileInfo fi in dirinfo.GetFiles("info_*"))
   {
         // do something with file
         fi.Delete();
   }
JerryShaw 46 Posting Pro in Training

Is the file your application encrypts an executable or something like a text file ?

Your application could use a Trojan technique. You would need a separate small exe that knows how to request the password, inspect the cypher key, decrypt the (named) embedded file to disk and perhaps call upon windows to open that new file.

To place the file into the trojan, you would need to access (add) the file to the resources section of the trojan exe. Then rename the trojan to the name you desire. Once the user runs this trojan exe, it would popup the password dialog. Once they enter the correct password, you would write the file from the resources section onto the hard drive. Then, if the system supports the file extension, you could launch it.

sounds very do-able. Have fun with it.

JerryShaw 46 Posting Pro in Training

The problem is simple, the solution a little more involved, but first you should understand that when the form repaints it goes through its list of componets and repaints them.
The image you lay on the form is not a part of the form's collection therefore, when the component it is sitting on top of gets painted, it gets rid of your bitmap.

The solution is to force your bitmap to be repainted anytime the form (or more specifically the container) that your bitmap will be hovering over.

To do it without killing your system, you should not read the bitmap file everytime there is a repaint. Instead, keep a variable to hold the bitmap at the form level, or build a collection of GDI objects you want to have repainted when the time comes.

In the form's Paint event, have it paint your GDI object.

Example:

BtiMap _bitmap = null;
        private void button1_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    _bitmap = new Bitmap(openFileDialog1.FileName);
                    Invalidate(); // cause the form to repaint.
                }
                catch
                {
                    MessageBox.Show("Sorry there is an error");
                }
            }
        }


        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            if(_bitmap != null)
                e.Graphics.DrawImage(_bitmap, new Point(0, 0));
        }

If this solves your issue, please mark it as solved.
//Jerry

JerryShaw 46 Posting Pro in Training

Are you sure you want to use the for loop with Count -1 ?

for(int i = 0;i< cartDataGridView.Rows.Count -1;i++)

I think you want :

for(int i = 0; i < cartDataGridView.Rows.Count ; i++)

If the grid only has the one order, you will not get any total (well total of 0), if you have more than one, it will miss the last one in the grid.

JerryShaw 46 Posting Pro in Training

You do not need to use the GetBytes. It is available if you need to do special things with that byte array, however you want the entire array as you originally placed it into the database.

SqlCommand cmd = new SqlCommand("Select ImageHash from SIMILAR WHERE ID=26", con); 
            con.Open(); 
            rdr = cmd.ExecuteReader(); 
            rdr.Read();
            byte[] temp = (byte[])rdr["ImageHash"];

// Jerry

JerryShaw 46 Posting Pro in Training

Passing parameters to a method requires the correct parameter list declaration in the Method construct.

If you plan on passing a strictly typed list then for your example:

private void something(int[] a, int[] b, int c)

If you do not know how many parameters you are going to send, or the order then you can use a different approach:

private void something(params object[] data )

To Call either of these methods you can format the call as such:

something(new int[] { 0, 1 }, new int[] { 2, 3 }, 3);

Note that if you have both of these method constructs, the more exact version is what will be used:
IOW the one with the something(int[] a, int[] b, c) is prime because it exactly meets the parameters being called.
If you rearrange the parameters so that the int is in position 0 or one, then it uses the something( params object[] data) version.

To use the "params" version you could do something like this:

private void something(params object[] data )
        {
            int sum = 0;
            int[] somearray;
            foreach (object obj in data)
            {
                if(obj.GetType() == typeof(int[]))
                {
                    somearray = (int[])obj;
                    foreach (int n in somearray)
                        sum += n;
                }
                else if (obj.GetType() == typeof(int))
                {
                    sum += (int)obj;
                }
            }
            MessageBox.Show(sum.ToString());
        }

Happy Coding // Jerry

JerryShaw 46 Posting Pro in Training

What types are blankl and blankw ?
As integers, I do not get any errors, or the thrown error.

JerryShaw 46 Posting Pro in Training

As danielernesto said, store it to a column type that supports byte arrays such as Image or VarBinary(max).

// Jerry

JerryShaw 46 Posting Pro in Training

As Sknake answered in the other post, if you need the tiff OCR'd then you need a package. If you need to know the number of bytes, then just open the file in a FileStream (or a number of other classes), and check the length.
If not OCR'd, then you are working with the raw image which is in bytes not lines or chars.

JerryShaw 46 Posting Pro in Training
DateTime dt;
int year;
int month;
int day;
if(DateTime.TryParse(textbox1.Text, out dt))
{
        month = dt.Month;
        year = dt.Year;
        day = dt.Day;
        // Do what you want with the breakout
}
JerryShaw 46 Posting Pro in Training
DataGridView dgv = new DataGridView();
dgv.CellValueChanged += new DataGridViewCellEventHandler(dgv_CellValueChanged);
JerryShaw 46 Posting Pro in Training

ddanbe,

Just for clarifiation, StringBuilder is exactly that, a mutable array of chars. Mutable meaning that is has internal facilities to expand its size in contrast to a fixed array. These internal facilities are really not much different than the manual method of adding a new element to a fixed array.

The class creates a buffer of (n) length (default is 16, max is Int.MaxValue). Everytime the Append... methods are used, it will try to add the chars to the buffer. If the buffer is not large enough, it will allocate more memory, and reload the chars into the new allocation. This is the biggest problem with using this class. Programmers, tend to use the default and this results in memory thrashing and a decrease in performance. Certainly not recommended for Mobile / Smartphone or embedded programming.

So yes, programmers need to know what is under the hood. To use this class efficiently, they should allocate enough space up front to reduce the reallocation process as much as possible.

Thanks for the complement on the code snips, I would do it differently in a production system by reducing the number of Split operations. Probably would just iterate through looking for the first space after a CRLF, and alter the chars for the first word as you describe in your snippet.

Kindly,
Jerry

JerryShaw 46 Posting Pro in Training

Thank You JerryShaw.. You Saved me a lot of Time .

Welcome.... Don't forget to mark this as Solved :)

JerryShaw 46 Posting Pro in Training

If you really don't need an SQL Server, then you can use XML.
Let me explain, On many projects I use a locally saved DataSet for all kinds of purposes, storing configuration, multi-media, and even storing serialized classes.

The DataSet class has an WriteXml method that will save the entire DataSet as an XML file. It has a ReadXml method that allows you to repopulate your applications dataset when you need it.

To get started, Create a dataset on your form, or special class, or DLL. Add the desired Tables, and columns with Types. You can even setup relationships similar to foreign keys between the tables.

Setup your form just like you would for any database centric application using binding sources, etc. (although this is optional).

Your application starts off with no data in the dataset, so let your user add data to the tables using your form. Once your user wants to save the data, then use

_myDataSet.WriteXml(_myFileName,XmlWriteMode.WriteSchema);

Now when the user starts the application, check to see if your filename exists, and if it does, use

_myDataSet.ReadXml(_myFileName);

Okay, now you have a local database contained in a DataSet. Now to perform SQL type queries, you can use the Table.Select method.
Lets assume you have a table named "Payroll" contained in your dataset. Lets say you want to get all the records for department "Engineering". (If you want all that start with Enginerring, you can use the LIKE 'Engineering%' qualifier, very …

sid78669 commented: Superb! He should be a prof!! +1
JerryShaw 46 Posting Pro in Training

StringBuilder is (as you know) an array of char.
So you can either loop through getting the first space to detect the word, and start looking for the return\line feed '\r\n' or just convert it to string.

Here are a couple ways.
If only one line is in the stringbuilder (dumb & ugly)

sb = new StringBuilder("alpha beta");
            string result = sb.ToString().Split(' ')[0].ToUpper()
                + sb.ToString().Substring(sb.ToString().Split(' ')[0].Length);

If more than one line in the stringbuilder:

StringBuilder sb = new StringBuilder();
            string text = string.Empty;
            char[] CRLF = new char[2] { '\r', '\n' };
            
            sb.AppendLine("Alpha One");
            sb.AppendLine("Bravo Two");
            sb.AppendLine("Charlie Three");
            
            string[] lines = sb.ToString().Split(CRLF,StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < lines.Length; i++)
            {
                string[] words = lines[i].Split(' ');
                text += words[0].ToUpper() + lines[i].Substring(words[0].Length) + Environment.NewLine;
            }
// text contains your text with the first word capitalize for each line.

PS: Hi Ramy, been a long time....

Ramy Mahrous commented: completely right +6
JerryShaw 46 Posting Pro in Training

If you want the listbox on the Main form to be updated when something happens on the other class, you need to create an event in the other class, and subscribe to it from the main form.

If you want the event to provide you with some information then you will need to either use an existing delegate or create your own.

You will want to create a simple arguments class to contain the information you want passed back to the main form.

class FooArgs
{
       private string _text;
       public string Text
       {  
            get{return _text;}
            private set{_text = value;}
       }
       public FooArgs (string value)
      {
          Text = value;
      }
}

You can put anything else you want into that FooArgs class that you need.

Next you want to setup a delegate for it, and assign an event in the Foo class.

public delegate void FooChanged(object sender, FooArgs e)
   public event FooChanged onFooChanged;

Now in your Foo class, when you want to notify the main form of some change:

public void DoSomething(string something)
{
      if( onFooChanged != null )
          onFooChanged(this, new FooArgs("erata"));
}

In the main form class, you would assign this event handler.

Foo foo = new Foo();
   foo.FooChanged += FooChanged(someFooHandler);

Give it a try... I free handed this, so hopefully there are no errors.
// Jerry

JerryShaw 46 Posting Pro in Training

Not knowing the layout of your application, I will make the assumption that you have the ListView on the main form.
You have some other form or class that is called upon to do something and you want something to appear in the ListView of the main form.

The problem Is the Scoping of the ListView instance. You need to send that instance to the other class, or make it public (modifier on the poperty editor <frowned upon>) on the main form, and make sure the class can see this instance.

Lets say your main form is named form1, your ListView is named listview1, and your other class is named Foo.

// Pass ListView into the constructor of Foo
Foo _foo = new Foo( listview1 );
_foo.DoSomething();

// OR pass it to a method of Foo
Foo _foo = new Foo();
_foo.DoSomething( listview1 );


class Foo
{
     private ListView _listview;
     public Foo( ListView listview)
    {
         this._listview = listview;
    }

    public  void DoSomething()
    {
         _listview.Items.Add("Test from Foo");
    }
}

OR

class Foo
{

     public void DoSomething( ListView listview )
     {
          listview.Items.Add("Another Test from Foo");
      }
}
JerryShaw 46 Posting Pro in Training

I am not familiar with Neverwinter Nights.
However it appears you are delving into graphical programming. It is a very exciting field, and I suggest getting a book on the subject. By dove tailing that with your component building book, you should be able to build just about anything.

There are two basic approaches. You can use bitmaps, or vector based (Pen drawn) objects. Create a base class to handle the typical drawing methods, and subclass the rendering methods to draw the image with the Paint event.

The topic is too deep for this forum, but you can check out this website for a basic demo.
http://www.bobpowell.net/animation.htm
The Shape class is a good tutorial for you to expand upon in building graphical components.

Have fun!

JerryShaw 46 Posting Pro in Training

For school work that is fine. For real world, you should use Int32.TryParse because you never know what will be in those text boxes.

int result_1;
int result_2;
if (Int32.TryParse(textBox1.Text, out result_1)
     && Int32.TryParse(textBox2.Text, out result_2))
{
      textBox3.Text = (result_1 * result_2).ToString();
}
JerryShaw 46 Posting Pro in Training

Typically this question comes up when you don't want the user to leave a dialog form until all of the required text boxes are populated.

If that is the case here, then do not enable the Ok button until the required textboxes are populated. To test when to enable the ok button, write a single event handler for the TextChanged event and assign it to all three textbox controls.

In the event handler;

buttonOK.Enabled = !string.IsNullOrEmtpy(textbox1.Text) 
       && !string.IsNullOrEmpty(textbox2.Text)
       && !string.IsNullOrEmpty(textbox3.Text);

This is much better than a bunch of if..else..else statements.

If this is not a modal dialog type form, and you really need to use if..else statements, then use the format:

if( condition )
{
     ...
}
else if (condition2)
{
   ...
}
else if( condition3)
{
   ...
}
JerryShaw 46 Posting Pro in Training

=======
I discovered it wasn't set. Setting it to either HelloWinForm.Test or HelloWinForm.Program, the first two problems disappear, but not the third. I can't see how this code has more than one entry point, and I'm not at all clear on why the compiler requires these gyrations in Startup Object. None of these issues are mentioned by CSharpSchool, which claims the code I used will run as written. This is my first Windows app, and WOW! am I in the dark on this. What gives? Maybe I should just get a different tutorial. Any explanations of this or, failing that, any suggestions for which tutorial(s) I should use?
=======
First, No, you do not need to set the Startup Object for this project.
Second, looks like a very old tutorial, I suggest getting a book so you are familiar with how VS structures a program.

To create your hello world project, let the IDE do the work for you.
Create a new Win Form project, drag a label named lblGreeting onto the form.
Now either setup the properties of the form for its Text and Size, and the Text for the label and just run it, OR (the hard way) in the constructor (the only method created for your new form) add the code under the existing InitializeComponent(); line.

public Form1()
        {
            InitializeComponent();
            this.Text = "My First Windows Application";
            this.Size = new Size(300, 300);
            Label lblGreeting = new Label();
            lblGreeting.Text = "Hello …
JerryShaw 46 Posting Pro in Training

As LizR said, binding is the best approach, however you can manually locate the Customer in the table and populate the address text box.

string custName = combobox.Text;
DataRow[] addressInfo = custData.Select(string.Format("Customer='{0}'",custName));
if(addressInfo.Length > 0)
{
    edStreet.Text = (string)addressInfo[0]["Street"];
    edCity.Text = (string)addressInfo[0]["City"];
    // and so on...
}

Hope this helps,
Jerry

JerryShaw 46 Posting Pro in Training
char[] space = new char[1] { ' ' };
Console.WriteLine("Enter in numbers");
int nAnswer;
string[] answer = Console.ReadLine().Split(space
           ,StringSplitOptions.RemoveEmptyEntries);
                
List<int> myArray = new List<int>();
foreach(string str in answer)
     if( Int32.TryParse(str,out nAnswer) )
                    myArray.Add(nAnswer);

// Your answer can be pulled from the list using:
int[] result = myArray.ToArray();
JerryShaw 46 Posting Pro in Training

Okay, I will see if I can be of help.
First, I am not a fan of Access databases, I am primarily an SQL guy, but the concepts are the same.

Some definitions need to be explored. When you say "form" are you referring to a DataGridView on a WinForm ?

When you say null out the last three columns of the un selected (non populated) columns ? Do you intend to get rid of (make invisible) the rows that do not have a value in these three columns ? and at what time does this happen (button click event somewhere on the form) ?

I assume by some of your comments that you are using the IDE to create your data access layer class (DAL). The IDE (IMO) performs a horrible job of it, and is typically more of a stumbling block than helpful for new developers.

Lets look at your requirements:
The application I would like to complete does the following things.
-Take user input and use it to query a large table and return a smaller table that will be used as a form.
-Allow user to edit this form
-Remove null values left after user edits the form
-Store & print the completed form

Getting the data into the grid is pretty simple. DataSet with a bindingSource and a DataGridView... I take it that you have this much done so far. Editing the Grid depends …

JerryShaw 46 Posting Pro in Training

Or simply post the variables in the constructor.
// Jerry

JerryShaw 46 Posting Pro in Training

Been a long time since I was on this board... Just viewed your question by accident.
Ok, one thing to always remember when dealing with images, or icons is they are always stored as an array of byte. Therefore, you would store the byte array in the XML file, and pull it out as a byte array, then load it into your menu icon property.

Let me know if this helps. If you get stuck, maybe I can whip up a short example.

// Jerry

JerryShaw 46 Posting Pro in Training

Make sure your catalog is set to the correct database. Currently it is set to master which is the primary system database.

JerryShaw 46 Posting Pro in Training

Your c# code appears to be correct. The ExecuteNonQuery method returns an int value on the success or failure of the transaction. I suggest that you inspect the return value. If it is a zero (0) then the SQL Server processed your request without error.

I would also suggest that you do not specify the type when you add a parameter. Let ADO figure that out for you at run time. If you ever need to change a parameter type in the stored procedure, you will have to update your SQL code to match. This can be avoided by letting ADO manage the type for you.

Last suggestion, Use Parameter.AddWithValue to streamline your assignments.

Good Luck

JerryShaw 46 Posting Pro in Training

yes it does exactly that:
Below is a short version. In my production environment, it takes a parameter called an "Alias" that lets the method fetch additional information from configuration for building the connection string such as Windows or SQL authentication, the server and database names, user and password information.

This short version should help you.

public static SqlConnection GetSqlConnection()
{
    string connectionString = string.Format("Data Source={0};Initial Catalog={1};Integrated Security=True",serverName,catalogName);

    return new SqlConnection(connectionString);
}
JerryShaw 46 Posting Pro in Training

Elmo,

Let me share with you (and others viewing) a better way to manage SQL procedure calls.
I have a Data Access Layer (DAL) static class that is full of little helper methods like the one below. Using this approach will make your code cleaner, more compact, and less buggy, and well... life a little easier.

Let dotNet do the work for you when possible.
Add this method, if you do not have a static class, then just remove the static assignment, and you can work on that aspect later.

// Note: GetSqlConnection simply returns my connection string.
public static void ExecuteNonQueryStoredProcedure(string ProcedureName, params SqlParameter[] values)
        {
            SqlConnection conn = GetSqlConnection();
            SqlCommand cmd = new SqlCommand(ProcedureName, conn);
            cmd.CommandTimeout = 60;
            cmd.CommandType = CommandType.StoredProcedure;
            if (values != null && values.Length > 0)
                cmd.Parameters.AddRange(values);
            try
            {
                conn.Open();
                cmd.ExecuteNonQuery();
            }
            finally // NO CATCH ON PURPOSE, want the error to escelate
            {
                conn.Close();
                conn.Dispose();
            }
        }

To use this method I use this format

try
{

  ExecuteNonQueryStoredProcedure("CreateCustomer", 
     new SqlParameter("@companyName", txt_CompanyName.Text) ,
     new SqlParameter("@forename", txt_ContactForename.Text) ,
     new SqlParameter("@surname", txt_ContactSurname.Text) ,
     new SqlParameter("@phoneNo", txt_PhoneNo.Text) ,
     new SqlParameter("@mobileNo", txt_MobileNo.Text) ,
     new SqlParameter("@altNo", txt_AlternativeNo.Text)    );
}
catch (SqlException eSql)
{
     // do something about it
}
catch (Exception e)
{
    // general catch
}

Much cleaner, and easier to debug. All the nitty gritty work is done the same way everyime in the Execute.... method. With that done, you can focus on your real objectives.

BTW: I didn't see anything …

JerryShaw 46 Posting Pro in Training

Okay - First I would suggest a change to the query

Instead of

Select ItemNumber from ItemsTable where CatagoryId = (Select CatagoryId From CatagoryTable Where Catagoryname=@CatgName

Make it:

Select i.ItemNumber from ItemsTable i 
JOIN CategoryTable c on i.CatagoryId=c.CatagoryId
where c.CatagoryName = @CatgName

To get the data into a dataset through a proc and adapter:

SqlConnection conn = new SqlConnection(<Your Connection String>);  
  SqlCommand cmd = new SqlCommand(<Procedure Name>, conn);
  cmd.CommandType = CommandType.StoredProcedure;
  cmd.Parameters.AddWithValue("@CatgName",<Your Cat Name>);
  SqlDataAdapter adapter = new SqlDataAdapter(cmd);
  adapter.Fill( <Your dataSet or dataTable>);

Hope this Helps
Jerry

JerryShaw 46 Posting Pro in Training

IsBackGround
Quote from Visual Studio 2008 on-line help
A thread is either a background thread or a foreground thread. Background threads are identical to foreground threads, except that background threads do not prevent a process from terminating. Once all foreground threads belonging to a process have terminated, the common language runtime ends the process. Any remaining background threads are stopped and do not complete.


My Info - a background thread is more forgiving than a foreground thread. The main application can not stop while any foreground threads are active. All background threads are automatically aborted when the main thread (the application) terminates.

JerryShaw 46 Posting Pro in Training

True, using INI files in dotNet applications is considered a security risk by Microsoft, and I no longer use them myself, but there is a need for them in Legacy replacements. I posted an ini class up on DaniWeb a long time ago. You should still be able to find it, if not, give me a message, and I will repost it.

On the subject of the built in Configuration of dotNet, there are some gotchas to be aware of.
1) If you use versioning software, the configuration is reset to its defaults each time the file is versioned. IOW your user loses any settings they set in the configuration.

2) User configuration items are also lost each time you move the file to another directory.

3) Deleting the application does not remove the associated configuration file from the hard drive.

4) If you add a new setting (post delivery), you must perform update methods during installation to merge the new settings into the existing configuration. If you don't then the application will read the old configuration that is missing the new setting, and you get Exceptions. If this happens, find the config file in the local settings, and delete it, or manually edit it, or deploy an application that can fix it.

5) Vista uses a different file extension for the configuration file than XP.

// Jerry

JerryShaw 46 Posting Pro in Training

When dealing with threads, consider the timing involved. The Start() is an invocation and not a direct call to the target thread function.
Therefore, (in your example), the Main has had no interupts to prevent it from completing before the thread function begins.
If you were to cause the main to sleep for a couple milliseconds after the Start, it would allow the thread function to startup before the Main completed (eg interupt).

The the static assignment allows the function to invoke quickly (timing).
Just because it is static does not mean it will always startup in the desired order, again timing.

Add a using System.Threading, and after the Start() call, use Thread.Sleep(2) and you should find the desired results even if the thread function is not static.
You may also wish to set the thread's IsBackground property to true before it is started. This will help the thread to perform better outside the main thread activity.

Hope this helps..
Jerry

JerryShaw 46 Posting Pro in Training

I have an MDI application and I need the child form to know when it is docked in the MDI parent, or cascaded into its own form. Does anyone know if there an event or method of letting the child form determine this condition ?

Thanks in advance

JerryShaw 46 Posting Pro in Training

Is ProjectData.EndApp(); really needed ?
If e.cancel is left alone (not set to true), the program is going to close normally.
Doesn't EndApp() force an application termination disregarding any event assigned to Form_Closed ?

JerryShaw 46 Posting Pro in Training

string MyString = string.format("INSERT INTO tblUsers(userID, Name, Position)
VALUES('{0}','{1}','{2}'", txId.Text, txtUser.Text, txtPosition.Text );

JerryShaw 46 Posting Pro in Training

You forgot to assign the SqlConnection to your adapter.