Mitja Bonca 557 Nearly a Posting Maven

One thing to mention: the code I pasted above is written by heart - so there can be some errors, but I hope there are not :)!

Mitja Bonca 557 Nearly a Posting Maven

You can doit this way:

Random r = new Random();

//in your class:

// 1. Generate those 20 numbers (or what ever lenght) youz want:

int allRows = table1.Rows.Count; //total rows of table one
int myPick = 20; // this is your variable of how many rows random numbers to get!

List<int> myRandoms = GenerateRandomNumbers(allRows, myPick);
List<DataRow> rowsToRemove = new List<DataRow>();
for (int i = 0; i < table1.Rows.Count; i++)
{
      if (myRandoms.Contains(i)) //this will check for the correct row to select into table 2!
      {
            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;
}


//new method to generate random numbers:
private List<int> GenerateRandomNumbers(int maxValue, int NumbersToGet)
{
      List<int> list = new List<int>();
      int number;
      for(int i = 0; i <= NumbersToGet; i++)
     {
           do
           {
                  number = r.Next(maxValue);
           }
           while(!list.Contains(number));
           list.Add(number);
      }
      return list;
}

Include my code too. This is only the main part which was changed.

Mitja Bonca 557 Nearly a Posting Maven

You mean you wanna get 20% of the nummbers (in case we have 100 numberss this means 20 numbers as well).

But not from 1 to 20, but randomly picked up from 1 to 100 (20 numbers somewhere in between)?

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

Im talking about C#`s class: Sytem.Data.DataTable;

I dont know what kind of collection you use, but you should use one of the C# has. Or at least convert to it. And you dont need any class to create.

So, can you show us the code, maybe we can figure something out?

Mitja Bonca 557 Nearly a Posting Maven

1st of all, dataSet does NOT have any rows. DataSet is only a collection of dataTables.
DataTable is the object which has rows - just to make clear.

Then to your issue: use a random class to get a random numbers, and this number you then use to get that many rows from a dataTable, and put then into a new dataTable (the selected one delete). This way you will get two dataTables - and now you can put then both into a dataSet.

Understood?

Mitja Bonca 557 Nearly a Posting Maven

I did an example code how to use Threading and progressBar on two forms.
You can download a project here.

Mitja Bonca 557 Nearly a Posting Maven

I have to divide dataset into training dataset(80%) and test dataset (20%) using random sampling.

What do you mean by dividing?

Mitja Bonca 557 Nearly a Posting Maven

try using Threading:

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

Namespace WFInvoke
	Public Partial Class Form1
		Inherits Form
		Public Sub New()
			InitializeComponent()
		End Sub

		<STAThread> _
		Private Shared Sub Main()
			Application.Run(New Form1())
		End Sub

		Private Sub IncrementMe()
			'Instead of this loop use your code for converting
			For i As Integer = 0 To 99
				UpdateProgress()
				Thread.Sleep(100)
			Next
			If InvokeRequired Then
				Invoke(New MethodInvoker(AddressOf Close))
			Else
				Close()
			End If
		End Sub

		Private Sub UpdateProgress()
			If Me.progressBar1.InvokeRequired Then
				Dim updateProgress__1 As MethodInvoker = AddressOf UpdateProgress
				progressBar1.Invoke(updateProgress__1)
			Else
				progressBar1.Increment(1)
			End If
		End Sub

		Private Sub button1_Click(sender As Object, e As EventArgs)
			Dim threadStart As ThreadStart = AddressOf IncrementMe
			threadStart.BeginInvoke(Nothing, Nothing)
		End Sub
	End Class
End Namespace
Mitja Bonca 557 Nearly a Posting Maven

YOu wanna show a progressBar on another Form?
Simply create the method to update progressBar (like is mine "UpdateProgress" method) on another form, mark it as Public, so you can access to it from the main form.
Thats all.

Mitja Bonca 557 Nearly a Posting Maven

I can see you use DataTable as a binding source to the dgv control.
So you can use filtering on the dataTable, with a help of "SELECT" method:

Private table As DataTable
Public Sub New()
	InitializeComponent()
	table = New DataTable("MyTable")
	table.Columns.Add("Id", GetType(Integer))
	table.Columns.Add("Name", GetType(String))
	table.Columns.Add("Car", GetType(String))

	table.Rows.Add(1, "Name 1", "Ferrari")
	table.Rows.Add(2, "Name 2", "Jaguar")
	table.Rows.Add(3, "Name 3", "Ferrari")
	table.Rows.Add(4, "Name 4", "Porsche")
	table.Rows.Add(5, "Name 5", "Ferrari")
	table.Rows.Add(6, "Name 6", "Porsche")

	dataGridView1.DataSource = New BindingSource(table, Nothing)
End Sub

Private Sub button1_Click(sender As Object, e As EventArgs)
	Dim myFilter As String = "Ferrari"
	Dim newTable As DataTable = New DataView(table, "Car = '" & myFilter & "'", "Name DESC", DataViewRowState.CurrentRows).ToTable()
	dataGridView1.DataSource = Nothing
	dataGridView1.DataSource = New BindingSource(newTable, Nothing)
End Sub

NOTE: "Car = 'Ferrari' is an actual filter. So in your case myFilter variable is set to some textBox, which will be used to filter dgv.

Mitja Bonca 557 Nearly a Posting Maven

Take a look at this simple example, which shows how to use a new thread (thread is busy with some loop), and shows how to use delegates to update progressBar:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
 
namespace WFInvoke
{
    public partial class Form1 : Form
    {     
        public Form1()
        {
            InitializeComponent();
        }
 
        [STAThread]
        static void Main()
        {
            Application.Run(new Form1());
        }
 
        private  void IncrementMe()
        {
            for (int i = 0; i < 100; i++)
            {
                UpdateProgress();
                Thread.Sleep(100);
            }
            if(InvokeRequired)
            {
                Invoke(new MethodInvoker(Close));
            }
            else
            {
                Close();
            }
        }
 
        private  void UpdateProgress()
        {
            if (this.progressBar1.InvokeRequired)
            {
                MethodInvoker updateProgress = UpdateProgress;
                progressBar1.Invoke(updateProgress);
            }
            else
            {
                progressBar1.Increment(1);
            }
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            ThreadStart threadStart = IncrementMe;
            threadStart.BeginInvoke(null, null);
        }       
    }
}
Mitja Bonca 557 Nearly a Posting Maven

Mate, my code works fine, you did something wrong. Ok, let me rephrase it a bit:

//on ther from, from which you want to call the method (instead of button click event);
private void CallMethodOnOtherForm() //this is maybe some of your buttons from where you wanna open 2nd form!!
{
     OtherForm of = new OtherForm();
     of.MethodToExecute();
     of.Show();
}

//other form which has a button click event:
private void button_Click()
{
     //instead of having code in here, I created new method, which you an call from this form..
     MethodToExecute();
}

public void MethodToExecute() //call this method
{
    //... or from other form!!
 
    //the method to execute:
    int a = 1 + 2;
    MessageBox.Show("Sum is: " + a.ToStirng());
}
Mitja Bonca 557 Nearly a Posting Maven

What path? This is the one you wrote, how do we know your path mate??!

I have changed the code a bit, to what I think its best:

'WRITE CORRECT PATH FILE HERE:
Dim filePath As String = "C:\\Documents and Settings\\Mitchikels\\My Documents\\AVDC\\Downloaded Files"
If System.IO.Directory.Exists(filePath) Then
	Dim myDir As New System.IO.DirectoryInfo(filePath)
	For Each myFile As System.IO.FileInfo In myDir.GetFiles("*.mp3")
		Dim lvwItem As New ListViewItem()
		lvwItem.Text(System.IO.Path.GetFileNameWithoutExtension(myFile.FullName))'1st column		
		lvwItem.SubItems.Add(myFile.Extension)'2nd column		
		length = ((myFile.Length \ 1024) \ 1024).ToString()'if this lenght variable is type of string!!		
		'BTW Check for Correction of the math formula!!!
		length = [String].Format("0:0.00", lenght)
		lvwItem.SubItems.Add(length & " " & sizetext)
	Next
End If
Mitja Bonca 557 Nearly a Posting Maven

To access to particular dataBase, you only need the correct connection string.

Mitja Bonca 557 Nearly a Posting Maven

Where exactly do you get this error? Use a debugger (set a break point to check on whcich line error occurs.

Mitja Bonca 557 Nearly a Posting Maven
String strFile = File.ReadAllText("c:\\File1.txt");
strFile = strFile.Replace("oldvalue", "newvalue");
File.WriteAllText("c:\\File1.txt", strFile);
Mitja Bonca 557 Nearly a Posting Maven

Then there is no such file. Why you dont create it and then insert into it at the same time? This way you for sure will not get this error:

Dim path As String = "C:\MyFolder\myFiletxt"
'write your own file path - full one (no need if file exists, just make sure Directories exist!!!
Using fs As New FileStream(path, FileMode.OpenOrCreate)
	Using tw As TextWriter = New StreamWriter(fs)
			'
		tw.WriteLine("some text in here") 'use your own text
	End Using
End Using
Mitja Bonca 557 Nearly a Posting Maven

Try to write a full path to the file:

Dim writer As New System.IO.StreamWriter("C:\MyFolder\myFile.txt", False)
Mitja Bonca 557 Nearly a Posting Maven

What kind of data do you have, and what to replace?
thx for the answer.

Mitja Bonca 557 Nearly a Posting Maven

Im glad you are happy.
You are welcome. YOu can vote up if helpful or mark as answered.
bye, bye

Mitja Bonca 557 Nearly a Posting Maven

There is. use SelectionAlignment property:

richTextBox1.SelectionAlignment = HorizontalAlignment.Center
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

No need. Just ask here.

Mitja Bonca 557 Nearly a Posting Maven

YOu wanna pass data from ListView to the TextBoxes on some other Form (and create them as many as needed too)?

If so, 1st of all do NOT change Modifiers property to public. Leave them as private, and rather gather all the data from listView, put then into some collection (like genetic List<T>) and pass then to Form2 into constructor. There you create new TextBoxes, based on the number of items in a List<T>, and populate them from the list.

Mitja Bonca 557 Nearly a Posting Maven

If you wanna store more picture of one patient, you cannot (or its not a good practice) to store more then one into one cell of a table.
Instead of that, I strongly suggest you to create a new Table which will be only for patient`s images. It will have only a foreigh key of patient, image name, and image it self (in byte array).

This way you can store as many pictures as you like for one patient. So DB shoud look like:

TABLENAME: field1, fields2, ...

PATIENT: PatientID, Name, LastName, ...
PATIENT_PICTURES: PatientID_FK(int), ImageName(varchar,50), Picture(byte)

You got my point?

Mitja Bonca 557 Nearly a Posting Maven

You still didnt answer on ny question: Do you wanna loop through the images of patients? Will you have any buttons (Next, Back)?

If you you can do an ImageList, and loop through them while pressing on one of those tow buttons.

Mitja Bonca 557 Nearly a Posting Maven

Do you wanna add only one picture?
why you call this code:

byte[] arrimage = dt.Rows[0][0];

As far as I can see from this code, you get image(s) from dataBase. And you wanna show it/them in pictureBox.
Only one, or you wanna show more? If more, then you create a button Next and Back to loop through images (and data of Patients - if there are any).

Am I right?

Mitja Bonca 557 Nearly a Posting Maven

It looks like you need to create a new Thread. This will salve the issue of frozen form. Put the time consuming code onto this thread, and use a progressBar to show the updating of the work.
Instead of using Thread you can use Backgroundworker class.

Mitja Bonca 557 Nearly a Posting Maven

hmm now i have a problem : how can i separate this images?

What do you mean? Dont you have images in a ImageList or something?

Mitja Bonca 557 Nearly a Posting Maven

YOu have to use CellValidating event:

Private Sub dataGridView1_CellValidating(ByVal sender As Object, _
    ByVal e _
    As DataGridViewCellValidatingEventArgs) _
    Handles dataGridView1.CellValidating

    Me.dataGridView1.Rows(e.RowIndex).ErrorText = ""
    Dim newInteger As Integer

    ' Don't try to validate the 'new row' until finished 
    ' editing since there
    ' is not any point in validating its initial value.
    If dataGridView1.Rows(e.RowIndex).IsNewRow Then Return
    If Not Integer.TryParse(e.FormattedValue.ToString(), newInteger) _
        OrElse newInteger < 0 Then

        e.Cancel = True
        Me.dataGridView1.Rows(e.RowIndex).ErrorText = "the value must be a non-negative integer"

    End If
End Sub

For more info check here.
Mitja Bonca 557 Nearly a Posting Maven

On which line do you get this error? Is it maybe on line 33 in this line of code:

Timer1.Interval = 100

It seems you didnt initialize a new timer. On form load (or in constructor) instanitate a new instance of a timer:

Dim Timer1 As New Timer()
Mitja Bonca 557 Nearly a Posting Maven

The best and simpliest option is to use MaskedTextBox (instead of TextBox).
You only have to define the mask property:

maskedTextBox1.Mask = "000,000,000,000.00"
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

Maybe this will help:

Imports System.Windows.Forms
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared

Namespace WindowsApplication1
	Public Partial Class Form1
		Inherits Form
		Public Sub New()
			InitializeComponent()
		End Sub

		Private Sub button1_Click(sender As Object, e As EventArgs)
			Dim cryRpt As New ReportDocument()
			cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt")

			Dim crtableLogoninfos As New TableLogOnInfos()
			Dim crtableLogoninfo As New TableLogOnInfo()
			Dim crConnectionInfo As New ConnectionInfo()
			Dim CrTables As Tables

			crConnectionInfo.ServerName = "YOUR SERVERNAME"
			crConnectionInfo.DatabaseName = "DATABASE NAME"
			crConnectionInfo.UserID = "USERID"
			crConnectionInfo.Password = "PASSWORD"

			CrTables = cryRpt.Database.Tables
			For Each CrTable As CrystalDecisions.CrystalReports.Engine.Table In CrTables
				crtableLogoninfo = CrTable.LogOnInfo
				crtableLogoninfo.ConnectionInfo = crConnectionInfo
				CrTable.ApplyLogOnInfo(crtableLogoninfo)
			Next

			cryRpt.Refresh()
			cryRpt.PrintToPrinter(1, True, 0, 0)

		End Sub
	End Class
End Namespace
Mitja Bonca 557 Nearly a Posting Maven
//in your method:
        string text = "Some text to crypt";
        string crypt = Crypt(source);

        //calls:
        private string Crypt(string input)
        {
            MD5CryptoServiceProvider hasher = new MD5CryptoServiceProvider();
            byte[] data = hasher.ComputeHash(Encoding.UTF8.GetBytes(input));

            StringBuilder sb = new StringBuilder();
            foreach (byte b in data)
                sb.AppendFormat("{0:x2}", b); 

            return (sb.ToString());
        }
Mitja Bonca 557 Nearly a Posting Maven

Then you need some sql query, like:

SqlConnection sqlConn = new SqlConnection("connString");
SqlCommand cmd = new SqlCommand();
stirng query = @"DELETE FROM MyTable WHERE MyDateColumn < @myDate";
cmd.Parameters.Add("@myDate", SqlDbType.DateTime).Value = DateTime.Now.AddDays(-1);
Mitja Bonca 557 Nearly a Posting Maven

What is your DB structure? Would you like to delete whole row (if date is older then 1 day)?

Mitja Bonca 557 Nearly a Posting Maven

Yep.

SqlCommand cmd = new SqlCommand(@"query", "connection");
SqlDataReader reader = cmd.ExecuteReader();
if(reader.HasRows)
{
     
}
else
     MessageBox.Show("No rows found.");
Mitja Bonca 557 Nearly a Posting Maven

You are welcome.
bye

Mitja Bonca 557 Nearly a Posting Maven

to create events, put the code in form constructor.

//on form1:
public Fomr1()
{
     InitializeComponent();
     this.Load += new System.EventHandler(Form1_Load);
}

private void Form1_Load(object sender, EventArgs e)
{
     //this will now fire at loading time!
}
Mitja Bonca 557 Nearly a Posting Maven

Your error is in the Update query. You mixed up one and double quotes. Do it this way:

sqlSOPDept.CommandText = "UPDATE dbo.docHeader SET revision = '" & newRev & "' WHERE model = '" & Convert.ToString(Me.cmbModel.SelectedValue.ToString) & "' AND part = '" & Convert.ToString(Me.cmbPart.SelectedValue.ToString) & "'"
Mitja Bonca 557 Nearly a Posting Maven

I hope you didnt use the exact code I pasted?!
You have to change the Sql query (to suit your dataBase design) and you have to use your connection string while creating a new reference of SqlConnection class.

And one more thing: I boxes the retreived value to integer. Is the column type of integer? If not, change to the right one.

If this is not it, please tell me what the error is!

Mitja Bonca 557 Nearly a Posting Maven
int myVariable = 0;
            using (SqlConnection sqlConn = new SqlConnection("connString"))
            {
                using (SqlCommand cmd = new SqlCommand(@"SELECT MAX(MyColumnName) FROM MyTable", sqlConn))
                {
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            if (reader.GetValue(0) != DBNull.Value)
                                myVariable = (int)reader[0];
                        }
                    }
                }
            }
Mitja Bonca 557 Nearly a Posting Maven

Why would you change the primary key? You shouldn`t do that. Thats why Primary keys are for - they stay the same until forever. What in case if this table of yours is connected to some other table, abnd there is a foreign key? you will get different data when you will try to equl both primary key and foreign key.
So I would never do this.
One more thing to add: if you will change ids why are they for anyway? They are pointless to use.

Mitja Bonca 557 Nearly a Posting Maven

In my opinion, you have way too much code of DGV.
What you need is only to use DataSource property.

just and only this:

SqlConnection main_user_con = new SqlConnection();
            main_user_con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\clubdb.mdf;Integrated Security=True;User Instance=True";
            string con_string = "select * from users";
            SqlDataAdapter userda = new SqlDataAdapter(con_string, main_user_con);
            DataTable userdt = new DataTable();
            userda.Fill(userdt);
            userdgv.AutoGenerateColumns = false;
            userdgv.DataSource = new BindingSource(userdt, null); //use it this way

And then you only add a code to add a new column - checkBox column.

Mitja Bonca 557 Nearly a Posting Maven

Hi, would you mind to share your code here with us? Will be easier to salve the problem.
Show us how you bind DGV to the dataTable (and stuff).

Mitja Bonca 557 Nearly a Posting Maven

YOu can do a windows application, which will work fine over the net (like msn, skype,..).
You need to create a server (which is always good to have, to check what going on around) and then you need clients to log on to server and chat to each other.
One simple example you can find here.

Mitja Bonca 557 Nearly a Posting Maven

PLEASE answer on ALL the question? Cant yoiu guys read these days?

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]);
}