Welcome to Dream.In.Code
Getting C# Help is Easy!

Join 136,423 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 2,338 people online right now. Registration is fast and FREE... Join Now!




Creating and using functions

 
Reply to this topicStart new topic

Creating and using functions

webwired
15 Oct, 2008 - 08:52 AM
Post #1

D.I.C Head
Group Icon

Joined: 26 Aug, 2007
Posts: 129



Thanked: 1 times
Dream Kudos: 100
My Contributions
Hi, I created a function in a class but seem to be having trouble using it...

The class file is TicketsQueries and here is the function that I am trying to use...
CODE

        public void InsertTicket(DateTime TicketDate, string TicketDescription, int TherapistID, int CustomerID, decimal TicketBillableTime, decimal TicketBillableRate, decimal TicketTotal, string TicketPaid, decimal TicketProfit)
        {
            string sSQL = "InsertTicket";
            SqlConnection cnInsertRecord = new SqlConnection(DataAccess.GetConnectionString("MPCS.Properties.Settings.MassageProConnectionString"));
            SqlCommand cmdInsertRecord = new SqlCommand();
            cmdInsertRecord.Parameters.Clear();
            cmdInsertRecord.CommandText = sSQL;
            cmdInsertRecord.CommandType = CommandType.StoredProcedure;
            cmdInsertRecord.Parameters.AddWithValue("@TicketDate", TicketDate);
            cmdInsertRecord.Parameters.AddWithValue("@TicketDescription", TicketDescription);
            cmdInsertRecord.Parameters.AddWithValue("@TherapistID", TherapistID);
            cmdInsertRecord.Parameters.AddWithValue("@CustomerID", CustomerID);
            cmdInsertRecord.Parameters.AddWithValue("@TicketBillableTime", TicketBillableTime);
            cmdInsertRecord.Parameters.AddWithValue("@TicketBillableRate", TicketBillableRate);
            cmdInsertRecord.Parameters.AddWithValue("@TicketTotal", TicketTotal);
            cmdInsertRecord.Parameters.AddWithValue("@TicketPaid", TicketPaid);
            cmdInsertRecord.Parameters.AddWithValue("@TicketProfit", TicketProfit);
            cmdInsertRecord.Connection = cnInsertRecord;
            DataAccess.HandleConnection(cnInsertRecord);
            cmdInsertRecord.ExecuteNonQuery();
        }

On my form I am calling it with this code...
CODE

TicketsQueries.InsertTicket(ticketDateTimePicker.Value, ticketDescriptionTextBox.Text, TID, CID, billedTime, billedRate, ticketTotal, ticketPaidComboBox.Text, ticketProfit);

But I am getting this error...
QUOTE

An object reference is required for the nonstatic field, method, or property 'MPCS.TicketsQueries.InsertTicket(System.DateTime, string, int, int, decimal, decimal, decimal, string, decimal)'


Can someone help me with what I am doing wrong, there are other functions in that class file that I am calling and they are working correctly...
User is offlineProfile CardPM
+Quote Post

PsychoCoder
RE: Creating And Using Functions
15 Oct, 2008 - 09:16 AM
Post #2

using DIC.Core;
Group Icon

Joined: 26 Jul, 2007
Posts: 8,993



Thanked: 125 times
Dream Kudos: 8625
Expert In: VB, VB.Net, C#, SQL, ASP, ASP.Net, Web Development, HTML, CSS, Win32 API, Javascript, mySQL, J#, Boo.Net

My Contributions
Since you class is not a static class you must create an instance of the class before calling any of the methods. Look at this example

csharp

//create an instance of your TicketsQueries class
TicketsQueries tickets = new TicketsQueries();

//now you can call your InsertTicket method using
//the instance you created in the first line
tickets.InsertTicket(ticketDateTimePicker.Value, ticketDescriptionTextBox.Text, TID, CID, billedTime, billedRate, ticketTotal, ticketPaidComboBox.Text, ticketProfit);


You could also make your class static (and all methods inside it would have to be static as well), like

csharp

//make your class static
public static class TicketsQueries
{
//now since your class is static so do the methods have to be static
public static void InsertTicket(DateTime TicketDate, string TicketDescription, int TherapistID, int CustomerID, decimal TicketBillableTime, decimal TicketBillableRate, decimal TicketTotal, string TicketPaid, decimal TicketProfit)
{
string sSQL = "InsertTicket";
SqlConnection cnInsertRecord = new SqlConnection(DataAccess.GetConnectionString("MPCS.Properties.Settings.MassageProConnectionString"));
SqlCommand cmdInsertRecord = new SqlCommand();
cmdInsertRecord.Parameters.Clear();
cmdInsertRecord.CommandText = sSQL;
cmdInsertRecord.CommandType = CommandType.StoredProcedure;
cmdInsertRecord.Parameters.AddWithValue("@TicketDate", TicketDate);
cmdInsertRecord.Parameters.AddWithValue("@TicketDescription", TicketDescription);
cmdInsertRecord.Parameters.AddWithValue("@TherapistID", TherapistID);
cmdInsertRecord.Parameters.AddWithValue("@CustomerID", CustomerID);
cmdInsertRecord.Parameters.AddWithValue("@TicketBillableTime", TicketBillableTime);
cmdInsertRecord.Parameters.AddWithValue("@TicketBillableRate", TicketBillableRate);
cmdInsertRecord.Parameters.AddWithValue("@TicketTotal", TicketTotal);
cmdInsertRecord.Parameters.AddWithValue("@TicketPaid", TicketPaid);
cmdInsertRecord.Parameters.AddWithValue("@TicketProfit", TicketProfit);
cmdInsertRecord.Connection = cnInsertRecord;
DataAccess.HandleConnection(cnInsertRecord);
cmdInsertRecord.ExecuteNonQuery();
}
}


Now that it's static you cal use it the way you have it now

csharp

TicketsQueries.InsertTicket(ticketDateTimePicker.Value, ticketDescriptionTextBox.Text, TID, CID, billedTime, billedRate, ticketTotal, ticketPaidComboBox.Text, ticketProfit);

Hope this helps smile.gif
User is online!Profile CardPM
+Quote Post

webwired
RE: Creating And Using Functions
15 Oct, 2008 - 09:29 AM
Post #3

D.I.C Head
Group Icon

Joined: 26 Aug, 2007
Posts: 129



Thanked: 1 times
Dream Kudos: 100
My Contributions
Yes, thank you, that helps alot, I have a better understanding of how classes and functions are accessed now...
User is offlineProfile CardPM
+Quote Post

wingot
RE: Creating And Using Functions
15 Oct, 2008 - 02:20 PM
Post #4

New D.I.C Head
*

Joined: 13 Oct, 2008
Posts: 38

Given the fact that you are passing in all of the parameters (i.e., They aren't already properties of the object) you could also have made just the method static, and still had the class as normal.

This is extremely handy when there is a function of the class that is not dependent on an instantiation of the class, but which can be called by anyone anywhere so long as the right information is provided (like this method).
User is offlineProfile CardPM
+Quote Post

webwired
RE: Creating And Using Functions
19 Oct, 2008 - 08:49 AM
Post #5

D.I.C Head
Group Icon

Joined: 26 Aug, 2007
Posts: 129



Thanked: 1 times
Dream Kudos: 100
My Contributions
Another question on the same topic... On the MainForm, I have a DataGrid being populated inside of a function, so that it can be called and populated/refreshed without having to repeat the entire code, it works fine if it is called from the MainForm, but how can I call it from another form, so that upon closing of the other form, it will refresh the DataGrid with the new entries that were inserted from the other form?

The MainForm...
CODE

namespace MPCS
{
    public partial class MainForm : Form
    {
        private void loadTicketsDataGrid(int CID)
        {
            ticketsDataGridView.DataSource = TicketsQueries.GetTicketsByCustomerID(CID);

            ticketsDataGridView.Columns[0].Name = "TicketID";
            ticketsDataGridView.Columns[0].DataPropertyName = "TicketID";
            ticketsDataGridView.Columns[0].Width = 5;
            ticketsDataGridView.Columns[0].HeaderText = "";
            ticketsDataGridView.Columns[0].Visible = false;

            ticketsDataGridView.Columns[1].Name = "TicketDate";
            ticketsDataGridView.Columns[1].DataPropertyName = "TicketDate";
            ticketsDataGridView.Columns[1].Width = 110;
            ticketsDataGridView.Columns[1].HeaderText = "Date";

            ticketsDataGridView.Columns[2].Name = "TicketDescription";
            ticketsDataGridView.Columns[2].DataPropertyName = "TicketDescription";
            ticketsDataGridView.Columns[2].Width = 200;
            ticketsDataGridView.Columns[2].HeaderText = "Description";

            ticketsDataGridView.Columns[3].Name = "TherapistID";
            ticketsDataGridView.Columns[3].DataPropertyName = "TherapistID";
            ticketsDataGridView.Columns[3].Width = 5;
            ticketsDataGridView.Columns[3].HeaderText = "";
            ticketsDataGridView.Columns[3].Visible = false;

            ticketsDataGridView.Columns[4].Name = "CustomerID";
            ticketsDataGridView.Columns[4].DataPropertyName = "CustomerID";
            ticketsDataGridView.Columns[4].Width = 5;
            ticketsDataGridView.Columns[4].HeaderText = "";
            ticketsDataGridView.Columns[4].Visible = false;

            ticketsDataGridView.Columns[5].Name = "TicketBillableTime";
            ticketsDataGridView.Columns[5].DataPropertyName = "TicketBillableTime";
            ticketsDataGridView.Columns[5].Width = 75;
            ticketsDataGridView.Columns[5].HeaderText = "Time";

            ticketsDataGridView.Columns[6].Name = "TicketBillableRate";
            ticketsDataGridView.Columns[6].DataPropertyName = "TicketBillableRate";
            ticketsDataGridView.Columns[6].Width = 75;
            ticketsDataGridView.Columns[6].HeaderText = "Rate";
            this.ticketsDataGridView.Columns[6].DefaultCellStyle.Format = "c";

            ticketsDataGridView.Columns[7].Name = "TicketTotal";
            ticketsDataGridView.Columns[7].DataPropertyName = "TicketTotal";
            ticketsDataGridView.Columns[7].Width = 75;
            ticketsDataGridView.Columns[7].HeaderText = "Total";
            this.ticketsDataGridView.Columns[7].DefaultCellStyle.Format = "c";

            ticketsDataGridView.Columns[8].Name = "TicketPaid";
            ticketsDataGridView.Columns[8].DataPropertyName = "TicketPaid";
            ticketsDataGridView.Columns[8].Width = 75;
            ticketsDataGridView.Columns[8].HeaderText = "Paid";

            ticketsDataGridView.Columns[9].Name = "TicketProfit";
            ticketsDataGridView.Columns[9].DataPropertyName = "TicketProfit";
            ticketsDataGridView.Columns[9].Width = 5;
            ticketsDataGridView.Columns[9].HeaderText = "";
            ticketsDataGridView.Columns[9].Visible = false;
        }
    }
}


The other form...
CODE

namespace MPCS
{
    public partial class AddTicketForm : Form
    {
        private void newTicketButton_Click(object sender, EventArgs e)
        {
            int errorTracker = 0;
            if (ticketDescriptionTextBox.Text == "")
            {
                MessageBox.Show("You must enter a description.");
                errorTracker += 1;
            }
            if (ticketBillableTimeTextBox.Text == "")
            {
                MessageBox.Show("You must enter the billable time.");
                errorTracker += 1;
            }
            if (ticketBillableRateTextBox.Text == "")
            {
                MessageBox.Show("You must enter the billable rate.");
                errorTracker += 1;
            }
            if (ticketPaidComboBox.Text == "")
            {
                MessageBox.Show("You must select whether or not the ticket was paid.");
                errorTracker += 1;
            }
            if (errorTracker == 0)
            {
                decimal ticketProfit = (ticketTotal * TherapistPercentage) / 100;
                TicketsQueries.InsertTicket(ticketDateTimePicker.Value, ticketDescriptionTextBox.Text, TID, CID, billedTime, billedRate, ticketTotal, ticketPaidComboBox.Text, ticketProfit);
                MainForm mForm = new MainForm();
                mForm.loadTicketsDataGrid(CID);
                this.Close();
            }
        }
    }
}


Notice on the other form that I use "mForm.loadTicketsDataGrid(CID);" to try and refresh the DataGrid prior to the closing of this form...

Now on the MainForm, I tried to use public static void for the function, but it gave a arm's length of errors... any ideas on how to accomplish this task?
User is offlineProfile CardPM
+Quote Post

Jayman
RE: Creating And Using Functions
19 Oct, 2008 - 10:35 AM
Post #6

Student of Life
Group Icon

Joined: 26 Dec, 2005
Posts: 6,939



Thanked: 42 times
Dream Kudos: 500
Expert In: C#, VB.NET, Java

My Contributions
Just make the method public, it does not need to be static.

CODE

public void loadTicketsDataGrid(int CID)

User is online!Profile CardPM
+Quote Post

webwired
RE: Creating And Using Functions
20 Oct, 2008 - 05:28 AM
Post #7

D.I.C Head
Group Icon

Joined: 26 Aug, 2007
Posts: 129



Thanked: 1 times
Dream Kudos: 100
My Contributions
Thanks jayman9, sure enough, that did it... Just when I told PsychoCoder I thought I had it down... LOL...

This post has been edited by webwired: 20 Oct, 2008 - 07:34 AM
User is offlineProfile CardPM
+Quote Post

wingot
RE: Creating And Using Functions
20 Oct, 2008 - 04:06 PM
Post #8

New D.I.C Head
*

Joined: 13 Oct, 2008
Posts: 38

Just to help your understanding, I'll give you a quick explanation of why you did one static and the other not.

With the first example you posted, this was for the method TicketQueries.InsertTicket(DateTime, string, int, int, decimal, decimal, decimal, string, decimal). Now, in this instance, the method was within the class TicketQueries, which was not being instantiated (i.e., You were not creating an instance of the class before calling the method). As it was not being instantiated, you were generating the error because the method was not static. As you found out, labelling the method with the "static" keyword allowed you to use it, and this is because the static keyword makes the method seperate from any instantiation (and makes it so that you can't even call the method on an instantiated object).

Your second problem needed to be non static because it is the other way around. You have an instance of MainForm (specifically, the form being shown on screen) and it is the value of this specific instantiation that you want to modify (there is no value in modifying a non-instantiated form's display values/datagrid details). As such, you needed to make the method non-static so that it is a method of the object itself rather than being something that can be called without instantiation.

If you don't understand the word instantiation or instances of classes then the above will not have made too much sense, but http://searchcio-midmarket.techtarget.com/...212355,00.html# appears to be a reasonable reference, if a bit wordy. To simplify, you would have a class named car, but your car is actually an instance of that car class, with it's own make, model, datagrid wink2.gif, completely seperate to my car instance which has it's own make, model, etc.

Effectively, static is similar to function libraries of old languages where you just call the method once. Most of the Math class is a good example, there would be no value of instantiating the Math class just to run the Sqrt method; instead you just call Math.Sqrt. As such, Sqrt is defined as a static method within the Math class.

Hope that helps to explain/clarify the issue with static methods.
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 12/2/08 01:18PM

Live C# Help!

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month