Mitja Bonca 557 Nearly a Posting Maven

And try to use Parameters, so you dont assign values directly into the query, but in query you only write parameters, which you then add bellow.
Example:

OleDbCommand com = new OleDbCommand(@"UPDATE cus SET cus_name = @param1, order = @param2 WHERE no = @param3", con);
com.Parameters.Add("@param1", OleDbType.VarChar, 50).Value = textBox4.Text;
com.Parameters.Add("@param2", OleDbType.VarChar, 50).Value = textBox6.Text;
com.Parameters.Add("@param3", OleDbType.VarChar, 50).Value = textBox7.Text;
try
{
    com.ExecuteNonQuery();
}
catch(Excpeption ex)
{
      //show exception if needed
}

Change the type of parameters to exact type (or varchar, or int, or... - checkl your database).

Mitja Bonca 557 Nearly a Posting Maven

Try this code to create a moving button from one location to another:

Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms

Namespace WindowsApplication9

	Public Partial Class Form1
		Inherits Form
		Public Velocity As Integer() = New Integer(1) {}
		Public count As Integer
		Public Dest As System.Drawing.Point = New Point(394, 368), Temp As System.Drawing.Point
		Public Sub New()

			InitializeComponent()
		End Sub
		Public Function CheckV(a As Point, b As Point, Temp As Point, time As Integer) As Integer


			Dim vx As Integer = 0, vy As Integer = 0
			If time = 1 Then
				Dim sx As String = Convert.ToString(a.X - b.X)
				If Math.Abs(a.X - b.X) < 1 Then
					Return 1
				Else

					If sx.Length > 2 Then
						vx = (a.X - b.X) \ 100
					ElseIf sx.Length = 2 Then
						vx = (a.X - b.X) \ 10
					Else
						vx = 1

					End If
				End If

				Return vx
			ElseIf time = 2 Then
				Dim sy As String = Convert.ToString(a.Y - b.Y)
				If Math.Abs(a.Y - b.Y) < 1 Then
					Return 1
				Else
					If sy.Length > 2 Then
						vy = (a.Y - b.Y) \ 100
					ElseIf sy.Length = 2 Then
						vy = (a.Y - b.Y) \ 10
					Else
						vy = 1

					End If
				End If
				Return vy
			Else
				Return 0
			End If

		End Function
		Private Sub button1_Click(sender As Object, e As EventArgs)
			button1.Enabled = False
			For i As Integer = 0 To 1
				Velocity(i) = CheckV(Dest, button1.Location, Temp, i + 1)
			Next
			timer1.Start()
		End Sub

		Public Function [Stop](a As Boolean, b As Boolean) …
Mitja Bonca 557 Nearly a Posting Maven

Are these files in one folder? If so, you can get all files from this folder into a FileInfo[] (you need fileInfo, because you need a full path, so set files back where they were before renaiming).
Then you do some additional code of renaiming and use Move method for an actual renaiming:

string path =@"C:\MyFolder";
            FileInfo[] files = new DirectoryInfo(path).GetFiles("*.txt");
            for (int i = 0; i < files.Length; i++)
            {
                string newFile = String.Format("{0}{1}.{2}", "File", (i + 1), "txt");
                string fullNewPath = files[i].DirectoryName;
                File.Move(files[i].FullName, Path.Combine(fullNewPath, newFile));
            }

I hope you like it.

Mitja Bonca 557 Nearly a Posting Maven

Done it!
Here is the code, jsut copy and paste it into a brand new project (attention, change project name, so you wont copy complete code of mine to yours created project!!)
You dont need to put anything on the form - keep it empty.

Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Sep05_PeriodicalTable  //CHANGE TO YOUR NAMESPACE!!!
{
    public partial class Form1 : Form
    {
        List<ElementData> elementsList;
        List<LegendData> legendList;
        Button[] elebuttons;
        Button[] legButtons;

        public Form1()
        {
            InitializeComponent();
            //path
            string fileName = "PeriodicalTable.txt";
            string path = Environment.CurrentDirectory;
            path = Path.Combine(path, fileName);

            //creating new list<T>:
            elementsList = new List<ElementData>();
            legendList = new List<LegendData>();

            //reading file line by line and adding data into list<T>:
            string type = null;
            foreach (string data in ReadingData(path))
            {
                if (data == "ELEMENT_LIST")
                {
                    type = "elements";
                    continue;
                }
                else if (data == "LEGEND")
                {
                    type = "legend";
                    continue;
                }

                if (type == "elements")
                    SeperateElementData(data);
                else if (type == "legend")
                    SeperateLegendData(data);               
            }
            //Creating phisical periodical table from the data:
            CreatingElements();
            //Creating legends:
            CreatingLegends();
        }

        private void CreatingElements()
        {
            elebuttons = new Button[elementsList.Count];
            //starting position for 1st upper left button:
            int x = 20;
            int y = 60;
            //and size of buttons:
            int size = 48;
            foreach (ElementData el in elementsList)
            {
                if (el.LocationX > 0)
                    x = 20 + size * el.LocationX;
                else
                    x = 20;
                if (el.LocationY > 0)
                    y = 60 + size * el.LocationY;

                elebuttons[el.SequenceNumber - 1] = …
ddanbe commented: Nice effort :) +14
nick.crane commented: Excellent first go! +10
Mitja Bonca 557 Nearly a Posting Maven

You can set tje order of the columns like:

dataGridView1.Columns["Name"].DisplayIndex = 0;
    dataGridView1.Columns["RegNo"].DisplayIndex = 1;
    dataGridView1.Columns["Adress"].DisplayIndex = 2;
kvprajapati commented: ++ +15
Mitja Bonca 557 Nearly a Posting Maven

To get a week number of the month you can do:

//in your method:
DateTime time = DateTime.Now;
int weekNumber = GetWeekOfMonth(time); //calling a method

        public static int GetWeekOfMonth(DateTime date)
        {
            DateTime beginningOfMonth = new DateTime(date.Year, date.Month, 1);

            while (date.Date.AddDays(1).DayOfWeek != CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek)
                date = date.AddDays(1);

            return (int)Math.Truncate((double)date.Subtract(beginningOfMonth).TotalDays / 7f) + 1;
        }
ddanbe commented: Nice addition! +14
Mitja Bonca 557 Nearly a Posting Maven

Here you have online converter.

ddanbe commented: Hey! Great tip! +14
Mitja Bonca 557 Nearly a Posting Maven

Try it this way:

Dim days As Integer = 12 'your value from DB! (one or the other - didnt know what you want
Dim months As Integer = 5 'your value from DB!
Dim [date] As DateTime = DateTime.Now 'some date !

'get new date (current date + days):
[date] = [date].AddDays(days)

'get new date (current date + months):
[date] = [date].AddMonths(months)
Mitja Bonca 557 Nearly a Posting Maven

This is getting pointeless mate!
For UPDATE statement you do:
UPDATE tableName SET Field1 = @param1, Fields2 = @param2 WHERE idFields = @paramID

adam_k commented: :D +6
Mitja Bonca 557 Nearly a Posting Maven

Here you go:

public Form1()
        {
            InitializeComponent();
            //adding some example columns:
            //1. column is checkBox, rest of 2 are some usual column:

            DataGridViewCheckBoxColumn checkColumn = CreateCheckBoxColumn();
            dataGridView1.Columns.Add(checkColumn);
            dataGridView1.Columns.Add("col2", "Column 2");
            dataGridView1.Columns.Add("col3", "Column 3");

            //adding some example rows:
            for (int i = 1; i <= 10; i++)
            {
                dataGridView1.Rows.Add(false, "item A" + i, "item B" + i);
            }

            //create an event:
            dataGridView1.CurrentCellDirtyStateChanged += new EventHandler(dataGridView1_CurrentCellDirtyStateChanged);
            dataGridView1.CellValueChanged += new DataGridViewCellEventHandler(dataGridView1_CellValueChanged);
        }

        private DataGridViewCheckBoxColumn CreateCheckBoxColumn()
        {
            DataGridViewCheckBoxColumn column = new DataGridViewCheckBoxColumn();
            {
                column.Name = "checkColumn";
                column.HeaderText = "Select rows";
                column.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
                column.ThreeState = false;
            }
            return column;
        }

        void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (dataGridView1.IsCurrentCellDirty)
                dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
        }

        private void dataGridView1_CellValueChanged(object obj, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == dataGridView1.Columns[0].Index) //compare to checkBox column index
            {
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    if (!row.IsNewRow)
                    {
                        DataGridViewCheckBoxCell checkBox = dataGridView1[0, row.Index] as DataGridViewCheckBoxCell;
                        if (checkBox != null)
                        {
                            if ((bool)checkBox.Value == true)
                                dataGridView1.Rows[row.Index].Selected = true;
                            else
                                dataGridView1.Rows[row.Index].Selected = false;
                        }
                    }
                }
            }
        }
ddanbe commented: Nice +14
Mitja Bonca 557 Nearly a Posting Maven

It would be better to use datasource property of comboBox to pass data from table to comboBox:

Private Sub Form5_Load(sender As System.Object, e As System.EventArgs)
	Dim con As New SqlConnection()
	con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\lito\Documents\QMP_DB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
	con.Open()
	Dim da As New SqlDataAdapter("select * from Subject_Info", con)
	Dim table As New DataTable()
	da.Fill(table)
	comboBox1.DataSource = New BindingSource(table, Nothing)
	comboBox1.DisplayMember = "Name"
	'write the column name which will be diplayed
	'you can even use  valueMember property, 
	'Names - DisplayMember - this is was you see in comboBox
	'IDs - ValueMember can be used as additional value of Person
	comboBox1.ValueMember = "ID"
	'column name for value         
End Sub
debasisdas commented: agree +13
adam_k commented: You've got it +6
Mitja Bonca 557 Nearly a Posting Maven

YOu know what... I was only trying to help him, because I knew he would have come back and asking me for more info, how this, how that, and so on...
Thats why I decided to give him a code, to see exactly what he needs.

But ok, from now on, I will keep of giving people code in this kind of manner. But still no need to down voting my post.

Mitja Bonca 557 Nearly a Posting Maven

Ok, because Im so good and willing to help yet, I did the code for you:

Random r = new Random();
        private void Method()
        {
            DataTable table1 = new DataTable("table1");
            DataTable table2 = new DataTable("table2");

            //I will use only one column, but the same is if you use more!
            table1.Columns.Add("column 1", typeof(int));
            
            //create same column names as table1
            table2 = table1.Clone(); 

            //lets add some rows:
            for (int i = 0; i < 100; i++)
                table1.Rows.Add(i);

            //generate a random number:
            int myRandom = r.Next(table1.Rows.Count);

           
            //now lets get that random number of rows from table1 to table2 - from top down, and remove all added to table2:            
            //creating listT to add rows (becuase you cannot remove or delete rows in a loop)!
            List<DataRow> rowsToRemove = new List<DataRow>();
            for (int i = 0; i < table1.Rows.Count; i++)
            {
                if (i <= myRandom)
                {
                    rowsToRemove.Add(table1.Rows[i]);
                    table2.Rows.Add();
                    foreach (DataColumn col in table1.Columns)
                    {
                        table2.Rows[i][col.ColumnName] = table1.Rows[i][col.ColumnName];
                    }
                }
                else
                    break;
            }

            //remove rows from table1:
            foreach (var dr in rowsToRemove)
                table1.Rows.Remove(dr);

            // NOW YOU HAVE:
            // In table1 rows from random number and up to 100
            // In table2 rows from 0 to the randomnumber (including it)!
        }

This is working perfectly good, I have tested it!!

Mitja Bonca 557 Nearly a Posting Maven

Loop through the rows of DGV, and check is there is at least one checkBox checked. If there is, Enable the button, if not, leave it Disabled (this is in case if you will check on some button click event, and not when checking ot unchecking a comboBox)

If you wanna check the actual state of current checkBox, you will have to use two events of DGV:
1. CurrentCellDirtyStateChanged
2. CellValueChanged

What i mean is, if you add (or remove) a tick into a checkBoxCell, these two events will fire, and then you can check the actual state of current checkBoxCell value.

I suggest you to create a class integer variable, which will count the number of checkBoxes checked. Then you do the checking in the CellValueChanged, if the value is 0 Disable a button, if the value is greater then zero, enable it.

Here is the example code:

//class variable (put it on the top of the code!
        int checkBoxCounter;

        void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (dataGridView1.IsCurrentCellDirty)
                dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
        }

        private void dataGridView1_CellValueChanged(object obj, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 1) //compare to checkBox column index
            {
                DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)dataGridView1[e.ColumnIndex, e.RowIndex];
                if (checkCell =! null)
                {
                     if((bool)checkCell.Value == true)
                         checkBoxCounter++;  //count + 1;
                     else
                         checkBoxCounter--;   //subtract 1 (-1)
                }
            }

            //here you can do the checking or button will be enabled or disabled:
            if(checkBoxCounter > 0)
                button1.Enabled = true;
            else if(checkBoxCounter == 0)
                button1.Enabled = false;                
        }

This is it. And …

Mitja Bonca 557 Nearly a Posting Maven

Pass every image to this method bellow:

'in your method:
Private bImage As byr() = ImageToByteArray(yourImage)

'method
Public Function ImageToByteArray(imageIn As System.Drawing.Image) As Byte()
	Dim ms As New MemoryStream()
	imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif)
	Return ms.ToArray()
End Function
Mitja Bonca 557 Nearly a Posting Maven

Hi,
I would suggest you to use ReadLine() method, not ReadToEnd(). This way you avoid some additional code, which would be needed if you would use ReadToEnd() method.
So after using ReadLine() method, you get a string of text line by line. Each line will habe the shape of you:

"Name amount1 amount2"

What you can do is to split string (by whitespace), and:
1. put into a stirng array and all add to generic list
2. create a new class and assign data to properties of this class and add to generic List<T>
-------------------------------------------------

1.

List<string[]> list  = new List<string[]>();
StreamReader sr = new StreamReader("Aqua.txt");
string line;
while((line = sr.ReadLine()) != null)
{
    string[]array = line.Spit(' ');
    list.Add(array); 
}

//when retreiving data loop over list and access to the vlaues by settting indexes:
foreach(string item in list)
{
    string name = item[0];
    string no1 = item[1];   
    string no1 = item[2];
    //you can convert to int if oyu like:
    int intNo1 = int.Parse(item[0]);
}
Mitja Bonca 557 Nearly a Posting Maven

Ok, that you wont bother with insert query (even if you know it, or if you have a stored procedure), here is my full code:

string lastDir;
        string fileName;
        public Form1()
        {
            InitializeComponent();
        }

        private void buttonOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog open = new OpenFileDialog();
            open.Filter = "Image Files(*.png; *.jpg; *.bmp)|*.png; *.jpg; *.bmp";
            if (lastDir == null)            
                open.InitialDirectory = @"C:\";
            else
                open.InitialDirectory = lastDir;
            if (open.ShowDialog() == DialogResult.OK)
            {
                fileName = System.IO.Path.GetFullPath(open.FileName);
                lastDir = open.FileName;
                pictureBox1.Image = new Bitmap(open.FileName);
                this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
            }
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            //get image:
            Image img = Image.FromFile(fileName);
            //get byte array from image:
            byte[] byteImg = ImageToByteArray(img);

            //here do the insertion into dataBase!
            //but remember, your field in DB must be type to byte array
            //example:
            using (SqlConnection sqlConn = new SqlConnection("connString"))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandText = @"INSERT INTO MyTable VALUES (@id, @image, @name)";
                    cmd.Connection = sqlConn;
                    sqlConn.Open();
                    try
                    {
                        cmd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
        }

        public byte[] ImageToByteArray(Image img)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            return ms.ToArray();
        }
yousafc# commented: Mitja is best developer +3
Mitja Bonca 557 Nearly a Posting Maven

What is your DB table (table you wish to insert into) structure?

Anyway, here is my solution for you, I only didnt include sql and DB insertion.
(for it you have to use sql query:
@"INSERT INTO Table VALUE (@id, @picByte, @picName)"
- id
- pic byte[]
- pic name (string) - its optional, but its good to have it.

So heres the code:

string lastDir;
        string fileName;
        public Form1()
        {
            InitializeComponent();
        }

        private void buttonOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog open = new OpenFileDialog();
            open.Filter = "Image Files(*.png; *.jpg; *.bmp)|*.png; *.jpg; *.bmp";
            if (lastDir == null)            
                open.InitialDirectory = @"C:\";
            else
                open.InitialDirectory = lastDir;
            if (open.ShowDialog() == DialogResult.OK)
            {
                fileName = System.IO.Path.GetFullPath(open.FileName);
                lastDir = open.FileName;
                pictureBox1.Image = new Bitmap(open.FileName);
                this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
            }
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            //get image:
            Image img = Image.FromFile(fileName);
            //get byte array from image:
            byte[] byteImg = ImageToByteArray(img);

            //here do the insertion into dataBase!
            //but remember, your field in DB must be type to byte array
        }

        public byte[] ImageToByteArray(Image img)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            return ms.ToArray();
        }
Mitja Bonca 557 Nearly a Posting Maven

Try this code:

Private table As DataTable
Public Sub New()
	InitializeComponent()

	table = New DataTable("myTable")
	table.Columns.Add("column 1", GetType(String))
	table.Columns.Add("column 2", GetType(String))
	table.Rows.Add("a1", "b1")
	table.Rows.Add("a2", "b2")
	table.Rows.Add("a3", "b3")
	table.Rows.Add("a4", "b4")
	dataGridView1.DataSource = New BindingSource(table, Nothing)
End Sub

Private Sub button1_Click(sender As Object, e As EventArgs)
	Dim selectedRow As DataRow = table.Rows(dataGridView1.CurrentRow.Index)
	Dim newRow As DataRow = table.NewRow()
	newRow.ItemArray = selectedRow.ItemArray
	' copy data
	table.Rows.Remove(selectedRow)
	table.Rows.InsertAt(newRow, 0)
End Sub

as you can see the dataTable is bound to datagridview, so you can see the actual results, when selecting a row and pressing a button. The selected row will move to the top of DGV (the same as in dataTable).
If you want to use the code in dataSet, just create is, and add a dataTable to it.

mrbungle commented: Thanks for your help and time! Good code! +2
Mitja Bonca 557 Nearly a Posting Maven

Hi,
1st, point is that you have the same columns, ok its not really necessary, but its good when you want to copy a row from on dataGrid to anoter to have at least the same number of columns and that are the same type (even all can be parsed as objects).
So this is the code example:

private void button1_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in dataGridView1.SelectedRows)
            {
                dataGridView2.Rows.Add();
                int newRow = dataGridView2.Rows.Count - 1;
                foreach (DataGridViewCell cell in row.Cells)
                {
                    dataGridView2[cell.ColumnIndex, newRow].Value = cell.Value;
                }
            }
        }
Mitja Bonca 557 Nearly a Posting Maven

Do you want to set "u" property to field "i"?
If so, you can do it this way:

int i = 9;
int o = 8;

private U;
int u
{
    get { return U; }
    set { U = i; }
}

If you will get i in u property (like you showed), then there is no point in having u property at all.

Mitja Bonca 557 Nearly a Posting Maven

1st time you SET it.
2nd time oyu get it.

Simple. If you want to read, 1st you have to set it, then when is set, you can ge it.

Example:

class a1
{
     a2 a;
     private void methodA()
     {
          a = new a2();
          a.MyText = "something to set"; //set
     }

     private void methodB()
     {
          string text = a.MyText; //get
     }
}

class a2
{
     public string MyText { get; set; }
}
Mitja Bonca 557 Nearly a Posting Maven

Yes, take a look at this example here.

ddanbe commented: Great tip! +14
Mitja Bonca 557 Nearly a Posting Maven

LOL, there is no such thing! Sorry, you came on the wrong place.

Best way to get knowledge is to try to use it in practice. SO has a plenty of questions about C# books/sites/tutorials. Learning pattern is really simple: read a little bit of information on C# and try to write small program that uses this information. Don't try to understand the whole thing at once, grok it by small pieces and in a couple of weeks you'll get enough knowledge to write meaningful programs.

----------------
But in case, if you want to spend a couple of days more then only a few day, you can start to buy some books (or at least one), you can start here. Check for great books on amazon.com. This is the link to one great book I am currently reading (C# 2008 Step by Step; there is 2010 version too). On amazon.com you can find many, many books about programming. But the thing is, THERE IS NO FAST WAY of learing programming. It will take time, especially if you dont know any other programming language. If you do, it will be simplier and shorter learning, but in any case you will have to be patient.
btw, there is one great link of the most popular threads on StackOverflow here.

Hope it helps to start with :)

kvprajapati commented: Correct! +14
ddanbe commented: adatapost is right! +14
Mitja Bonca 557 Nearly a Posting Maven

You are welcome.
If this is was helpful upVote, or if this was it, mark the thread as answered, so we close it.

Mitja Bonca 557 Nearly a Posting Maven

i dont have any experience with datagridview so kindly express your solution in bit detail

hmmm, this will take some time then... ;)

Ok, regarding to your thread`s title, you want to pass data from textBox to DGV. You can do it this (Simple) way:

dataGrivView1[0,0].Value = txtbox1.Text; //0,0 is 1st column, 1st row
dataGrivView1[1,0].Value = txtbox1.Text; //1,0 is 2nd column, 1st row
dataGrivView1[2,0].Value = txtbox1.Text; //2,0 is 3rd column, 1st row

//for example if you want to pass data to 5th column and 10 row you do:
dataGrivView1[9,4].Value = txtbox1.Text;
Mitja Bonca 557 Nearly a Posting Maven

One of the possibilities is to use TextChanged event handler:

private void textBox1_TextChanged(object sender, EventArgs e)
        {
            string lastChar = textBox1.Text.Substring(textBox1.Lenght -1, 1);
            if(lastChar == " ")
            {
                 MessageBox.Show("User has just pressed spaceBar.");
            }            
        }

Or use can use KeyPress event, where you will get the last character of whitespace:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
   if (!char.IsWhiteSpace(e.KeyChar))
   {
       MessageBox.Show("User has just pressed spaceBar.");
       //e.Handled = true;
   }
}
dotancohen commented: Thank you. +2
Mitja Bonca 557 Nearly a Posting Maven

I am glad I could help you.

Mitja Bonca 557 Nearly a Posting Maven

You didnt set any varible to change it. You have to do it:

Curent_Year = Current_Year.AddDays(1); //on the end of the code!
Mitja Bonca 557 Nearly a Posting Maven

YOu didnt start coding the correct way. You have to put buttons into an array, and loop through them and create a common event for them, like this:

//on form load on in constructor:
Button[] btns = new Buttons[]{button1, button2, button2, button4, button5, button6, button7, button8 };
foreach(Button btn in btns)
     btn.Click += new EventHanlder(buttons_Click);

private void buttons_Click(object sender, EventArgs e)
{
    Button button = sender as Button;
    //clicked button is not in "button" variable.
    //exmaple:
    string buttonName = button.Name;
    string butonText = button.Text;
    //you can now opperate wtih them..
}
Mitja Bonca 557 Nearly a Posting Maven

Here, I did the code you would like to have.
There is maybe some work to be done in the cell vadidating (data validation; if email and tel.number are correct), and this is about it.
When you do some changes, you press one button, and all it saves automatically (or you update or delete).

Code:

public partial class Form1 : Form
    {
        private string filePath;
        List<Addressar> list;
        public Form1()
        {
            InitializeComponent();
            filePath = @"C:\1\Addressar.txt";
            list = new List<Addressar>();            
        }

        protected override void OnShown(EventArgs e)
        {
            GetData();
            dataGridView1.AllowUserToAddRows = true;
            dataGridView1.DataSource = new BindingSource(list, null);
        }

        private void GetData()
        {
            if (System.IO.File.Exists(filePath))
            {
                using (StreamReader sr = new StreamReader(filePath))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        string[] columns = line.Split(new string[] { "-:-" }, StringSplitOptions.RemoveEmptyEntries);
                        Addressar adr = new Addressar();
                        adr.Id = int.Parse(columns[0]);
                        adr.First = columns[1];
                        adr.Last = columns[2];
                        adr.Email = columns[3];
                        adr.Phone = columns[4];
                        list.Add(adr);
                    }
                }
                if (list.Count == 0)
                    MessageBox.Show("File exists, but there is no data inside of it.");
            }
            else
                MessageBox.Show("File to read data from it, does not yet exist.");
        }

        private void buttonUpdate_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            foreach (Addressar adr in list)
            {
                string[] columns = new string[5];
                columns[0] = adr.Id.ToString();
                columns[1] = adr.First;
                columns[2] = adr.Last;
                columns[3] = adr.Email;
                columns[4] = adr.Phone;
                sb.AppendLine(String.Join("-:-", columns));
            }
            if (sb.Length > 0)
            {              
                System.IO.File.Delete(filePath);
                using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
                {
                    using (TextWriter tw = new StreamWriter(fs))
                    {
                        tw.Write(sb.ToString());
                        MessageBox.Show("Update has been done successfully.","Data updating"); …
ddanbe commented: Nice. +14
Mitja Bonca 557 Nearly a Posting Maven

You cannot access to AppendText or any property of TextBox over threads. You will have to use delegates to access to it on controls, not on your do, while loop:

namespace sync
{
    public partial class Form1 : Form
    {
        int s = 0;
        delegate void MyDelegate1(string msg);
        delegate void MyDelegate2(string msg);

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, System.EventArgs e)
        {
            s = 0;

            Thread begin1 = new Thread(start1);
            Thread begin2 = new Thread(start2);

            begin1.IsBackground = true;
            begin2.IsBackground = true;

            begin1.Start();
            begin2.Start();
        }

    private void start1()
    {        
             do
             {                
                 UpdateTextBox1("1");
                 Thread.Sleep(1000);
                 Application.DoEvents();
             }
             while (s == 0);        
    }

    private void start2()
    {
            do
            {
                UpdateTextBox2("2");
                Thread.Sleep(1000);
                Application.DoEvents();
            }
            while (s == 0);        
    }
 
       private void UpdateTextBox1(string text)
       {
           if(textBox1.InvokeRequired)
               textBox1.invoke(new MyDelegat1(UpdateTextBox1), new object [] {text});
           else
               textBox1.Text = text;
       }

       private void UpdateTextBox2(string text)
       {
           if(textBox2.InvokeRequired)
               textBox2.invoke(new MyDelegat2(UpdateTextBox2), new object [] {text});
           else
               textBox2.Text = text;
       }

        private void button2_Click(object sender, System.EventArgs e)
        {
            s = 1;
        }
    }
}

This should do the trick!

Mitja Bonca 557 Nearly a Posting Maven

Hmmm... this is not an easy answer. It would be better to get your self a book about basics of programming, because question of yours is exactly this. It will take some time to understand what are you asking, and some more to make it work (in complete).

We cannot provide you a simple answer, especially not in one sentance. As you have figured it out by your self, there is plenty to learn (you stated: more you read, more you got confused). Sure, this is not an easy task to learn - as said, this are the fundations, or the basics or programming (in any language). Its called Polymorhism - or inheritance (roughtly said).

You can start with this the simplest examples here.

Take a look at this simple example of Animals:

// Assembly: Common Classes
namespace CommonClasses
{
    public interface IAnimal
    {
        string Name { get; }
        string Talk();
    }
}
 
// Assembly: Animals
using System;
using CommonClasses;
 
namespace Animals
{
    public abstract class AnimalBase
    {
        public string Name { get; private set; }
 
        protected AnimalBase(string name) {
            Name = name;
        }
    }
 
    public class Cat : AnimalBase, IAnimal
    {
        public Cat(string name) : base(name) {
        }
 
        public string Talk() {
            return "Meowww!";
        }
    }
 
    public class Dog : AnimalBase, IAnimal
    {
        public Dog(string name) : base(name) {            
        }
 
        public string Talk() {
            return "Arf! Arf!";
        }
    }
}
 
// Assembly: Program
// References and Uses Assemblies: Common Classes, Animals
using System; …
galhajaj commented: thank u for the great answer! +1
Mitja Bonca 557 Nearly a Posting Maven

The code bellow as you can see is create for not knowing the actual *.csv file. Code creates a new dataTable, creates appropriate number of columns and then fill dataTable up, based on number of rows (and based on number of columns for each row).

Here is the code it might code right:

DataTable table = new DataTable("myTable");
            bool bCreateColumns = true;
            using (StreamReader sr = new StreamReader(@"C:\1\testCSVfile.csv"))
            {
                int rows = 0;
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    string[] columns = line.Split(new char[] { ';' }, StringSplitOptions.None);
                    if (bCreateColumns)
                    {
                        DataColumn[] dtColumns = new DataColumn[columns.Length];
                        int colCounter = 1;
                        foreach (DataColumn col in dtColumns)
                            table.Columns.Add("column" + colCounter++, typeof(string));
                        bCreateColumns = false;
                    }

                    for (int i = 0; i < columns.Length; i++)
                    {
                        table.Rows.Add();
                        table.Rows[rows][i] = columns[i];
                    }
                    rows++;
                }
            }
            dataGridView1.DataSource = new BindingSource(table, null);

Actually the seperator is semicolon ";" not a comma. My mistake before in the upper post! I applogize for that.

Mitja Bonca 557 Nearly a Posting Maven

You have 3 loops here. It seems strange to me. 1st you loop through rows, and in eqach row you loop through columns, and in each column you loop again through rows od dataTable.
This has no point I would say.
Tell me one thing, what dataSet (dataTable at index 0) holds? Whats in it?
You could loop only through the dataTable, and not trought those two loops x and y.

Please write some of the logic you have there, so I can understand the code a bit better.

johnt68 commented: Thanks as always for the help +2
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

According to MSDN :

Setting the BackColor has no effect on the appearance of the DateTimePicker.

You need to write a custom control that extends DateTimePicker. Override the BackColor property and the WndProc method.

Whenever you change the BackColor, don't forget to call the myDTPicker.Invalidate() method. This will force the control to redrawn using the new color specified.

const int WM_ERASEBKGND = 0x14;
protected override void WndProc(ref System.Windows.Forms.Message m)
{
     if(m.Msg == WM_ERASEBKGND)
     {
       Graphics g = Graphics.FromHdc(m.WParam);
       g.FillRectangle(new SolidBrush(_backColor), ClientRectangle);
       g.Dispose();
       return;
     }

     base.WndProc(ref m);
}

Here is another example of chnaging backColor to dtp: http://www.codeproject.com/KB/selection/DateTimePicker_With_BackC.aspx

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

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

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

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

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
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
Mitja Bonca 557 Nearly a Posting Maven

Heres an exmample:

private Bitmap transparentImage;
        public Form1()
        {
            InitializeComponent();

            transparentImage = new Bitmap(20, 20);
            Graphics graphics = Graphics.FromImage(transparentImage);
            graphics.FillRectangle(Brushes.Transparent, 0, 0, 20, 20);
            graphics.Dispose();

            DataGridViewImageColumn imageColumn = new DataGridViewImageColumn();
            {
                imageColumn.Name = "imageColumn";
                imageColumn.HeaderText = "Images";
                imageColumn.Width = 100;
                imageColumn.ImageLayout = DataGridViewImageCellLayout.Stretch;
                imageColumn.CellTemplate = new DataGridViewImageCell(false);
                imageColumn.DefaultCellStyle.NullValue = null;
            }
            dataGridView1.Columns.Add("column1", "Column 1");
            dataGridView1.Columns.Insert(1, imageColumn);
            dataGridView1.Rows.Add("item 1", null);
            dataGridView1.Rows.Add("item 2", null);
            dataGridView1.AllowUserToAddRows = false;

            dataGridView1.CellClick += new DataGridViewCellEventHandler(dataGridView1_CellClick);
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1[e.ColumnIndex, e.RowIndex].Value == null)
            {
                OpenFileDialog open = new OpenFileDialog();
                open.Filter = "Image Files(*.png; *.jpg; *.bmp)|*.png; *.jpg; *.bmp";
                if (open.ShowDialog() == DialogResult.OK)
                {
                    Bitmap result = new Bitmap(100, 100);
                    using (Graphics g = Graphics.FromImage((Image)result))
                        g.DrawImage(new Bitmap(open.FileName), 0, 0, 100, 100);
                    dataGridView1[e.ColumnIndex, e.RowIndex].Value = result;
                }
            }
        }

there has some code to be done on the image resizing, but this works. Not you can insert an image from hard disk, with OpenFileDialog() method. And you can only select it ones (31 row - comparison to null value of the cell - you can change that, or remove).

ddanbe commented: Nice. +14
Mitja Bonca 557 Nearly a Posting Maven

Look, why dont you do as I showed you? It will work 100%.

Mitja Bonca 557 Nearly a Posting Maven

Sure it is. What you have to so, is to create a new Form, that will look like a messageBox. Put a textBox on it, and a buttons (Ok, Cancel, or what ever).
Simple.

Mitja Bonca 557 Nearly a Posting Maven

You have to pass a value to the 1st subitem of the listView, like that:

string name = "SomeName";
int id = 2;
ListViewItem lvi = new ListViewItem();
lvi.Text = name;
lvi-Subitems.Add(id.ToString());
listView1.Items.Add(lvi);

If you want to insert in a specific row, you have to create a loop of the listView`s rows:

for(int i = 0; i < listView1.Items.Count; i++)
{
    //same code here as abouve
}
Mitja Bonca 557 Nearly a Posting Maven

This is a base example of using connection string, but it works:

static string connString = @"Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;";
        private YourMethod()
        {
            using (SqlConnection sqlConn = new SqlConnection(connString))
            {
                sqlConn.Open();
                //do inquieries:
                string sqlQuery = @"SELECT ... FROM ... WHERE";
            }
        }

Use your correc connection string!

Mitja Bonca 557 Nearly a Posting Maven

:)
You are welcome. Why I had to work? Hmm, you didnt let me step off, so I had to contine working. (btw, you can add a vote for me :) ).

If there is anything you dont know, come here, we`ll surely help you out.