Mitja Bonca 557 Nearly a Posting Maven

I know it can be creates like:

TextBox[] tbsArray = new TextBox[2];
tbsArray[0] = textBox1;
tbsArray[1] = textBox2;

//or:
TextBox[] tbsArray = new TextBox[] { textBox1, textBox2 };

//or in a loop:
foreach(TextBox tb in new TextBox[] { textBox1, textBox2 })
{
     //...
}

If there is any other way you would like to have it, let us know.
bye

Mitja Bonca 557 Nearly a Posting Maven

DO:

//on main form:
void OpenClient()
{
    Client c = new Client(this);
    c.DoWork();
}

public void AddText(string text)
{
    this.richTextBox1.AppendText(text+Environment.NewLine);
}

//on client class:
class Client
{
    MainForm mf;
    public Client(MainForm _mf)
    {
        this.mf = _mf;
    }

    public DoWork()
    {
        string text = "";
        //do some work ... and add value to text field;
        //and pass to rtb on main form:
        mf.AddText(text);
    }
}
Mitja Bonca 557 Nearly a Posting Maven

Create a DataTable, do the SELECT statement of that number (column name) from database, and do the filtering, if the number already exists in dataTable. I would suggest using Linq - its simple and fast.

It should be like:

            int textBoxNumber = int.Parse(textBox1.Text);
            DataTable table = new DataTable("Numbers");
            using (SqlConnection conn = new SqlConnection("connString"))
            {
                using (SqlDataAdapter da = new SqlDataAdapter(@"SELECT ShopID FROM ShopType", conn))
                    da.Fill(table);
            }
            if (table.Rows.Count > 0)
            {
                IEnumerable<DataRow> query = table.AsEnumerable().Where(w => (int)w["ShopID"].ToString() == textBoxNumber);
                if (query.Count() == 0)
                {
                    //no number yet
                }
                else
                {
                    //number already exists!
                }
            }
            else
            {
                //show message there is no number in db yet
            }

IMPORTANT: my code assumes your ID is a number (integer). If your field in dataBase is an integer there will be no problem, but if its a varchar (string), then change this code to:

.Where(w => (string)w["ShopID"] == textBox1.Text); //must be a string

Hope it helps,
bye

Mitja Bonca 557 Nearly a Posting Maven

great to hear that. It happens.
Just mark the thread as salved - in case if you didnt know that.
bye

Mitja Bonca 557 Nearly a Posting Maven

You should use DataRowView class to retreive item and value from comboBox:

Dim view As DataRowView = comboBox1.SelectedItem
Dim value As Object = view("ColumnNameForValueMember")
Dim item As Object = view("ColumnNameForDisplayMember")
textBox1.Text = item.ToString()

Put this code into comboBox SelectedIndexChanged event.

Mitja Bonca 557 Nearly a Posting Maven

Add "ToString()" method on the end:

comboBox1.SelectedItem.ToString();

To add: SelectedItem for it self is an object type, but I need to have a string.
You could even Convert to string like:

Convert.ToString(comboBox1.SelectedItem);
Mitja Bonca 557 Nearly a Posting Maven

Remove parentheses from sql query this ( and this ).

Mitja Bonca 557 Nearly a Posting Maven

WHERE Clause is the condition of what the inquiry will be based on.
If you do:
"SELECT * FROM MyTable" - it will return all data from database table (data are meant all rows, since we use * simbol)
If you do:
"SELECT * FROM MyTable WHERE Name = "John"; - it will return ONLY rows where in the Name column is John (same as your example).

This means the whole name "John" not only "Jon", or "J".

Maybe you entered only "J" or "Joh" and thats why you didnt get any results.
Thats why sql querying supporty partial values (or starting from beginning, or in form somewhere in the middle, or to the end).
Thats why we must use LIKE keyword and % simbol.
If you do:
... WHERE Name = 'J%' - will return all rows that STARTS with J
... WHERE Name = '&n' - will return all rows that ENDS with n
... WHERE NAme = '&hn&' - will return all rows that CONTAINS hn in some where in the middle!

I hope I was clear enough about using LIKE keyword in sql queries.
So I your case I assume you wanna get all rows that starts with some name, so you do:

 "SELECT * From DVD where Name LIKE ='" + txtName.Text + "%'";
Mitja Bonca 557 Nearly a Posting Maven

Ups, sorry, you are right. I copied the previous code, and I guess forgot to duble check it.
My intentions were good....

Mitja Bonca 557 Nearly a Posting Maven

What do you mean "Prompt the form name"?
And btw instead of returing string, rather return a boolean values - true of false.

Mitja Bonca 557 Nearly a Posting Maven

Use DataReader class and Add items to comboBox:

Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;data source=C:MyFolder\MyProject\myAccessDatabase.accdb"
Dim conn As New OleDbConnection(connString)
Dim sql As String = "SELECT ColumnName FROM Clientes"
Dim cmd As New OleDbCommand(sql, conn)
conn.Open()
Dim reader As OleDbDataReader = cmd.ExecuteReader()
While reader.Read()
    comboBox1.Items.Add(reader(0).ToString())
End While
reader.Close()
conn.Close()
cmd.Close()
Mitja Bonca 557 Nearly a Posting Maven

I would like you to continue using Linq, which is really some piece of work from MS.

To get 1st 50 words:

string text = "you long string";
var result_1st50 = text.Split(' ').Select(s=>s.Lenght).Take(50).ToList();

To get next 50 (and skip 1st 50):

var result_1st50 = text.Split(' ').Select(s=>s.Lenght).Skip(50).Take(50).ToList();

As you can see, Skip will skip the number of words, while Take will get the number of words. For example if you wanna get words from 350 to 400, you only change:
//.Skip(350).Take(50).ToList();

ToList() is the annonimus method, that already create a new list of strings, so no need of any further loop.

Mitja Bonca 557 Nearly a Posting Maven

The simpliest way would be to spit the string by white spaces into string array, and count the words (by Length property):

string text = "you long string";
string[] splitted = text.Split(' ');
int wordsCount = splitted.Length;

Or even better (shorter), by using Linq:

int a = text.Split(' ').Select(s => s.Length).Count();
coder389 commented: Now, how will I display the first 50 words, then next 50 words and so on? +0
Mitja Bonca 557 Nearly a Posting Maven

Do it like:

    System.IO.DirectoryInfo downloadedMessageInfo = new    DirectoryInfo(GetMessageDownloadFolderPath());

foreach (FileInfo file in downloadedMessageInfo.GetFiles())
{
    file.Delete(); 
}
foreach (DirectoryInfo dir in downloadedMessageInfo.GetDirectories())
{
    dir.Delete(true); 
}

or:

public void DeletingFilesAndFolders(DirectoryInfo directory)
{
    foreach(System.IO.FileInfo file in directory.GetFiles()) file.Delete();
    foreach(System.IO.DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true);
}
Mitja Bonca 557 Nearly a Posting Maven

I dont get your point. What would you like to do exactly? Tell us the pattern why not adding a Beef as well?

Mitja Bonca 557 Nearly a Posting Maven

sure, loop through the rows, and check the columns you have a condition, and set ReadOnly to true:

 For Each row As DataGridViewRow In dgv.Rows
    If row("ConditionColumnName").Value.ToString() = "your condition" Then
        row.[ReadOnly] = True
        'you can even color the row differently
        'like:
        row.DefaultCellStyle.BackColor = Color.Red
    Else
        row.[ReadOnly] = False
            'normal color
        row.DefaultCellStyle.BackColor = Color.White
    End If
Next
Mitja Bonca 557 Nearly a Posting Maven

In this case, we have to re-do your code completely. Usin some Linq and an additional method. I did think of something like this:

        private void YourMethod()
        {
            double media = 1.8815;
            List<double> lista = new List<double>();
            lista.Add(2.201);
            //and other values...

            List<double> aux = new List<double>();
            for (int i = 0; i < lista.Count; i++)
            {
               if(CheckNext5(media, lista.Skip(i).Take(5).ToList()))
               {
                   for (int j = 0; j < 5; j++)
                       aux.Add(lista[i + j]); 
                   i = i + 4;
               }
            }
        }

        private bool CheckNext5(double media, List<double> list)
        {
            bool bFlag = true;
            foreach (double item in list)
            {
                if (item < media) 
                {
                    bFlag = false;
                    break;
                }
            }
            return bFlag;
        }

There is a method, that checked next 5 values if they are higher then the media variable, is so, they are added to the new list, else, loops goes on to get next values.
ps: vote and add a comment :)

Hope you like it :)

Mitja Bonca 557 Nearly a Posting Maven

You means to add all numbers (of 5 in a row) if higher then the media into new list?

Mitja Bonca 557 Nearly a Posting Maven

If so, you can do it like:

List<double> aux = new List<double>();
int counter = 0;
for (int i = 0; i < lista.Count; i++) 
{
    if(counter == 5)
        break;
    if(lista[i] > media && counter <= 5)
    {
        aux.Add(list[i]);
        counter++;
    }   
    else
    {
        counter = 0;
        aux.Clear();
    }
}

//show values...
chromatinpt commented: 1 +1
Mitja Bonca 557 Nearly a Posting Maven

It clears because cooner or later your code goes to else block, and clears the list.

But I actually dont get it which value would you like to put into aux list from lista. Can you clarify it a bit better?

Do you mean that tin the for loop you check the current value, and if this and next 5 values are higher then the media value, you put all these 5 values into aux list?
And you continue loopint to the end of the items in lista?

Mitja Bonca 557 Nearly a Posting Maven

1st of all, if you use radionButton, there is always one selected (its not the same as checkBoxes, where you can deselect all). Ok, its possible to deselect all radionButtons in a group as well, but this is not the purpose then in using radionButtons.

About showing the button control, when there is some text inside a textBox, you can use a Length property to check how long is the actual text, and show/hide button based on that - inisde the TextChanged event (just subscribe to in, on double clicking on it in winform designer:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    if(textBox1.Text.Length == 0) //checking if there is any text inside textBox - if there is at least 1 character, buttoon will show up
    {
        button1.Visible = false;
    }
    else
    {
        button1.Visible = true;
    }
}
Mitja Bonca 557 Nearly a Posting Maven

I assume you are trying to create a code for checking the password strenght. Here is some of my code I used to have for it:

Private Enum PasswordScore
    Blank = 0
    VeryWeak = 1
    Weak = 2
    Medium = 3
    Strong = 4
    VeryStrong = 5
End Enum

Private Shared Function CheckingPasswordStrength(password As String) As PasswordScore
    Dim score As Integer = 1
    If password.Length < 1 Then
        Return PasswordScore.Blank
    End If
    If password.Length < 4 Then
        Return PasswordScore.VeryWeak
    End If

    If password.Length >= 8 Then
        score += 1
    End If
    If password.Length >= 12 Then
        score += 1
    End If
    If Regex.IsMatch(password, "[0-9]+(\.[0-9][0-9]?)?", RegexOptions.ECMAScript) Then
        'number only //"^\d+$" if you need to match more than one digit.
        score += 1
    End If
    If Regex.IsMatch(password, "^(?=.*[a-z])(?=.*[A-Z]).+$", RegexOptions.ECMAScript) Then
        'both, lower and upper case
        score += 1
    End If
    If Regex.IsMatch(password, "[!,@,#,$,%,^,&,*,?,_,~,-,L,(,)]", RegexOptions.ECMAScript) Then
        '^[A-Z]+$
        score += 1
    End If
    Return CType(score, PasswordScore)
End Function
Mitja Bonca 557 Nearly a Posting Maven

Are these textBoxes on same form?
I would suggest you to create an array of textBoxes (in order, like you will populate them), and then just loop through them and fill text into each of them.
Example:

TextBox[] tbs;
public Form1()
{
    tbs = new TextBox[]{textBox1, textBox2, textBox3 }; //put all in here
}

public PopulateTextBoxes(string[] data)
{
       for(int i = 0; i < tbs.Lenght; i++)
       {
           tbs[i].Text = data[i];
       }
}

Call the method PopulateTextBoxes when you have all data gathered. I used string array, but you can have some other parameter, like a custom class, or what ever.

If there is so many textboxes, and this might consume some time to populate them all, you can create a new thread, and populate them there, but you will have to use delegates to do it so.

Mitja Bonca 557 Nearly a Posting Maven

Show us your Designer code of the form (whole code).
Its hard to tell what can be wrong, but for sure there is some "additional" code that changes position of controls.

Mitja Bonca 557 Nearly a Posting Maven

It sulely cant work this way, your class reference is not accessable. You created and instantiated new class refercne in Form1 constructor. You must define it on a class level, so it can be accessed in your RedCheckBox_CheckedChanged event, like:

Events redEvent; //define class on a class level!
public Form1()
{
    InitializeComponent();
    redEvent = new Events();
}

private void RedCheckBox_CheckedChanged(object sender, EventArgs e)
{
    redEvent.RedCheckBoxEvent();
}

Hope it helps,
bye

Mitja Bonca 557 Nearly a Posting Maven

Yes and your exact question would be?
Show us some example code, with the calculations, I mean.

Mitja Bonca 557 Nearly a Posting Maven

Whole code would be:

string connectionString = "Data source=localhost;Database=locations;user id=root;password=ietmdb;";
DataTable tables = new DataTable("Tables");
using (SqlConnection connection = new SqlConnection(connectionString))
{
    using(SqlCommand command = connection.CreateCommand())
    {
        command.CommandText = "select table_name as Name from INFORMATION_SCHEMA.Tables where TABLE_TYPE = 'BASE TABLE'";
        connection.Open();
        tables.Load(command.ExecuteReader(CommandBehavior.CloseConnection));
    }    
}

foreach(DataRow row in table.Rows)
{
    DropDownList1.Items.Add(row[0].ToString());
}
Mitja Bonca 557 Nearly a Posting Maven

try using this select query statement:

"select table_name as Name from INFORMATION_SCHEMA.Tables where TABLE_TYPE = 'BASE TABLE'";
Mitja Bonca 557 Nearly a Posting Maven

Variable (in your case a generic list) declared as public static is one solution to use it all over the project.
But if has its own weaknesses, like that it stays in memory for as long as your project is alive. And if the variable becomes huge, it can eat a lot of memory.
If you want to free the memory you should set the field to null so that the object the field has been pointing to becomes eligible for GC.
This only points out something: try to avoid static variables.

-------
What I would do to hold same referecne through all the classes of a project, is to pass the class reference to all the other classes, this way, you can access to non-static public field (or property).
Example:

class ClassForVarialbe
{
     public List<string> stageManagementList;

     public ClassForVariable()
     {
         stageManagementList = new List<string>();
     }

     //...
     //you can even create a common method to do or check something     

}


class Class1
{

     void StartingMethod()
     {
          //here we`ll instantiate a new variable (generic list):
          ClassForVariable cfv = new ClassForVariable();
          //to access to the public variable and ADD into it, you can use the class referecne:
          cfv.stageManagementList.Add("one");

          //now open other class (and pass the referecne or a class where out variable is);
          Class2 c2 = new Class2(cfv); //pass a class referecne
          c2.AddToList(); //examle from class2 how to add into same list

          //now open class3 and print data from list out:
          Class3 c3 = new Class3(); 
          c3.ReadFromList(cfv); //pass …
Mitja Bonca 557 Nearly a Posting Maven
Mitja Bonca 557 Nearly a Posting Maven

I did the whole code for you, since I see its pointeless to do long explanations what to do.
Here it is (btw, code work you know):

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

Namespace Apr11_1
    Public Partial Class Form1
        Inherits Form
        Private comboBox2 As DataGridViewComboBoxColumn
        Public Sub New()
            InitializeComponent()

            'creating 2 comboBox columns:
            Dim comboBox1 As DataGridViewComboBoxColumn = CreatingComboBox("column1", "Category")
            comboBox2 = CreatingComboBox("column2", "Item name")
            dataGridView1.Columns.Insert(0, comboBox1)
            dataGridView1.Columns.Insert(1, comboBox2)

            'and creating other columns (textboxes):
            'you wll add more (quantity, rate,...)
            dataGridView1.Columns.Add("column3", "Column 3")

            'bind data to 1st combo:
            Dim table As DataTable = GetData_ForComboBox1()
            comboBox1.DataSource = table.DefaultView
            comboBox1.DisplayMember = "Column1"
                'comboBox1.ValueMember = "CategoryID";
            comboBox1.DataPropertyName = "Column1"
        End Sub

        Private Function CreatingComboBox(name As String, headerText As String) As DataGridViewComboBoxColumn
            Dim cmbcolumn As New DataGridViewComboBoxColumn()
            If True Then
                cmbcolumn.Name = name
                cmbcolumn.HeaderText = headerText
                If name = "column1" Then
                    'creating event for comboBox1:
                    dataGridView1.EditingControlShowing += New DataGridViewEditingControlShowingEventHandler(AddressOf dataGridView1_EditingControlShowing)
                End If
            End If
            Return cmbcolumn
        End Function

        Private Sub dataGridView1_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs)
            Dim combo As ComboBox = TryCast(e.Control, ComboBox)
            If combo IsNot Nothing Then
                ' Remove an existing event-handler, if present, to avoid 
                ' adding multiple handlers when the editing control is reused.
                RemoveHandler combo.SelectedIndexChanged, New EventHandler(AddressOf ComboBox_SelectedIndexChanged)
                ' Add the event handler. 
                AddHandler combo.SelectedIndexChanged, New EventHandler(AddressOf ComboBox_SelectedIndexChanged)
            End If
        End Sub

        Private Sub ComboBox_SelectedIndexChanged(sender As Object, e As EventArgs)
            Dim cb As ComboBox = TryCast(sender, ComboBox)

            'get the data from bind cell of comboBox:
            Dim view As DataRowView …
Mitja Bonca 557 Nearly a Posting Maven
No. We will discuss here about the issue.

---
So tell me, how you populate comboBox1? From database? Are the items databound to some datasource like datatable?
How do you intend to get data for populating comboBox2? Bind them to the comboBox2?

Tell us more... we would be more then glad to help you out...

Mitja Bonca 557 Nearly a Posting Maven

RichBoxControl defenatelly. It can take text (every type of it - riched too, thats why the name of the control) and even images.

Mitja Bonca 557 Nearly a Posting Maven

create new select query and use a WHERE clasue as an item from 1st drop down list (catgory). Then fill datatable, and bind it to 2nd drop down list.

Mitja Bonca 557 Nearly a Posting Maven
prerit commented: Thank you for your help.Your link solved my prob +0
Mitja Bonca 557 Nearly a Posting Maven

In sql SELECT statement use ORDERBY columnName

    "SELECT DISTINCT column_name(s) FROM table_name ORDERBY columnName"
Mitja Bonca 557 Nearly a Posting Maven

Exmaple:

    "SELECT DISTINCT column_name(s) FROM table_name"
Mitja Bonca 557 Nearly a Posting Maven

Use DISTINCT keyword inside you sql query statement (since you said these data come from database).

Mitja Bonca 557 Nearly a Posting Maven

I would like to know how you file looks like (phisiclly). Then tell us what to add, change, or what ever...

Mitja Bonca 557 Nearly a Posting Maven

Put a pictureBox on the form, and put gif animation inside of it.

Mitja Bonca 557 Nearly a Posting Maven

Change the password inside the connection string (as Jx said already). And where is username? Usually there are both, username and password in the connection string.

Mitja Bonca 557 Nearly a Posting Maven

try it this way:

 string date1 = "1/2/2001";
 DateTime date = Convert.ToDateTime(date1);
 //this is what you have to do:
 string date2 = date.ToString("MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);

My 1st two lines of code are only example to get an actual date (you already have a date from database).

Mitja Bonca 557 Nearly a Posting Maven

Sorry, I forgot o enumerate my "couner" variable. So it moves to a new row every 2nd itteration:

DataTable table2 = new DataTable();
table2.Columns.Add("Column_name", typeof(string));
table2.Columns.Add("Row_name", typeof(string));

DataRow row;
int counter = 0;
for(int i = 0; i < tableOriginal.Columns.Count; i++) //loop through the columns of original table
{

    for(int j = 0; j < tableOriginal.Rows.Count; j++)
    {        
        if(j == 0)
        {
            table2.Rows.Add();
            table2.Rows[counter][0] = tableOriginal.Rows[j][i];
        }
        else if(j == 1)
            table2.Rows[counter++][1] = tableOriginal.Rows[j][i]; //here I do +1, so it will write to the right row
    }

}

Mitja Bonca 557 Nearly a Posting Maven

Try this:

DataTable table2 = new DataTable();
table2.Columns.Add("Column_name", typeof(string));
table2.Columns.Add("Row_name", typeof(string));

DataRow row;
int counter = 0;
for(int i = 0; i < tableOriginal.Columns.Count; i++) //loop through the columns of original table
{

    for(int j = 0; j < tableOriginal.Rows.Count; j++)
    {        
        if(j == 0)
        {
            table2.Rows.Add();
            table2.Rows[counter][0] = tableOriginal.Rows[j][i];
        }
        else if(j == 1)
            table2.Rows[counter][1] = tableOriginal.Rows[j][i];
    }
}   

Maybe there will some any error, I did the code by heart. Let me know if its working.
bye

Mitja Bonca 557 Nearly a Posting Maven

What will you have in a listbox? Files?
If so you can do a loop through all the item in listbox and compare each of them to your file name.
Can you do it?

Mitja Bonca 557 Nearly a Posting Maven

You didnt tell us a thing concering your issue. You only pasted some code and some error.
Please, tell us more about it.
Where this error occurs, and so on?

You have plenty of variables inside this code, that we dont even know what they really are (ie: transaction, Variables,...)
Please more info needed if you want to get some decent help from us.

Mitja Bonca 557 Nearly a Posting Maven

And one more thing, your i is always 0, becuase you never increment it (+1 on each step of the loop). And even if you would increment it (by using for loop) MIN will always be zero. And thats because

if (randomNum[i] < min) 

will never be true.
As I said, you have to 1st create an array of all 10 numbers and then find the min and max value.
There are ways of making your code work, but you will have to check on every step of the loop if any of current random number is bigger or smaller of any od the numbers in array. But this just doesnt make any sence.

This would means:

if (randomNum[i] > "of any of the current number is array")
{
   //set max number to randomNum[i];
}
//same for min
Mitja Bonca 557 Nearly a Posting Maven

This is some strange code to find min and max value of integer array.
Why dont you create an array of n numbers, and then use Linq to find those 2 values:

//an array of numbers:
int[] numbers = { 1, 2, 3, 4, 5 };
//then do:
int min = numbers.Min();
int max = numbers.Max();
Mitja Bonca 557 Nearly a Posting Maven

What type is the column DatePrinted in your database? Is it a real datetime, or its just a varchar? You dont do any parsing.

Mitja Bonca 557 Nearly a Posting Maven
  1. if you would provide date too, it would calculate it correctly.
  2. or try somethig like:

     private void button2_Click(object sender, EventArgs e)
     {
         DateTime t1 = Convert.ToDateTime(textBox1.Text);
         DateTime t2 = Convert.ToDateTime(textBox2.Text);
         if (t2 < t1)
            t2 = t2.AddDays(1);
         TimeSpan ts = t2.Subtract(t1);
         MessageBox.Show(string.Format("The difference is {0}:{1}", ts.Hours, ts.Minutes));
     }
    

Dont forget to add some "protection" to dates, in case if there is an error input, like:

     DateTime t1;
     if(DateTime.TryParse(textBox1.Text, our t1))
     {
         //go on... all ok
     }
     else
         MessageBox.Show("Wrong input time or date...");

Hope it helps,
bye