Mitja Bonca 557 Nearly a Posting Maven

Why you dont name the differently? This is a stupid idea. And i dont even know how your code works.
but anyway, you can loop through them and do:

protected override void OnShown(EventArgs e)
        {
            foreach (Control c in this.Controls)
            {
                if (c is DataGridView)
                {
                    DataGridView dgv = c as DataGridView;
                    dgv[0, 0].Selected = false;
                }
            }
        }
Mitja Bonca 557 Nearly a Posting Maven

This will do to deselect all:

protected override void OnShown(EventArgs e)
        {
            dataGridView1[0, 0].Selected = false;
            dataGridView2[0, 0].Selected = false;
            dataGridView3[0, 0].Selected = false;
        }
Mitja Bonca 557 Nearly a Posting Maven

This might help:

dataGridView1.Rows[0].Cells[0].Selected = false;
Mitja Bonca 557 Nearly a Posting Maven

This example requires that the code in the example is called from a form that has its IsMdiContainer property set to true.
That means that your MainForm has the property IsMdiContainer set to true;

//before creating a new instance of a Report class, do:
this.IsMdiContainer = true;
Report newMDIChile = new Report();
//and the rest of the code
Mitja Bonca 557 Nearly a Posting Maven

Yep
just to add to ddanbe post (how to practicaly do it):

string a = "10:12";
a = a.Replace(":", ".");
Mitja Bonca 557 Nearly a Posting Maven

Do you know that this line of code:

string strSource = webClient.DownloadString(URL);

will get the whole code of the website. So its almost impossible to compare this text with some other.
You will have to get some text out of that string.

Mitja Bonca 557 Nearly a Posting Maven

Use Linq:

string[] a = { "a", "b", "c" };
string[] b = { "b", "c", "d" };
string[] c = a.Intersect(b).ToArray();

Array c has values "b" and "c".

Mitja Bonca 557 Nearly a Posting Maven

Momerath, I can see you are pretty familiar with Regex. But Iam not. I would like to learn then more.
So I will ask right here. How to do (seperate) the regex, that will check for more conditions?
Is the seperator the backslash '\'? Or how would be the easiest way to combine it?

Mitja Bonca 557 Nearly a Posting Maven

I would even suggest you to create you own report (recommend Crystal Reports) and pass data (checked rows) to the report and show then here.

Mitja Bonca 557 Nearly a Posting Maven

You want to convert some value to double, which apparently is NOT a double. So to get rid if try, catch blocks and some strnage errors, you can use TryParse method in this manner:

double answer;
            if (sender is System.Windows.Forms.Button)
            {
                if (double.TryParse(answerBox.Text, out answer))
                    answer = Convert.ToDouble(answerBox.Text);
                else
                    MessageBox.Show("inserted value \"" + answer + "\" is not a number (type double)!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
Mitja Bonca 557 Nearly a Posting Maven

Code like Sort() method is completely bound by how fast you can get the data off the disk. The file simply can never fit in the file system cache so you're always waiting on the disk to supply the data. You're doing fairly well at 10 MB/sec, optimizing the code is never going to have a discernible effect.

Get a faster disk. Defrag the one you've got as an intermediate step.
And its the fault of yout system if it hangs up. It shouldnt.

-------------------------------------------------

There is another solution:
Short answer - load the data into a relational database eg Sql Express, create an index, and use a cursor based solution eg DataReader to read each record off and write it to disk.

-------------------------------------------------

If this would help you out you go ahead and do your own custom sorting algoritm. For info you can go HERE. But remember, you have to be good at math ;)

Mitja Bonca 557 Nearly a Posting Maven

If there is really alot of data, which will be a time consuming action, you can create a new thread (or use BackGroundWorker, which is a new thread too), and use Sort method:

string [] array = {"some values in array"};
Array.Sort(array);
Mitja Bonca 557 Nearly a Posting Maven

Glad to hear.
btw... if you are (partly) satisfied with the answer or you get any good idea from the post, you can up vote the post, or mark the thread as answered (so we close it up). Any anyone else who faces these kind of issues gets the solution earlier.
Thx in advance.

Mitja Bonca 557 Nearly a Posting Maven

Enabled property means that the control is accessabled (if set to true). If set to false its not in use (its like readonly).
try it.

Mitja Bonca 557 Nearly a Posting Maven

use Enable property (not ReadOnly):

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            textBox1.Enabled = false;
            textBox1.Text = "Some text";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Enabled = true;
            textBox1.Focus();
            textBox1.SelectionStart = 0;
            textBox1.SelectionLength = 0;
        }
    }
Mitja Bonca 557 Nearly a Posting Maven

If you would like to validate the last part of the email string; this are the extensions (com, us, ...) i would suggest you to do a list of them, and then loop through them to check if the inserted one has any match, like here:

/// <summary>
/// method for determining is the user provided a valid email address
/// We use regular expressions in this check, as it is a more thorough
/// way of checking the address provided
/// </summary>
/// <param name="email">email address to validate</param>
/// <returns>true is valid, false if not valid</returns>
public bool IsValidEmail(string email)
{
    //regular expression pattern for valid email
    //addresses, allows for the following domains:
    //com,edu,info,gov,int,mil,net,org,biz,name,museum,coop,aero,pro,tv
    string pattern = @"^[-a-zA-Z0-9][-.a-zA-Z0-9]*@[-.a-zA-Z0-9]+(\.[-.a-zA-Z0-9]+)*\.
    (com|edu|info|gov|int|mil|net|org|biz|name|museum|coop|aero|pro|tv|[a-zA-Z]{2})$";
    //Regular expression object
    Regex check = new Regex(pattern,RegexOptions.IgnorePatternWhitespace);
    //boolean variable to return to calling method
    bool valid = false;

    //make sure an email address was provided
    if (string.IsNullOrEmpty(email))
    {
        valid = false;
    }
    else
    {
        //use IsMatch to validate the address
        valid = check.IsMatch(email);
    }
    //return the value to the calling method
    return valid;
}
Mitja Bonca 557 Nearly a Posting Maven

Try this code:

public static bool isValidEmail(string inputEmail)
{
   string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
         @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" + 
         @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
   Regex re = new Regex(strRegex);
   if (re.IsMatch(inputEmail))
    return (true);
   else
    return (false);
}
Mitja Bonca 557 Nearly a Posting Maven

Hi, if you have dgv bound to dataTable you can only loop through the dataTable, and retreive all the data from dataTable (no need from dgv), because all the data put into dgv, are "automatically" saved into dataTable as well (because of the binding source).

1st loop has to go by looping through the rows, and 2nd one has to loop through the columns:

for (int i = 0; i < table.Rows.Count; i++)
            {
                for (int j = 0; j < table.Columns.Count; j++)
                {
                    DateTime dt1 = Convert.ToDateTime(table.Rows[i][j]).AddDays(1);
                    if (DateTime.Now > dt1)
                    {
                        string sta = "Pending";
                        SqlCommand cmd3 = new SqlCommand("UPDATE tblDaily_Task_Schedule SET Task_Status = '" + sta + "'", con);
                        cmd3.ExecuteNonQuery();
                    }
                }
            }
Mitja Bonca 557 Nearly a Posting Maven
static void Main(string[] args)
        {
            Program d = new Program();
            d.Myprog("ahasda");
            Console.ReadLine();
        }
        void Myprog(params string[] array)
        {
            int num = 0;

            foreach (string str in array)
            {
                foreach (char c in str)
                {
                    if (c.Equals('a'))
                        num++;
                }
            }
            Console.WriteLine(num);
        }
Mitja Bonca 557 Nearly a Posting Maven

Or:

string example = "0123456789";
int count = example.Length;
Mitja Bonca 557 Nearly a Posting Maven

That means that your DataTable is empty. You didnt get any data out of the dataBase. Check the sql query.

Mitja Bonca 557 Nearly a Posting Maven

You can bind it (this is the best solution and th fastest).

dataGridView1.DataSource = new BindingSource(myDataSet.Tables["tableName"], null);

Thats it!
And the data will appear in the DGV.

Mitja Bonca 557 Nearly a Posting Maven

To add:

namespace yourproject
{	
	public class Program : Form
	{
		private Button NewGame;                
                public Program()
		{
			InitializeComponent();
                        1st you need to create a button:
                        NewGame = new Button;
                        NewGame.Location = new Point (100,100);
                        NewGame.Text = "press me";
                        NewGame.Name = "button1";
                        NewGame.Size = new Size(40, 23);                        
                        NewGame.Click += new EvenHandler(NewGame_Click);           
                        this.Controls.Add(NewGame);
                 }

                 private void NewGame_Click(object sender, EventArgs e)
                 {
                       //do the code on the button click here
                 }
            }
      }
}
Mitja Bonca 557 Nearly a Posting Maven

Actually I'm make a system in C# but this system want link to old system(vb). So that I'm just add the data into old system database. I'm found that have RecNo. So I'm not choice, must be follow old system database. because some other system also follow this. Because this part of system is use to arrange Lorry can take how many thing.

Anyway, you can still use code i gave you, just a bit modified.

Tell me something, how do you know when you need a new Record number, because of this depends what to look 1st.

Mitja Bonca 557 Nearly a Posting Maven

What dont you put all the data into DataTable, and then only use SqlCommandBuilder object to do an Update of the data in DataTable to the Appropriate Table in DataBase?

Here are links how to do it:
http://support.microsoft.com/kb/308507 and
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.updatecommand%28v=vs.71%29.aspx

Mitja Bonca 557 Nearly a Posting Maven

One more suggestion: You can create a report (Crystal Report would be perfect), pass data of label to it, design it by your needs, and print it out.
Thats why Reports are made for.

Mitja Bonca 557 Nearly a Posting Maven

One thing, I would strongly suggest you to use only one column for the record number.
You have to combine Loading number and Record number. This way you will have a lot less problems.
It sure is possible to create a working code for this kind of dataBase structure you have now, but I repeat my self, if there is no condition to have borh columns, remove one, and have only one.
Anfd there is still one thing missing in the Loading number: a year value. What if the year changes to the next one? You will get duplicates for sure.

Your record number shoud look like "dd/MM/yyyy/record number (4 digits)
So you will run records by date and the record number:
4/5/2011/0001
4/5/2011/0002
4/5/2011/0003
5/5/2011/0001
and so on!!

Isnt this a better, any most important, way simplier idea?

If you answered with yes, you can take a look into my code example, which does this work:

class Program
    {
        private static string connString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\AppsTest\2011\Apr15DB_AutoGenerate\monthAutoGenerateID.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
        static void Main(string[] args)
        {
            //get this month`s name:
            DateTime date = DateTime.Now;
            string month3Letters = String.Format("{0:MMM}", date);

            //get last id from dataBase:
            string newID = GetLastID();
            if (newID != null)
            {
                string onlyMonthName = newID.Substring(0, 3);
                if (onlyMonthName == month3Letters)
                {
                    //get number from id:
                    int numberID = Convert.ToInt32(newID.Remove(0, 3));
                    //auto-increment to get new id:
                    numberID++;
                    //now we have to add zeros on the left side …
ddanbe commented: Continous effort. :) +14
Mitja Bonca 557 Nearly a Posting Maven

BTW: if you want to get the text one beside another - in one line, you only have to change StringBuilder`s AppendLine() method with only Append().
Simple
Enjoy :)

Mitja Bonca 557 Nearly a Posting Maven

First you have to create a global TextBox variable array, so in the whole class is visible. Then create textboxes, and when you need to loop through them, do the following (code at the bottom):

TextBox[] tbs;

void CreatingTextboxes()
{
    tbs = new TextBox[int.Parse(numericUpDown.Value)];
    //now loop with your code from the top and create textBoxes in the a bit different way they you did:

    int x = 20;
    int y = 30;
    for(int i = 0; i< tbs.Lenght; i++)
    {
         tbs[i] = new TextBox();
         tbs[i].Name = "textBox" + i+1;
         tbs[i].Location = new Point (x, y);
         tbs[i].Width = 100;
         this.Controls.Add(tbs[i]);
         //set new coordinated for a new textbox:
         y += 30; //vertical 
         x += 0;  //horizontal - do what ever you want to put them in the form!
    }
}

void GetTextFromTextBoxes()
{
    StringBuilder sb  = new StringBuilder();
    foreach(Control c in this.Controls)
    {
       if(c is TextBox && c != null)
       {
           Textbox tb = c as TextBox;
           //read each text from textBox:
           if(tb.Text != String.Empty)
               sb.AppendLine(tb.Text);
       }
    }

    //lets show the text in all textBoxes!
    MessageBox.Show(sb.ToString());
    //you can do with the text what ever you want, I only wanted to show how to get all the text from each textBox on the form, and get them together trom all of them!
}

Let me know what do you think,
bye,

Mitja Bonca 557 Nearly a Posting Maven

Anyway, here is my code of putting dgv`s content to a csv file:

Private Sub buttonSave_Click(sender As Object, e As EventArgs)
	Dim sbCSV As New StringBuilder()
	Dim intColCount As Integer = dt.Columns.Count
	For Each dr As DataRowView In dt.DefaultView
		For x As Integer = 0 To intColCount - 1
			sbCSV.Append(dr(x).ToString())
			If (x + 1) <> intColCount Then
				sbCSV.Append(",")
			End If
		Next
		sbCSV.Append(vbLf)
	Next
	Using sw As New StreamWriter("c:\csv\table1.csv")
		sw.Write(sbCSV.ToString())
	End Using
End Sub
Mitja Bonca 557 Nearly a Posting Maven

Try to remove "Value" from the if statement:

If dc IsNot Nothing Then
	strExport += dc.Value.ToString() & "   "
End If
Mitja Bonca 557 Nearly a Posting Maven

Try splitting it(as said in the post abouve with th Split method.
And do it like:

while (reader.Read())
            {
                string[] array = reader[0].ToString().Split(',');
                foreach (string item in array)
                    lstPK.Items.Add(item);
            }

Even if there will be no comma in the string, there will always be one item to add to listBox.

Mitja Bonca 557 Nearly a Posting Maven
int rowsCount = cmd.ExecuteNonQuery();
Mitja Bonca 557 Nearly a Posting Maven

You mean to get all values from all columns and add them into one cell?
Into same dataGridView or into some other one?

Mitja Bonca 557 Nearly a Posting Maven

You mean this code:

private void cmbProgramme_SelectedIndexChanged(object sender, EventArgs e)
{ 
  //DO NOT USE THIS NOW ANY MORE!!
  cmbCourses.Items.Clear();  //you say this is not working??
  // And the rest

This has to work, especially becuase you ADD items to comboBox - your comboBox is not dataBound!!

... but
Lets change the code a bit to:

SqlCommand cmd = new SqlCommand(@"SELECT C_Name FROM tblCourses WHERE P_Name = '" + cmbProgramme.SelectedItem.ToString() + "'", MyConnection);
MyDataAdapter = new SqlDataAdapter(cmd);
//You dont need to fill comboBox item by item, you can set the it`s dataSouce to the dataTable:
cmbCourses.DataSource = table;
cmbCourses.DispayValue = "C_Name";
cmbCourses.ValueMember= cmbCourses.DisplayMember;
//nothing else!

//AND BTW: if you use DataSource property - you have to remove the line of comboBox.Items.Clear() method !

Check it out, and let me know if it works...

Mitja Bonca 557 Nearly a Posting Maven
cmbCourses.Items.Clear();

method should clear all the items from comboBox. if not try with additional code ( both):

cmbCourses.SelectedIndex = -1;
Mitja Bonca 557 Nearly a Posting Maven

Check this out:
But be careful with the column number (as far as I can see you assign date value to 14th subitem - mine is on 2nd (Subitems[1]):

Public Sub New()
	InitializeComponent()
	listView1.Columns.Add("Id", 50, HorizontalAlignment.Left)
	listView1.Columns.Add("Date and time", -2, HorizontalAlignment.Left)
	listView1.View = View.Details
	listView1.FullRowSelect = True

	'add example data:
	Dim table As New DataTable("MyTable")
	table.Columns.Add("Id", GetType(Integer))
	table.Columns.Add("Date", GetType(DateTime))
	table.Rows.Add(1, DateTime.Today.AddDays(-1))
	table.Rows.Add(2, DateTime.Today)

	'put this data to listView:
	For Each dr As DataRow In table.Rows
		Dim lvi As New ListViewItem()
		lvi.Text = dr(0).ToString()
		lvi.SubItems.Add([String].Format("{0:MM/dd/yyyy hh:mm:ss}", Convert.ToDateTime(dr(1))))
		listView1.Items.Add(lvi)
	Next

	'create a listView event:
	listView1.SelectedIndexChanged += New EventHandler(AddressOf listView1_SelectedIndexChanged)
End Sub

Private Sub listView1_SelectedIndexChanged(sender As Object, e As EventArgs)
	If listView1.SelectedIndices.Count > 0 Then
		Dim value As String = listView1.SelectedItems(0).SubItems(1).Text
		If value IsNot Nothing Then
			dateTimePicker1.Value = Convert.ToDateTime(value)
		End If
	End If
End Sub
Mitja Bonca 557 Nearly a Posting Maven

I should work. Take a look at this simple example:

class MyClass
    {
        string a; //this will not be initialized, but there will be no error in compile time
        string b = "b";
        public void MyMethod()
        {
            a = "a";
            string c;  //this will not be initialized, but there will be no error in compile time
            string d = "d";
        }
    }

This all works.

Mitja Bonca 557 Nearly a Posting Maven

Just to add:
... be careful here. adatapost is correct, but be careful in two things
- row index
- column index

You have to state the correct indexes, and for the column you can even state the column name!

Mitja Bonca 557 Nearly a Posting Maven

The code looks fine. Where should be the problem?
Into this code you got the customers with their data:

Customer cust = new Customer();
SortedList custList = cust.ListCustomerByPostcode(ECenterPostcodeTextBox.Text);
//custList hold now customers data!!

//now you want to put them to listBox!
//you will have to loop through the list and add them one by one:
for(int i = 0; i< custList.Count; i++) //instead of count, cound be Lenght property! not sure atm
{
   lstCustomerSelect.Items.Add(custList[i]);
}

But it might work even without any loop, just to use AddRange method

lstCustomerSelect.Items.AddRange(custList[i]); //not sure, try it out

I hope i didnt do a lot of mistakes, I wrote this by heart.

johnt68 commented: Big thankyou +2
Mitja Bonca 557 Nearly a Posting Maven

Sure it is:

Rabit[] rabits = new Rabit[10];
Fox[] foxes = new Fox[6];
Dog[] dogs = new Dog[4];
for(int i = 0; i < 10;i++)
{
   Rabit r = new Rabit();
   rabits[i] = r;
   if(i < 6)
   {
       Fox f = new Fox();
       foxes[i] = f;
   }
   if(i < 4)
   {
       Dog d = new Dog();
       dogs[i] = d;
   }
}

Now you have 3 arrays of the classes

If you dont want to have classes in the array, simply dont use array, and create classes as abouve:

for(int i = 0; i < 10;i++)
{
   Rabit r = new Rabit();
   if(i < 6)
       Fox f = new Fox();
   if(i < 4)
       Dog d = new Dog();
}
TheBadger commented: Thx that works great! +1
Mitja Bonca 557 Nearly a Posting Maven

Ok, glad to hear. Though you can try out code I gave you.
if the issue is salved, you can close the thread (mark it as answered).
best regards

Mitja Bonca 557 Nearly a Posting Maven

YOu can do it this way:

List<Label> labels = new List<Label>();
            List<TextBox> textBoxes = new List<TextBox>();
            foreach (Control c in this.Controls)
            {
                if (c is Label)
                {
                    Label label = c as Label;
                    labels.Add(label);
                }
                else if (c is TextBox)
                {
                    TextBox text = c as TextBox;
                    textBoxes.Add(text);
                }
            }

            foreach (Label l in labels)
                this.Controls.Remove(l);
            foreach (TextBox t in textBoxes)
                this.Controls.Remove(t);
Mitja Bonca 557 Nearly a Posting Maven

So you only have to remove pictureBoxes, and lables? All of them?
Because you have to be very specific which controls to remove.

Mitja Bonca 557 Nearly a Posting Maven

Ok, I did the full working solution.
What you have to do, is to conside of getting the last record out of the database (look into my 1st post).
Then you use this code I did for you:

public Form1()
        {
            InitializeComponent();

            //get record out of database
            //you can use any method you want, 
            string record = "11/04/0011";
            record = CalculateNewRecordNumber(record);
        }

        private string CalculateNewRecordNumber(string record)
        {            
            string[] data = record.Split('/');
            DateTime currentDate = DateTime.Today;
            int recordYear = int.Parse(data[0]);
            recordYear = int.Parse("20" + recordYear);
            int recordMonth = int.Parse(data[1]);
            if (currentDate.Year == recordYear)
            {
                if (currentDate.Month == recordMonth)
                {
                    //year and month are the same, we only have to increment the number:
                    int number = int.Parse(data[2]);
                    //do the increment of the record number:
                    number++;
                    //create new record:
                    record = recordYear + "/" + recordMonth + "/";
                    string _recNumberOnly = number.ToString();

                    //loop to create 4 digits number!
                    for (int i = 0; i < 4; i++)
                    {
                        if (_recNumberOnly.Length == 4)
                            break;
                        else
                            _recNumberOnly = "0" + _recNumberOnly;
                    }
                    record += _recNumberOnly;
                }
                else
                {
                    //there is a new month!
                    //increment a month (year stays the same) and starts with number 0001:
                    recordMonth++;
                    record = recordYear + "/" + recordMonth + "/0001";
                }
            }
            else
            {
                //there is a new year!
                //increment a year and start from month 1 and starts with number 0001:
                recordYear++;
                record = recordYear + "/01/0001";
            }
            return record;
        }
Mitja Bonca 557 Nearly a Posting Maven

To read the last record from the DB you do:

"SELECT MAX(ColumnName) FROM MyTable"

And because this is a string (varchar) format, you 1st have to retreive the number out of the string, convert it to number (int), then do the incrementation (auto add 1) and convert it back to string and join with the rest of the "date" string".

And one important thing to mention: Before doing the incrementation (addint +1) you have to get the current date. If the month is not the same as the last retreived date, you have to start with number 1.

Mitja Bonca 557 Nearly a Posting Maven

How to use a invokeRequired method while you have to invoke a control over threads shows the exmple code with using Delegates bellow:

Private Delegate Sub MyDelegate(msg As String)
Private Sub FillingListBox(value As String)
	If listBox1.InvokeRequired Then
		listBox1.Invoke(New MyDelegate(AddressOf FillingListBox), New Object() {value})
	Else
		listBox1.Items.Add(value)
	End If
End Sub

You call this method when you want to pass the new item to listBox.

Mitja Bonca 557 Nearly a Posting Maven

You have to use a DataReader class to get a value our of database:

string cmd = "Select FName From Emp Where EmpID = 20");
OracleCommand oc = new OracleCommand(cmd, oraConnection);
//open a connection:
oraConnection.Open();
OracleDataReader reader = command.ExecuteReader();
string result = null;
if(reader.Read())
     result = (string)reader[0];
reader.Close();
oraConnection.Close();
if(result.StartsWith("s")
{
     //what would you like to do here?
}
else
{
     //and what would you like to do here?
}

You didnt say what exactly would you like to do in if, else blocks.
About what Cell are you talking about?

Mitja Bonca 557 Nearly a Posting Maven
Mitja Bonca 557 Nearly a Posting Maven
for(int i = 0; i< lstCols.Items.Count; i++)
{
    if((i +1) < lstCols.Count)
        textBox1.Text += lstCols.Items[i] + ", ";
    else
       textBox1.Text += lstCols.Items[i];
}
Behseini commented: Perfect answer +3