Mitja Bonca 557 Nearly a Posting Maven

Put some boolean flag into the code, so you can say to the code when it can be used and when not - but you.

I mean something like:

bool bFlag = false;

void buttonEnable()//event of button
{
    bFlag = true;  // this will prevent firing the ItemChecked code in the 1st go-through
}

void ItemChecked() //event of listView
{
   if(!bflag)
   {
       // put yout code in this even in here...
   }
   else
       bFlag = false;
}
Mitja Bonca 557 Nearly a Posting Maven

Make it simple:

Random rand = new Random();
            int[] vett = new int[16];
            for (int i = 0; i < vett.Length; i++)
            {
                vett[i] = rand.Next(1, vett.Length + 1);
                Console.WriteLine(vett[i]);
            }
Mitja Bonca 557 Nearly a Posting Maven

Do:

Double.Parse(txtHoursWorked.Text) * Double.Parse(delstHourlyRate.SelectedItem) + Double.Parse(txtHoursOvertime.Text) * DoubleRate
Mitja Bonca 557 Nearly a Posting Maven

You are a BAD reader mate.
If you would read my post in some other tread of yours, you would see I told you you can NOT do mathematical opearations over stirngs.
Text property or textbox, SelectedItem of listBox, are type of string, and thats why you cannot do math operations over them - I repeat.

You are ONLY allowed to do math operations over real number types, like integer, decimal, double, float, uint, ulong.

So what to do? You already have examples that we gave you. Convert or Parse to particulat type.

Mitja Bonca 557 Nearly a Posting Maven

try:

strsql = "delete from cg_security_user_right where user_id = '" & TextBox1.Text & "' role_id = '" & TextBox2.Text & "'"
Mitja Bonca 557 Nearly a Posting Maven

I will agree with Momerath, but if you still insist with depliying sql server into application, then you can read here for more info.

Mitja Bonca 557 Nearly a Posting Maven

Tell us the exact formulas you use for calculating depreciation (the real formulas), maybe we can help you then...

Mitja Bonca 557 Nearly a Posting Maven

I dount we can help you out with this, maybe you didnt use the correct formulas for calculation. Code it self looks fine.

Mitja Bonca 557 Nearly a Posting Maven

Please try using break point, and go through the code line by line, and you will find out where exactly the problem is.
I told you maybe I didnt set the correct value, I used Integer for some of them, maybe you have some other type. Check them out!!!

Mitja Bonca 557 Nearly a Posting Maven

Set both properties SelectionStart to zero and SelectionLength to the lenght of the text inside:

textBox1.SelectionStart = 0
textBox2.SelectionLength = textBox1.Text.Lenght
Mitja Bonca 557 Nearly a Posting Maven

Exactly on which line the error occurs?

Mitja Bonca 557 Nearly a Posting Maven

Remember:
1. you cannot do math operations over strings; you MUST convert them to appropriate type (I used integers, if trey are not, change them to appropriate type!!
2. messagebox shows strings, so if there is any value not-a-string, convert (or parse) it to stirng.
So do:

MessageBox.Show("Basic hours worked: " + txtHoursWorked.Text & vbCr & vbLf & 
"Hourly rate of pay: " & lstHourlyRate.SelectedItem.ToString() & vbCr & vbLf & 
"Basic pay: " & (Integer.Parse(txtHoursWorked.Text) * Integer.Parse(lstHourlyRate.SelectedItem.ToString())) & vbCr & vbLf & 
"Overtime hourly rate: " & DoubleRate & vbCr & vbLf & 
"Overtime pay: " & OvertimePay & vbCr & vbLf & 
"Total pay: " & (Integer.Parse(txtHoursWorked.Text) * Integer.Parse(lstHourlyRate.SelectedItem.ToString())))

If "vbCr & vbLf" dones not do, try using "Environment.NewLine"
Hope it helps,
bye

Mitja Bonca 557 Nearly a Posting Maven

You have to use StringBuilder class to write into it 1st, then when you are done with reading files, you do the Write thing.
So your code shoud look (in sepearate methods):

class Program
    {
        static void Main(string[] args)
        {
            string readFrom = @"F:\abc\";
            string writeTo = @"F:\test.txt";
            StringBuilder sb = Read(readFrom);
            Write(writeTo, sb);
        }

        private static StringBuilder Read(string filePath)
        {
            StringBuilder sb = new StringBuilder();
            DirectoryInfo di = new DirectoryInfo(filePath);
            FileInfo[] files = di.GetFiles("*.txt");
            foreach (FileInfo fri in files)
            {
                using (StreamReader streamReader = fri.OpenText())
                {
                    string line;
                    for (int count = 0; count < 10; count++)
                    {
                        line = streamReader.ReadLine();
                        string[] items = line.Split(' ');
                        float myInteger = float.Parse(items[1]);
                        sb.AppendLine(myInteger.ToString()); //this will write line byline (you can use Append() method only to write in a single line
                        //but you will neeed separator then (I think)
                    }
                }
            }
            return sb;
        }

        private static void Write(string filePath, StringBuilder sb)
        {
            using (StreamWriter file = new StreamWriter(filePath, true))
            {
                file.WriteLine(sb.ToString());
                file.Close();
            }
        }
    }
Mitja Bonca 557 Nearly a Posting Maven

I really suggest you to read any/some book(s) mate. It would really do good for you. You are constantly asking basic questions, that you should know it easily, if you are coding for at least a couple of months.
No offence, but this is how it is.
We are here to help, not to do all the code instead of you.
You come up with some code, which obviously not working, and with some crappy issue explanation, and then you want from us to save in a god`s way your problem.
This is just not the way we work. Sorry mate.

Mitja Bonca 557 Nearly a Posting Maven

This is the most simpliest random number selection (form 1 to 33 - take 14 random numbers):

Dim r As New Random()
Dim listOfNums As New List(Of Integer)()
For i As Integer = 1 To 33
	While True
		Dim num As Integer = r.[Next](1, 34)
		If Not listOfNums.Contains(num) Then
			listOfNums.Add(num)
			Exit While
		End If
	End While
Next
Mitja Bonca 557 Nearly a Posting Maven

Check it here.

Mitja Bonca 557 Nearly a Posting Maven

Please write some notes on the lines where errors are.

Mitja Bonca 557 Nearly a Posting Maven

HEre s the code exampe, a mid more sophisticated:

Dim r As New Random()
Dim students As New List(Of Student)()
'I will create 33 stdents in a loop (you fil them your way...)
For i As Integer = 1 To 33
	Dim s As New Student()
	s.Id = i
	s.Name = "Student Name " & i
	s.bSelected = False
	students.Add(s)
Next
'now select 14 random student:
Dim selectedStudents As New List(Of Student)()
For i As Integer = 0 To 13
	While True
		Dim index As Integer = r.[Next](0, students.Count)
		If Not selectedStudents.Contains(students(index)) Then
			selectedStudents.Add(students(index))
			Exit While
		End If
	End While
Next

'prove of selected students:
Dim sb As New StringBuilder()
For i As Integer = 0 To selectedStudents.Count - 1
	sb.AppendLine(String.Format("{0}. ID: {1}, name: {2}", i + 1, selectedStudents(i).Id, selectedStudents(i).Name))
Next
Console.WriteLine(sb.ToString())
Console.ReadLine()
Mitja Bonca 557 Nearly a Posting Maven

Rather create a List<T> where T is a class object (student name, ...)

Mitja Bonca 557 Nearly a Posting Maven

try:

If listBox2.Items.Contains(listBox1.SelectedItem.ToString) Then
    MessageBox.Show("This item is in listbox 2.")
End If
Mitja Bonca 557 Nearly a Posting Maven

You can vote +1 and mark as answered.
Best regards.

?

Mitja Bonca 557 Nearly a Posting Maven

You can use SqlDataReader and set value to it:

SqlConnection conn = new SqlConnection("connString");
string query = @"SELECT SUM(columnName) FROM MyTable";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataReader reader = cmd.ExecuteReader();
if(reader.Read())
    textBox1.Text = reader[0].ToString();
reader.Dispose();
cmd.Dispose();
conn.Dispose();
Mitja Bonca 557 Nearly a Posting Maven
Mitja Bonca 557 Nearly a Posting Maven

Ok, I took an hour only for your, to do the code insread of you.
It works like you wanted, so like charm :)

Take a look, and let me know:

Public Sub New()
	Dim table1 As New DataTable("t1")
	Dim table2 As New DataTable("t2")
	table1.Columns.AddRange(New DataColumn() {New DataColumn("ID", GetType(Integer)), New DataColumn("Name", GetType(String)), New DataColumn("Age", GetType(Integer)), New DataColumn("ACOLUMN3", GetType(Boolean)), New DataColumn("ACOLUMN4", GetType(Boolean)), New DataColumn("ACOLUMN5", GetType(Boolean))})
	table2.Columns.AddRange(New DataColumn() {New DataColumn("ID", GetType(Integer)), New DataColumn("Name", GetType(String)), New DataColumn("Age", GetType(Integer)), New DataColumn("BCOLUMN3", GetType(Boolean)), New DataColumn("BCOLUMN4", GetType(Boolean)), New DataColumn("BCOLUMN5", GetType(Boolean))})

	table1.Rows.Add(1, "Jon", 23, True, False, False)
	table1.Rows.Add(2, "Jane", 17, False, True, True)
	table1.Rows.Add(3, "Joe", 29, True, True, True)
	table2.Rows.Add(1, "Jon", 23, False, False, True)
	table2.Rows.Add(4, "Joey", 17, True, False, True)
	table2.Rows.Add(3, "Joe", 29, False, False, False)

	'specify which columns are in both tables:
	Dim myColumns As String() = {"ID", "Name", "Age"}
	Dim myColumns2 As String() = {"ID", "Name", "Age", "BCOLUMN3", "BCOLUMN4", "BCOLUMN5"}

	Dim combined As New DataTable()
	'get column names from table1 ansd and name it:
	combined = table1.Clone()
	combined.TableName = "t1_t2"


	'add other columns from table2:
	For Each column As DataColumn In table2.Columns
		If Not myColumns.Contains(column.ColumnName) Then
			combined.Columns.Add(column.ColumnName, GetType(String))
		End If
	Next

	'set to false all cells in advacne:

	'add data from table1 to combined:
	For i As Integer = 0 To table1.Rows.Count - 1
		combined.Rows.Add()
		'set cells to false:
		SetCellsToFalse(i, 9, combined)
		For j As Integer = 0 To table1.Rows(i).ItemArray.Length - 1
			combined.Rows(i)(j) = table1.Rows(i)(j)
		Next
	Next

	'add data from table2 to combined:
	For i As Integer = 0 To table2.Rows.Count …
Mitja Bonca 557 Nearly a Posting Maven

lol, its a glitch in the code.
I wrote the code by heart (this is what I do all the time), I actually dont use VS any longer :)

Mitja Bonca 557 Nearly a Posting Maven

Otherwise you can do parameterised query:

sql1 = "update po_detail set po_number= @param1 where po_number=0;"
        cnn1 = New OleDbConnection(connectionString)
        cnn1.Open()
        cmd1 = New OleDbCommand(sql1, cnn1)
        cmd1.Parameters.Add("@param1", OleDbType.Int).Value = Integer.Parse(txtPoNo.Text) ' NOTE: CHECK THE TYPE OF YOUR COLUMN IN DB!!!
        cmd1.ExecuteNonQuery()
Mitja Bonca 557 Nearly a Posting Maven

try like:

"update po_detail set po_number= '" & txtPoNo.Text & "' where po_number = 0"

or if your database column is type of integer:

"update po_detail set po_number= '" & Integer.Parse(txtPoNo.Text) & "' where po_number = 0"
Mitja Bonca 557 Nearly a Posting Maven

1. Tell me one thing, how do you populate these 2 listBoxes?
Because so far I havent seen this code (and you actually didnt tell us).

2. And tell me one more thing, when some item is selected in listbox1, when you wanna transfer to listbox2, On which index do you wanna put it? On the same as it was in listBox1, or on last place?

Mitja Bonca 557 Nearly a Posting Maven

I did an example code how you can itterate through textBoxes on enter key press.
NOTE: my example uses only 3 textbox controls. If your have more, please enter all of them into textBox array!!

Code:

Public Partial Class Form1
	Inherits Form
	Private tbs As TextBox()
	Public Sub New()
		InitializeComponent()
		tbs = New TextBox() {textBox1, textBox2, textBox3}
		For i As Integer = 0 To tbs.Length - 1
			tbs(i).Tag = i
			tbs(i).KeyDown += New KeyEventHandler(AddressOf textBoxes_KeyDown)
		Next
		tbs(0).Focus()
	End Sub

	Private Sub textBoxes_KeyDown(sender As Object, e As KeyEventArgs)
		Dim tb As TextBox = TryCast(sender, TextBox)
		If tb IsNot Nothing Then
			If e.KeyCode = Keys.Enter Then
				Dim tag As Integer = CInt(tb.Tag)
				If tag = 2 Then
					tbs(0).Focus()
				Else
					tbs(tag + 1).Focus()
				End If
			End If
		End If
	End Sub
End Class
Mitja Bonca 557 Nearly a Posting Maven

Sorry, this way:

Dim rows As DataRow() = table.[Select]("right_id = '" & rightID & "' AND user_id = '" & userID & "'")
Mitja Bonca 557 Nearly a Posting Maven

DO:

Dim rows As DataRow() = "Select right_id = '" & rightID & "' AND user_id = '" & userID & "'"
Mitja Bonca 557 Nearly a Posting Maven

is your listbox databound? do you use DisplayMember and Valuemember properties?
If you DO NOT, you can NOT get SelectedValue property.

Mitja Bonca 557 Nearly a Posting Maven

Based on my previous code:

....
For Each row As DataRow In rows
	table.ImportRow(row)
Next
'pass the data from table to textboxes:
textBoxName.Text = tableNew.Rows(0)(0)
' 1st zero is row index, 2nd zero is column index - 1st row and 1st column
'for other do the same...
Mitja Bonca 557 Nearly a Posting Maven

i am working on a project for booking management system for photographers..
can anyone suggest some tables and content for the project....!

Booking man. system for photographers? What could that be?
How can we help you, if you dont know how to start? This is you and only you here who should know how to build a database structure. How can we know that?
Dont you think?
As said, we are here for HELP, not for doing all the thinking and code for you guys.
Sorry, but these are forum`s ruels too.

Mitja Bonca 557 Nearly a Posting Maven

You would like to get only the rows of customers that have the written lastname in textBox, if I got you right?

This means you have to do the filtering over dataSet to get new DataRows (array of them) and them convert this array back to dataset to bind it again with datagridview.
This can be done like this.

Dim ds As DataSet
'** means:
'check for correct name of the table in dataset, you can still use index like [0] if this is 1st or only table in dataset

    
    'class variable where you have all the data of customers and its bind to datagridview
    Private Sub DoTheFiltering()
        Dim filter As String = txtCustSearchNewBooking.Text
        Dim query As String = "LastName like '%" & filter & "'"
        Dim rows() As DataRow = ds.Tables("Customers").Select(query)
        '**
        Dim tableNew As DataTable = New DataTable("SelectedCustomers")
        'create columns for table:
        For Each column As DataColumn In ds.Tables("Customers").Columns
            tableNew.Columns.Add(New DataColumn(column.ColumnName, GetType(System.String)))
        Next
        'adding rows to table:
        For Each row As DataRow In rows
            table.ImportRow(row)
        Next
        'bind new datasource to dgv:
        dataGridView.DataSource = Nothing
        'resetting datasource
        dataGridView.DataSource = ne
        BindingSource(tableNew, Nothing)
    End Sub

This should do it.

Mitja Bonca 557 Nearly a Posting Maven

You can vote +1 and mark as answered.
Best regards.

Mitja Bonca 557 Nearly a Posting Maven

And 2nd task`s code:

using System; 

namespace CustomerApp 
{
   public class Customer 
   { 
       public string FirstName { get; set; }
       public string LastName { get; set; }
       
       public Customer(stirng _first, string _last)
       {
           this.FirstName = _first;
           this.LastName = _last;
       }

       public Customer(string _first)
       {
           this.FirstName = _first;
       }
   }
}

There is no methods needed in this task, at least none is called in WriteLine() method, only properties are called.

Mitja Bonca 557 Nearly a Posting Maven

No answer...
Anyway, I`m a good person, and I like to help, that`s why I did your 1st homework.
TAKE A SLOW LOOK through the code, and try to learn how its done.
Here`s the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mar01_2
{
    class Program
    {
        static void Main(string[] args)
        {
            Student s = new Student(1, "John", "C#");
            //calling methods:
            int feePaid = s.Payment(900);
            //checking is th course was paid in total
            s.DueAmount(); 
            //printing:
            Console.WriteLine(s.Print());
            Console.WriteLine(s.Print2());
            Console.ReadLine();
        }
    }

    class Student
    {
        public int RollNumber { get; set; }
        public string StudentName { get; set; }
        public string CourseName { get; set; }
        public int FeePaid { get; set; }
        public int TotalFee { get; private set; }

        public Student(int rollNo, string name, string course)
        {
            this.RollNumber = rollNo;
            this.StudentName = name;
            this.CourseName = course;

            if (CourseName == "C#")
                TotalFee = 2000;
            else if (CourseName == "ASP.NET")
                TotalFee = 3000;
        }

        public int Payment(int amount)
        {
            return FeePaid += amount;
        }

        public string Print()
        {
            return string.Format("Roll number: {0}\r\nName: {1}\r\nCourse: {2}\r\nFee paid: {3}.",
                RollNumber, StudentName, CourseName, FeePaid);
        }

        //added by my self (its important):
        public string Print2()
        {
            if (TotalFee > 0)
                return string.Format("Course fee was not paid it total. Its still missing {0} out of {1}.",
                    TotalFee, TotalFee+FeePaid);
            else
                return string.Format("Course is paid it total.");
        }

        public void DueAmount()
        {
            TotalFee -= FeePaid;
        }
    }
}
Mitja Bonca 557 Nearly a Posting Maven

School stuff, right?
We should not suppose to do the code instead of you, you know.
You do have some code, so what parts you do NOT understand, from what you have to do from your 1st task?
And please, do not post more then ONE issue at a time.

Mitja Bonca 557 Nearly a Posting Maven

If so, here`s an exampe:

Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs)
	Dim filePath As String = "C:\Myfile.txt"
	'use your path!
	If Not File.Exists(filePath) Then
		Dim fs As FileStream = File.Create(filePath)
		fs.Close()
	End If
	Using fs As New FileStream(filePath, FileMode.CreateNew, FileAccess.Write)
		Using sw As New StreamWriter(fs)
			For Each item As String In listBox1.Items
				sw.WriteLine(item)
			Next
		End Using
	End Using
End Sub
Mitja Bonca 557 Nearly a Posting Maven

I have a listbox and would like to save the items...

Save them where? To a database, to excel, to text file,..?

Mitja Bonca 557 Nearly a Posting Maven

Good question Momerath, but I doubt, otherwise, he wouldnt ask us. Its quite some code, if you want it to make it up for you.
Tell us what you know already, so you make it easier for us.

Mitja Bonca 557 Nearly a Posting Maven

OR:
You'll have to add support to the ListView class so you can be notified about scroll events. Add a new class to your project and paste the code below. Compile. Drop the new listview control from the top of the toolbox onto your form. Implement a handler for the new Scroll event.

Imports System.Windows.Forms

Class MyListView
	Inherits ListView
	Public Event Scroll As ScrollEventHandler
	Protected Overridable Sub OnScroll(e As ScrollEventArgs)
		Dim handler As ScrollEventHandler = Me.Scroll
		RaiseEvent handler(Me, e)
	End Sub
	Protected Overrides Sub WndProc(ByRef m As Message)
		MyBase.WndProc(m)
		If m.Msg = &H115 Then
			' Trap WM_VSCROLL
			OnScroll(New ScrollEventArgs(CType(m.WParam.ToInt32() And &Hffff, ScrollEventType), 0))
		End If
	End Sub
End Class

Beware that the scroll position (ScrollEventArgs.NewValue) isn't meaningful, it depends on the number of items in the ListView. I forced it to 0. Following your requirements, you want to watch for the ScrollEventType.EndScroll notification to know when the user stopped scrolling. Anything else helps you detect that the user started scrolling. For example:

Private mLastScroll As ScrollEventType = ScrollEventType.EndScroll

Private Sub myListView1_Scroll(sender As Object, e As ScrollEventArgs)
	If e.Type = ScrollEventType.EndScroll Then
		scrollEnded()
	ElseIf mLastScroll <> ScrollEventType.EndScroll Then
		scrollStarted()
	End If
	mLastScroll = e.Type
End Sub
Mitja Bonca 557 Nearly a Posting Maven

Add a new class into your project and paste this code:

Imports System.Windows.Forms

Public Class BetterListBox
	Inherits ListBox
	' Event declaration
	Public Delegate Sub BetterListBoxScrollDelegate(Sender As Object, e As BetterListBoxScrollArgs)
	Public Event Scroll As BetterListBoxScrollDelegate
	' WM_VSCROLL message constants
	Private Const WM_VSCROLL As Integer = &H115
	Private Const SB_THUMBTRACK As Integer = 5
	Private Const SB_ENDSCROLL As Integer = 8

	Protected Overrides Sub WndProc(ByRef m As Message)
		' Trap the WM_VSCROLL message to generate the Scroll event
		MyBase.WndProc(m)
		If m.Msg = WM_VSCROLL Then
			Dim nfy As Integer = m.WParam.ToInt32() And &Hffff
			If Scroll IsNot Nothing AndAlso (nfy = SB_THUMBTRACK OrElse nfy = SB_ENDSCROLL) Then
				RaiseEvent Scroll(Me, New BetterListBoxScrollArgs(Me.TopIndex, nfy = SB_THUMBTRACK))
			End If
		End If
	End Sub
	Public Class BetterListBoxScrollArgs
		' Scroll event argument
		Private mTop As Integer
		Private mTracking As Boolean
		Public Sub New(top As Integer, tracking As Boolean)
			mTop = top
			mTracking = tracking
		End Sub
		Public ReadOnly Property Top() As Integer
			Get
				Return mTop
			End Get
		End Property
		Public ReadOnly Property Tracking() As Boolean
			Get
				Return mTracking
			End Get
		End Property
	End Class
End Class

Build your project, then drop a BetterListBox from the top of your toolbox onto your form. Add several items, enough to get a scrollbar. Write a handler for the new Scroll event, something like this:

Private Sub betterListBox1_Scroll(Sender As Object, e As BetterListBox.BetterListBoxScrollArgs)
	Console.WriteLine("Scroll to {0}, tracking={1}", e.Top, e.Tracking)
End Sub

The e.Top property tells you which item is now displayed at the top of the ListBox. e.Tracking is true …

Mitja Bonca 557 Nearly a Posting Maven

Maybe your "Department_Code" is not a varchar type in the dataTable. If its an integer you have to convert the textBox text property to a number (int.Parse, or Convert.Toint32() methods).

Otherwise code looks clean.
Or define parameters a bit differently:

parameters.Add("@field2", SqlDbType.VarChar, 50).Value = txt_user.Text
Mitja Bonca 557 Nearly a Posting Maven

Sorry, never even tried yet. This is know what I do. And besides, it will take you a loooong looong time to create it (flawlessly).

Mitja Bonca 557 Nearly a Posting Maven

Did you set the column to be type of Image in the 1st place?

Mitja Bonca 557 Nearly a Posting Maven

Check for one tutorial here.

Mitja Bonca 557 Nearly a Posting Maven

Make your "str" variable as static.

static string str = ConfigurationManager.ConnectionStrings["Bank"].ConnectionString;
SqlConnection con = new SqlConnection(str);
Mitja Bonca 557 Nearly a Posting Maven

Get the current process and set its priority.

System.Diagnostics.Process.GetCurrentProcess().PriorityClass = System.Diagnostics.ProcessPriorityClass.Low;