kplcjl 17 Junior Poster

Your loop is entirely readable, understandable and isn't wrong. Just a warning about standard C# coding practices. Maybe this comes from arrays, where you declare the array [n] where n is the actual size of the array. Then you loop "for (i = 0; i < n ; i++) {...}".

I don't know why the community likes that style, but you see it all the time. One of the reasons I like it on 0 based initial loop values is that it exactly matches the number of loops being made, yet it still looks odd when you see j <= 12.

I don't know why, but some people really don't like to see "++j" instead of "j++" for the third parameter. Maybe they don't like to see ++ in front because it implies that that operation is done first and in a loop, that isn't the case.

kplcjl 17 Junior Poster

What I meant by "expensive query" is that you are executing functions. Each time you execute a function, it costs CPU, which means time and possibly money. Functions are handy, but if you can avoid them, do so. You don't have a where clause in your example, but if your query needs to do so, it increases the importance of finding a non"function" query. The group by clause increases the cost because it executes the function when it is calculating the group it goes into AND when it resolves the records. Here is an example table that removes the functions from the query by calculating them in a very short table.
You join this table with your query on regdate between stdate and endate and group your records by the fields in this table. Here is how to produce the table:

DECLARE @Years TABLE([Year] smallint,[Month] tinyint, inmonth char(3), stdate datetime, endate datetime)
DECLARE @styr DATETIME = '19900101', @enyr DATETIME = '19910101',@cnt tinyint = 1
WHILE @styr < @enyr
BEGIN
	INSERT @Years SELECT YEAR(@styr),MONTH(@styr), CONVERT(VARCHAR(3),@styr,100), @styr,DATEADD(millisecond,-3,DATEADD(MONTH,1,@styr))
	SET @styr=DATEADD(MONTH,1,@styr)
END
SET @styr='19900101'
WHILE DATEADD(YEAR,@cnt,@styr) < GETDATE()
BEGIN
	INSERT @Years
		SELECT [Year]+@cnt,[Month], inmonth, DATEADD(YEAR,@cnt,stdate),DATEADD(YEAR,@cnt,endate)
		FROM @Years where stdate between @styr and @enyr-1
	SET @cnt=@cnt+1
END
UPDATE @Years SET endate = DATEADD(MILLISECOND,-3,DATEADD(MONTH,1,stdate))
WHERE Month = 2
SELECT * FROM @Years y
ORDER BY Month, Year
kplcjl 17 Junior Poster

What, besides the comma that goes nowhere right after insumpo? Or the variable (invcount) that doesn't exist in the commented section? Or that you can't do derived calculations in an aggregate query? Or that this is an egregiously expensive query on a big table? Or you could get divide by zero errors?

Why, nothing at all!

declare @inv table(regdate datetime,amt real,nbr varchar(10))
insert into @inv
values(GETDATE()-100,10.3,''),(GETDATE()-100,5.3,'x'),(GETDATE()-300,10.3,''),(GETDATE()-100,100.3,'x'),(GETDATE()-101,10.3,'4')
select *,cast(case when InSum != 0 then (Insumpo / InSum ) else null end as decimal (20,4)) as sp,
CAST(case when incountpo != 0 then (incountpo/incountpo) else null end as decimal(20,4))as tp from 
	(select year(regdate) as [Year],month(regdate) as [Month],
	CONVERT(varchar(3),regdate,100)as inmonth,
	count(*) as incount, cast(sum(amt)as decimal(20,2))as insum,
	count(case when nbr <>' ' then amt else Null end) as incountpo,
	SUM(case when nbr <>' ' then (amt)else 0.00 end)as insumpo
	from @inv
	group by year(regdate), month(regdate),CONVERT(varchar(3),regdate,100)) x
kplcjl 17 Junior Poster

OK SQL documentation sucks. I know that, I've known that for years, but it can be helpful and useful at times, so I use it. I thought I remembered correctly what "~" did, but looked it up anyway. I'm reading the usual @#$%, but getting the basic information (While thinking "You have no idea what you are talking about.") then read something flat out wrong.

Is there any place where we can ask Microsoft to fix their documentation some time in the future that won't land in the bit bucket?

What's wrong? Besides all the various statements about it being a signed integer, their binary(2) bit patterns, they said ~170 evaluates to -170. If we used 1's comp machines that would be correct, but all the machines currently manufactured that I know about uses 2's comp and ~170 evaluates to -171. For any signed integer number @n that is not null, this evaluates as true:
if(~@n=-1-@n)...

Also, ~170 will also evaluate as 85 or 1:

declare @i tinyint = 170,@b bit=~170,@bi bigint = 5000000000000
select ~@i,@b,cast(321.345 as BINARY(4)),cast(321 as BINARY(4)),~@bi
kplcjl 17 Junior Poster

Permalink came up with the basic problem of your description. It tells you what you want to do, but not what you are doing. You say it's not being stored on the database. So how are you storing your registration information? Does each session store it's own data table with it's own psudo identity field? Of course it would generate the same id, you've got the dats stored in separate areas and they would both start with the same psudo id #.
Are you storing everyone's information in the application level? If so, is your psudo id set up to increment properly? Are you adding a new row because the registration info is different? If so, have you added two rows and verified it is imcrementing OK?
Anyway, this doesn't sound like a DB problem, but an asp.net problem.

kplcjl 17 Junior Poster

The point isn't to avoid using functions at all, just don't use them in the query.

DECLARE @dt1 datetime = CAST(DATEPART(YEAR,GETDATE()) AS CHAR(4))+'0101'
DECLARE @dt2 datetime = DATEADD(YEAR,1,@dt1)
-- You now have a range of dates for the current year in variables that remain constant in the query.
...WHERE DateOfInterest BETWEEN @dt1 AND @dt2
kplcjl 17 Junior Poster

I don’t have a problem, but sometimes I just love the way this system works.
I got the message {"Cannot convert object of type 'System.Int64' to object of type 'System.Data.SqlTypes.SqlInt32'."} {System.Data.DataException}

This was the command
System.Data.DataRow dr_Test0 = this.XML_DataSet.Tables[0].NewRow();

I also love how they obfuscate code. Finding the designer code:
private System.Data.DataSet XML_DataSet;
this.XML_DataSet = new System.Data.DataSet();
this.XML_DataSet.Tables.AddRange(new System.Data.DataTable[] {this.tbl_Test,//more tables}

this.tbl_Test = new System.Data.DataTable();
...
this.tbl_Test.Columns.AddRange(new System.Data.DataColumn[] {this.dataColumn1,//5 more columns}

The first data column definition:

this.dataColumn1.AllowDBNull = false;
this.dataColumn1.AutoIncrement = true;
this.dataColumn1.AutoIncrementStep = ((long)(-1));
this.dataColumn1.ColumnName = "TestID";
this.dataColumn1.DataType = typeof(System.Data.SqlTypes.SqlInt32);

AH HA! Because I asked it to be auto incrementing, I have to use long/Int64 for the field. The code of course doesn't know anything about the valid types while forcing a cast to long. And the only way I see the problem is because of a cast to long and I find the problem because of a runtime error. (AND NOT when I create the row, but when I try to get a copy of the row.)
Never mind I'll never produce over 2 billion rows of memory. (or that, I'm pretty sure 2 billion rows would wipe out my 4GB of virtual memory.)
Never mind I could probably declare the SQL server's identity field as small int and never blow up.

kplcjl 17 Junior Poster

Sailor_Jerry; You can use a label, you can set the TextBox "ReadOnly" property to true so it acts like a label, you can use the method Mahmoud suggested. There are a multitude of options available, all that is required is that you have the ability to read. Failing that, I fail to see how anyone can help you.

kplcjl 17 Junior Poster

can another way through which UI thread remain running

You will never, ever, see a form respond to a form change while the form's thread is active. The form thread MUST be idle, for changes to be returned to the form's thread to act on them. The timer solution works because it is a delegate running independently of your form thread. (There is a bug in the given logic "if (++i > 199)" will stop at 199 just like your loop.) If you want the user to be unable to do anything until the count is finished, then use his first solution. If you want another way, this will work, but I bet you like it less than the timer solution.

1. Create a routine to handle updating of your label from the passed information.
2. Create a small class that has a delegate routine. A looping routine.
3. Assign your form routine to your delegate.
4. start the looping routine in a new thread.
5. In the loop call the delegate and then Sleep. Forget the Refresh, you don't need it.

PS. I have a combo box that picks between 10, 5, 1, 0.1, 0.5, 0.05, 0.01, and 0.0 convert that to an integer a 1000 times bigger and sleeps for that time. (I sleep for a maximum of 500 and increment up to the set time when it is bigger than that. When you sleep for 10 seconds, it is agonizing to …

kplcjl 17 Junior Poster

I'm having a problem with starting with KeyPress event. The program is derecting me to the TextChanged event. How to change it to the KeyPress event.

I'm sure the purists are howling, but I say Keep the TextChanged event. use
if (!int.TryParse(My_tbx.Text, out i) {//Error handling block } where "i" is int.

You can do this with any numeric type.

You may want to check for negative numbers or see how uint handles negative numbers.

PS I personally hate the new Daniweb. It has so far thrown me out 3 times and I've resorted to using notepad so I can keep what I've typed when it throws me out again.

kplcjl 17 Junior Poster

Following query will give you all records that are in A, whenever b.flag is 'Y' it will show 'Y' other wise it will show null. You may still apply where clause at the end of query to filter your records.

SELECT a.*, case when b.flag='Y' then b.FLAG ELSE NULL END FLAG FROM A LEFT JOIN B ON A.ID=B.FK_ID_A

Correct process, but I'm confused. Do you want all A records or only where A.status="active"? If all why did you bring up the active part in the original post?

kplcjl 17 Junior Poster

Table1 has clustered PK A, 2 has clustered PK [A,B] and has a foreign key to table1. Both A and B are uniqueidentifiers and when table2 adds a record, B is always set to newid() so B is unique in table2. For each A value, there aren't more than 100 B values and generally less than 20 B values. Access comes from one A value in table1 to retreive all matching A values in table2. Anyway I was told A was a covering index value in table2. The structure makes very good sense, but after getting a different definition of what a covering index is, I looked it up on the web and the first description I heard isn't correct. So what IS this kind of structure called?

kplcjl 17 Junior Poster

1 question: why do you take away 65? Sorry for asking this but I am just a beginner programmer

A character field is just a couple (or four) of bytes of information. You can implicitly cast this Char field to int, which is what adapost did. ASCII is a coding standard that defines a single byte that can be used for almost all characters in the English language and is the standard format used when international characters aren't in use.
If you cast "A" to int, it will be 65. Every letter from A to Z are incrementally represented in alphabetical order from 65 to 90 in the ASCII format. You subtract 65, you get an alphabetical indexed location from 0 to 25 for the 26 letters.

kplcjl 17 Junior Poster

This is a modified version of the "about PrintDocument" example in the VS help. I couldn't find anything that told me the graphical width of a character. If you don't modify it, any line longer than the width of the page will disappear off the edge of the page. It will disappear off the bottom of the page if one line is long enough to extend past the end of the page unless you modify it further.
It's also modified to include all the using statements you may not need, but I did.
Anyway printing isn't easy, you have to think in graphical terms while producing your printout.
Also fix the ("C:\\...\\My Documents\\Example.txt"); line to point to the real text file to be printed.

using System;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
public class PrintingExample : System.Windows.Forms.Form 
{
    #region types
    private System.ComponentModel.Container components;
    private System.Windows.Forms.Button printButton;
    private Font printFont;
    private StreamReader streamToPrint;
    #endregion
    public PrintingExample() : base() 
   {
      // The Windows Forms Designer requires the following call.
      InitializeComponent();
   }
   // The Click event is raised when the user clicks the Print button.
   private void printButton_Click(object sender, EventArgs e) 
   {
      try 
      {
          streamToPrint = new StreamReader
             ("C:\\...\\My Documents\\Example.txt");
          try 
          {
             printFont = new Font("Courier New", 10);
             PrintDocument pd = new PrintDocument();
             pd.PrintPage += new PrintPageEventHandler
                (this.pd_PrintPage);
             pd.Print();
          }  
          finally 
          {
             streamToPrint.Close();
          }
      }  
      catch(Exception ex) 
      {
          MessageBox.Show(ex.Message);
      }
   }
   // The PrintPage event is raised for each page to be printed.
   private void pd_PrintPage(object sender, …
kplcjl 17 Junior Poster

PS "hit the text books" could include reading on-line help. It is much more helpful (to me) to buy a text book and see good examples.

kplcjl 17 Junior Poster

Printing is more complex than just saying "Please print my form." You need to hit the text books. Short form - create a System.Drawing.Printing.PrintDocument instance. You handle the PrintPage, BeginPrint, PrintPage, and EndPrint events to create the print image and send it to the printer.
Huh? Wha? Again, hit the text books.

Well, have you looked up the above print document object? Have you looked up these events? Do you understand what they tell you?

kplcjl 17 Junior Poster

It doesn't really matter, but why did you make "time" static?

kplcjl 17 Junior Poster

Did you even read my comments?

Interesting. You've switched from rdr[7] to rdr[6]. Make up your mind.

Go back and CAREFULLY read what I said about casting. (At least now you aren't starting from Midnight.)

kplcjl 17 Junior Poster

Putting clear text passwords in databases is a newbie security mistake. The original text sounded like it was from a newbie. I didn't intend to sound condescending, thought it might be of interest to someone just starting out to also think about how secure their information is. They always have the right to say nothing, tell me "Don't teach your grandmother how to suck eggs!" or "Thanks for the input."

kplcjl 17 Junior Poster

Passwords in a database in clear text is a bad idea, some encryption method should be used. The simplest method is to define a binary(16) password and store the MD5 conversion of the password. You'll never decrypt the password so the user will have to have a way of resetting his password if he forgets.
The alternate is to use an encrypt/decrypt method using a fixed password (Not a good method.) or the user's password (Anything encrypted using the user's password is lost for good if the password is lost.)
If you go with the MD5 method, you might want to encrypt other sensitive data using both the fixed password and the MD5 saved value as a combination.

kplcjl 17 Junior Poster

Printing is more complex than just saying "Please print my form." You need to hit the text books. Short form - create a System.Drawing.Printing.PrintDocument instance. You handle the PrintPage, BeginPrint, PrintPage, and EndPrint events to create the print image and send it to the printer.
Huh? Wha? Again, hit the text books.

kplcjl 17 Junior Poster

>it casted the timespan asd but it gives me more errors, can anyone please help me?
Maybe you should look at your monitor through a mirror, because you seem to be naturally backwards.

Well, at times I can't help being sarcastic, but I certainly have to take a back seat to you. You would think a code goddess would know mere mortals can't know everything and give them a break. (Yes, I know its funny watching puny creatures fall down and go boom. Still, isn't it better to get them standing, so they'll fall from a better height?)

Narue commented: Oh my god, go get yourself a sense of humor. -4
kplcjl 17 Junior Poster

PS Might you want to bypass the loop completely?

for (int i = 0; i < rdr.FieldCount && iftrue; i++)
kplcjl 17 Junior Poster

Hi i have a problem Error 1 Operator '<' cannot be applied to operands of type 'object' and 'System.TimeSpan'. to use timespan with < is there any type of code?

SqlCommand cmd = new SqlCommand("SELECT * FROM tblBooking", conn);
            SqlDataReader rdr = cmd.ExecuteReader();         
            DateTime ts = new DateTime();
            TimeSpan asd = ts.TimeOfDay;
            while (rdr.Read())
            {
                int x = Booking.noOfpersons;
                
                for (int i = 0; i < rdr.FieldCount; i++)
                {
                     if (rdr[7] < asd)
                    {
                        iftrue = true;
                    }
             }

What are you trying to do?
1. If you are intentionally trying to set "asd" to zero, why don't you set it to zero. (ts is midnight of day 0)
Did you really intend "DateTime ts = DateTime.Now();" to get the current time?
2. "if (rdr[7] < asd)" does not belong inside of "for (int i = 0; i < rdr.FieldCount; i++)" because it is a constant comparison which only needs to be executed once.
3. Is the eighth field of the table a time span or a date type?

How about?

SqlCommand cmd = new SqlCommand("SELECT * FROM tblBooking", conn);
            SqlDataReader rdr = cmd.ExecuteReader();         
            DateTime ts = DateTime.Now();
            TimeSpan asd = ts.TimeOfDay;
            while (rdr.Read())
            {
                int x = Booking.noOfpersons;
                ts = (DateTime) rdr[7];//I'm assuming you don't need the current time anymore in DateTime format
                TimeSpan asd2 = ts.TimeOfDay;
                if (asd2 < asd) iftrue = true;
                
                for (int i = 0; i < rdr.FieldCount; i++)
                {
                    //Do whatever valid reason you have for looping here. …
kplcjl 17 Junior Poster

FYI You have public static bool stopped = false;
being set to true by an instance. Note that if you have multiple instances, this would be set to true in one instance where another instance could still be running. You might want to set that as an instance get property and a private bool so no-one else can muck with it. If you have multiple instances then you could wait for the final move to finish before you exit.

kplcjl 17 Junior Poster

If your problem is solved you should mark it solved.

An alternate is to put an if statement in your move loop.

if (!Stopping) File.Move(s.FullName, TargetFile);

It would finish the last move of files and then just loop through everything without doing additional work and then leave. Since you have a try block, before the loop you could declare:

int zero = 0;

and after the move and still in the loop

if (Stopping) zero = 1/zero; //Intentionally aborting the loop

Not sure what stopping a thread in the middle of a move would do. (Purists would have you throw an exception instead of intentionally blowing up.)

kplcjl 17 Junior Poster

Hey guys,

I need a little help this is what I currently have:

Object[][] teamList = new Object[10][];
Label[] tlKnights = new Label[25];
Label[] tlSkullitz = new Label[25];

teamList[0] = tlKnights;
teamList[1] = tlSkullitz;

snip

For a two dimensional array solution:

Label[,] teamList = new Label[10,25];
teamList[0,0] = ...;//first label setup for tlKnights
teamList[1,0] = ...;//first label setup for tlSkullitz

Either you know the first number = 0 is for the tlKnights label and = 1 is for tlSkullitz and you never reference those objects or add

string[] teamNames= new string[10];
teamNames[0] = 'tlKnights';
teamNames[1] = 'tlSkullitz';

and now you can dynamically change the team names if a team decided they wanted to rename what to call their team. Again, objects tlKnights and tlSkullitz don't exist.
Also, is there any reason why you are using labels to store your data when a string array will work with what has been shown and would use less space?

kplcjl 17 Junior Poster

Hmmm, not only easier to read, but I started to second guess myself and thought I'd made a mistake in the first line's set of parenthesis

MyLbl.Text = ((Label[]) teamList[0])[0].Text;

Re-reading it, I'm thinking it's right again. (Label[]) teamList[0] cast the first object back to a Label array. The parenthesis around that allows you to point to an item in the array "(...)[0]" and then the property is just part of that one Label.

kplcjl 17 Junior Poster

It currently isn't jagged, you do know you could create a two dimensional array of labels?

kplcjl 17 Junior Poster

Hey guys,
snipped
So I've made an array of label Arrays and I'd like to be able to choose the label like this:

teamList[0][0].text

I'd like it to select the first label from the first list of label arrays so I can set the Name in the labels text value.
snipped

I'm assuming all these labels are not set up to display on your form and you want to transfer the label data to a label that is displayed.
I haven't tested it but this should work:

MyLbl.Text = ((Label[]) teamList[0])[0].Text;

Splitting it out a bit:

Label[] jnk = (Label[]) teamList[0];//Cast the object as a Label array
MyLbl.Text = jnk[0].Text;// Transfer the text to an object that is displayed

Personally, I like the second version better. It's easier for me to read and I wrote it to begin with.

kplcjl 17 Junior Poster

You an use System.IO.File.GetCreationTime(filename) to get when a particular file was created. Compare that to today's date and delete as necessary. You can then open a file with append access via a StreamWriter to write to a file. If the file exists, it will merely be appended to. If not, it will be created. Sample below.

string filename = @"C:\yourfilepath_and_name.txt";
        DateTime fileDate = File.GetCreationTime(filename);

        if (fileDate.Date < DateTime.Now.Date)
        {
            File.Delete(filename);
        }

        StreamWriter writer = new StreamWriter(filename, true); // opens file for appending
        writer.WriteLine("write to the file");

        // finish processing, then close and dispose of object
        writer.Close();
        writer.Dispose();

Compile your code to an executable, create a scheduled task in your operating system, and off you go.

Wouldn't "if (fileDate < DateTime.Now.Date)" work as well?
Or "if (File.GetCreationTime(filename) < DateTime.Now.Date)"?

kplcjl 17 Junior Poster

By removing the virtual and override lines I also wanted to point out
in

mn.BirthDate = new DateTime(2007, 9, 21);
        hmn.BirthDate = new DateTime(2008, 9, 21);

mn.BirthDate would always return 1/1/1800 no matter what. because the set accessor doesn't do anything in Human and the source. I had to include set for virtual overrides to work, also if you reversed the process order, hmn.BirthDate = 9/21/2008 would remain the value assigned even if both were the same instance.

Whoops, my mistake. hmn.BirthDate would always return 1/1/1800 no matter what. Don't reverse the order. mn.BirthDate = 9/21/2007 would remain the value assigned even if both were the same instance.

kplcjl 17 Junior Poster

Whoops, forgot to mention without virtual, C# generates a warning that both classes have the same method defined and you should put new in your code to indicate it was an intentional duplicate.

kplcjl 17 Junior Poster

kplcjl, your quick quiz highlights some important issues relating to inheritance and reference types. But i think someone just setting out in c# might struggle to understand the 'why' of the answers if they manage to find them at all.
...

The Man object in the heap will have its BirthDate set first to 21/9/2007 then 21/9/2008 because both of the variables are pointing to the same object.
...
Lastly, by removing the virtual and override lines you are now hiding the method instead of overriding it. These are both ways to implement polymorphism.

By removing the virtual and override lines I also wanted to point out
in

mn.BirthDate = new DateTime(2007, 9, 21);
        hmn.BirthDate = new DateTime(2008, 9, 21);

mn.BirthDate would always return 1/1/1800 no matter what. because the set accessor doesn't do anything in Human and the source. I had to include set for virtual overrides to work, also if you reversed the process order, hmn.BirthDate = 9/21/2008 would remain the value assigned even if both were the same instance.

kplcjl 17 Junior Poster

Also, look at using int.TryParse rather than Parse. TryParse will copy the value to an output variable and returns a boolean value to show wether the parse succeeded. int.Parse will throw an exception if the user doesnt enter a valid number.

Console.WriteLine("Please enter which shipping method you want:");
            Console.WriteLine("Enter 1- for Standard shipping.");
            Console.WriteLine("Enter 2- for Express shipping.");
            Console.WriteLine("Enter 3- for Overnight shipping.");
while(!int.TryParse(Console.ReadLine(), out shipping_Speed)
{
            Console.WriteLine("Incorrect value. Please enter a number between 1 and 3:");
}
            Console.WriteLine("Thank you.");

Thank you, I have incorrectly maligned C# because it didn't do just what this does.

kplcjl 17 Junior Poster

Try:

total_Weight = 0;
            if (shipping_Type == 'a')
            {
                Console.WriteLine("How many items are to be shipped?");
                total_Items = int.Parse(Console.ReadLine());
                Console.WriteLine("Amount:" + total_Items.ToString());
            }
            else if (shipping_Type == 'b')
            {
                Console.WriteLine("How heavy is your package?(In pounds)");
                total_Weight = double.Parse(Console.ReadLine());
            }
            else Console.WriteLine("Shipping type is not correct:" + shipping_Type);
            Console.WriteLine("Thank you.");

in the one section that is totally messed up.
1. Alarms went off in my head when I didn't see "total_Weight" initiallized and I managed to hit code to blow up.
2. You ask for an A or B and then check if it is == 1. I believe that will cast char as byte and then see if it is 1. (It wouldn't be true even if you typed 1.)
3. C# is case sensitive and you check for 'a', convert entries to lower case so if someone follows your instructions it still checks out.
4. "total_Items = (int)(Console.Read());" blows up on my machine. For some reason it keeps on reading until a newline is hit. I'm not sure what is going on because it doesn't produce an exception message but it won't execute the debug line I entered after it. (I'm using csc to compile the code because my VS doesn't support C#. I don't know how to create breaaklines in command line mode so, I wrote the poor man's debugger line.It didn't print probably because I was adding a null value)
3. Note that I added a new else at the end. …

kplcjl 17 Junior Poster

Sorry, about my last comment. On a serious note: As a newbie, you really should learn how to debug code. Insert a breakpoint and walk through your code. Use the watch windows to see what is happening. If you need to, get someone to show you how to do this.

kplcjl 17 Junior Poster

why the heck you created a console app?

Also, he did say the code sucked.

kplcjl 17 Junior Poster

Too true, but that was the original example. Have you seen any textbooks that don't give inane examples of inheritance?

Oh yea, my example requires that you instantiate human with an indication whether it is male or female and requires a birthdate. "Human x = new Human();" would blow up. If you provide a new birthdate "Human x = new Human("x",new new DateTime(2009, 9, 21));" you'd have a female that is NOT a Woman and you could NEVER change the original birth date. I didn't apply logic to keep a minimum age of 13 or older but that could be done. The hassle is that if you wanted a Woman class you'd almost have to copy the Man class to have a settable date. This is really poor design, even when I wrote the example. Man, I AM an inane "Textbook" example!

kplcjl 17 Junior Poster

On that note, the Man : Human or Woman : Human really isn't that great of an example because gender could easily be distinguished by a property, there's no reason to split the genders into sibling classes. ...

Too true, but that was the original example. Have you seen any textbooks that don't give inane examples of inheritance?

kplcjl 17 Junior Poster

Quick quiz: Given

public class Human
{
    public string name {get;set;}
    private DateTime Dbirthdate;
    private bool Disfemale;
    public bool IsFemale{get{return Disfemale;}}
    public virtual DateTime BirthDate { get { return Dbirthdate; } set { return; } }
    public Human(string MorF, DateTime Birth ){
        this.Dbirthdate = Birth;
        if (MorF.ToUpper() == "M") Disfemale = false;
        else Disfemale = true;
        name="Unknown";
    }
    public Human(string MorF, DateTime Birth, string givenname)
    {
        this.Dbirthdate = Birth;
        if (MorF.ToUpper() == "M") Disfemale = false;
        else Disfemale = true;
        name = givenname;
    }
}
public class Man : Human {
    private DateTime Mbirthdate;
    public Man()
        : base("M", new DateTime(1800, 1, 1))
    {
        //Default could be set to 21 years old DateTime.Now.AddYears(-21)) or 
        //REALLY old. Too bad for a historical figure. If dead is it still a Man?
        Mbirthdate = DateTime.Now.AddYears(-21);
    }
    public override DateTime BirthDate { get { return Mbirthdate; } set { Mbirthdate = value; } }
}

And in your main code:

Man mn = new Man();
        Human hmn = mn;
        mn.BirthDate = new DateTime(2007, 9, 21);
        hmn.BirthDate = new DateTime(2008, 9, 21);

What years are in hmn.BirthDate and mn.BirthDate?
change

Human hmn = mn;

to

Human hmn = new Man();

Same question.
change

...
public virtual DateTime BirthDate { get { return Dbirthdate; } set { return; } }
...
public override DateTime BirthDate { get { return Mbirthdate; } set { Mbirthdate = value; } }
...

to

...
public DateTime BirthDate { get { return Dbirthdate; …
kplcjl 17 Junior Poster

sorry - I read this wrong - I thought you wrote: It's not COMMON (I left out the "UN") but I was talking about instantiating a class this way not inheritance.

I am obviously very new to this stuff and struggling to learn. Hopefully it will click as I persist...
I appreciate your examples and your time. All very helpful..

It wasn't my comment, but it is a sentiment I agree with. (not uncommon, a double negative, that's bad English because it leads to misunderstandings like yours, but the sentiment was clear to me because this term is unfortunately common.)
When you code, you model. The human model is a common one used in examples because everyone understands it. It's also a great example because the model changes over time. When I was born, if you were male and adult, you had to be a Man. Today, it's not that obvious. It's not obvious to me that someone born male is still male. It is obvious to me that someone born male can be a Woman. Every criteria that you can use to prove is still male can also be used to prove people born female aren't female, so they must be male. How you implement the model is the trick.

kplcjl 17 Junior Poster

okay - thanks guys. So it seems like it's not done this way often...
I just thought I saw this a few times like in the above example..also with an interface example although I couldn't find that particular example.

OK, I missed it. What isn't done often? Inheritance? Something that is almost impossible to code well, an app that doesn't use inheritance, isn't done too often?
An interface is a special type of inheritance, you can't create an interface, but you can have an object that is an interface. The interface guarantees that certain methods do exist in any object that is an interface.
All of this has to do with casting. An example of implicit casting is:

Human h2 = new Man();

This explicit cast does the same thing:

Human h2 = (Human) new Man();

This is an integral concept of OO design.
When you do event processing in windows for example, one of the parameters passed is an Object. Depending on what you are doing, you can ignore it or do something with it, it's your choice. You don't have a choice of not supplying the Object in the parameter list of a Form event because the Form class insists it is passed.

kplcjl 17 Junior Poster

Human h2 = new Man();
this Man class reference will be created and Human class object will be created and we can call h2.ManMethod().

That's true, but intelisense won't detect that "ManMethod" is a valid method. If you said

Human h2 = new Woman();
h2.ManMethod();

It would compile, then blow up with an exception. Don't do this unless you are absolutely sure that the method exists.
This is also related to casting as well

byte[,] nms = (byte[,]) Numbrs.SaveFinalNmbrs[i];

is an example of one of my lines of code. SaveFinalNmbrs is an ArrayList, so it only contains the Object type. You HAVE to cast it for this code to work. The = new Man() works without casting because the code understands they are both Human. You can put it into the ArrayList without casting because whatever you have defined, it is an Object. You can't do Man h2 = new Human(); because a Human isn't a Man. I'm sure that would compile if you cast it as a Man, but I'm pretty sure your code would blow up the second it tries to execute that line.
When you create a windows app, how much coding to you do to paint the windows form? Resize it by dragging a side? None, right? that's because your app is a System.Windows.Forms.Form and you automatically inherit all that functionality.

kplcjl 17 Junior Poster

I don't understand. You have a datagrid that is displaying data. To do that you need to bind a dataset to it. In order to have data in a dataset, it must have one or more datatables in it, to store your data.
Why don't you trace the code generated for you to find the datatables that are already there?

kplcjl 17 Junior Poster

Its not supported but it still works. MS dont formally support any server products on home editions. It says the same on Visual Studio pro 2003 but that works fine on XP Home (Apart from ASP, obviously, because home doesnt have IIS). Same for VirtualPC. Install that on home and it gives you a warning but works fine.

But yeah, 2008 should work fine. Ive got SQL 2008 Developer (which is basically pro i think) off DreamSpark (MSDN for Students) and it installed and run perfectly on Vista Home Premium.

Well, I tried it because I know there is a lot of software that isn't supported, but still works. Not this one. Trying to upgrade SQL 2005 failed. (I suspect because it was the Express version.) Trying to install fresh failed after I removed all the SQL 2005 apps.

kplcjl 17 Junior Poster

I don't know of any way to control one object in the form that way. You can make the box's background totally transparent using the form's TransparencyKey property. I know that isn't what you asked for.

kplcjl 17 Junior Poster

I purchased a book that included an evaluation version of 2008 enterprise. I had downloaded SQL 2005 express and had tried to download 2008 which said it succeeded and I was left with 2005. I checked the OS list of supported ones. XP professional is on the list. XP home isn't. Without any expectation of succeeding, upgrading 2005 failed pretty quickly because it couldn't write to a dll file on my CD reader.
OK, uninstalled 2005, tried a fresh install of 2008. I got a lot further and spent a lot of time preparing the installation. It installed the programs but every one of them failed.
I went upstairs to a PC I totally hate, booted it up, saw I lost my virus protection, solved that by pulling my network cable, checked the OS (OK), drive space (barely OK), put the CD in... Nothing.
My CD drive isn't connecting with the computer.
AUUUGGG
OK, I don't expect help, I'm just venting. (and dreading the download time to install SQL 2005 express again.)

sknake commented: i hope some rep cheers you up +6
kplcjl 17 Junior Poster

So I am new to C#, and I am trying to to figure out what the problem is with my code. I know this works in VB.Net just not sure why it doesn't in C#

private Connection myConnection = new Connection();
        private SqlConnection mySqlConnection = new SqlConnection(myConnection.connectionString);

...

I'm surprised this works in VB.Net since you didn't define the connection string...(OK, I'm assuming you didn't supply that as part of the code.) If you are hard-coding the connection string, you should be able to create a static const string str = ""; and use that.
(It is better to use the constructor as suggested.)

kplcjl 17 Junior Poster

>What harm could making the bool variable public do?

Here is a blog, explaining some differences.Properties vs. Public Variables

SUMMARY:

  • Reflection works differently on variables vs. properties, so if you rely on reflection, it's easier to use all properties.
  • You can't databind against a variable.
  • Changing a variable to a property is a breaking change.

Thank you. Very informative and useless information mixed indescriminatly. (Slight disagreement with the author, but the comments!)
"Automatic properties" - a feature added to C# I wasn't aware of and simplifies property implementation.
I thought of another reason. XML documentation. Any way to do that for a variable?