none
C# Exceptions and number in forloop RRS feed

  • Question

  • I show two Exceptions
    The first one is when I do not put a number in k

    The second Exceptions is if K is more then egg I get an exception in the Parameters.AddWithValue

    I like to add a MessageBox.Show to have it add the correct number to k


    also how would you add to the output numbers for each row.

    1     EG216455
    2     nEG216456
    3     nEG216457
    4     nEG216458
    6     nEG216459
    7     nEG216460

    private void button1_Click(object sender, EventArgs e)
            {
                string egg = textBox1.Text; //egg will show "EG216455\r\nEG216456\r\nEG216457\r\nEG216458\r\nEG216459\r\nEG216460"	
                int k = Convert.ToInt32(textBox2.Text);  // did not put anything in k --- System.FormatException: 'Input string was not in a correct format.'
                string[] stringSeparators = new string[];//EG216455\r\nEG216456\r\nEG216457\r\nEG216458\r\nEG216459\r\nEG216460
                string[] s = egg.Split(stringSeparators, StringSplitOptions.None);
    
    
                DataTable dtSerial = new DataTable();
                DataTable table = new DataTable();
    
                for (int i = 0; i < k; i++)
                {
                                       //ConfigurationManager.ConnectionStrings["pie"].ConnectionString;
                    string connString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=Database.mdf;Integrated Security=True";
    
                    using (SqlConnection con = new SqlConnection(connString))
                    {
                        using (var cmd = new SqlCommand("SELECT ItemCode,ItemName FROM Table1  where ItemCode = @egg", con))//select eggcounter From [Product].[Counter01unit]  where eggcounter = @egg
                        {
                            cmd.Parameters.AddWithValue("@egg", s[i]); //Exception Unhandled -- System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'
                            con.Open();
                            SqlDataReader reader = cmd.ExecuteReader();
                            dtSerial.Load(reader);
                            table = dtSerial.Clone();
                            foreach (DataRow dr in dtSerial.Rows)
                            {
    
                                table.Rows.Add(dr.ItemArray);
                            }
                        }
                        con.Close();
                    }
                }
    
    
                dataGridView1.DataSource = dtSerial;
            }

    Saturday, February 16, 2019 7:48 PM

All replies

  • I show two Exceptions
    The first one is when I do not put a number in k

    I like to add a MessageBox.Show to have it add the correct number to k

    private void button1_Click(object sender, EventArgs e)
            {
                string egg = textBox1.Text; //egg will show "EG216455\r\nEG216456\r\nEG216457\r\nEG216458\r\nEG216459\r\nEG216460"	
                int k = Convert.ToInt32(textBox2.Text);  // did not put anything in k --- System.FormatException: 'Input string was not in a correct format.'

    Let's start with this:

    int k = Convert.ToInt32(textBox2.Text);

    You haven't said what is in textBox2.Text that results in the exception.

    Since you're trying to convert to an Int32 whatever string is in textBox2.Text
    it must represent a valid value for an Int32. If it isn't - including an empty
    string - then you will get an exception.

    If you want to test for and handle this situation instead of having an exception
    occur, then use TryParse instead of Convert or Parse.

    int k;
    bool res = Int32.TryParse(textBox2.Text, out k);
    if(!res) // TryParse returned false ...
    {
        // pop up a message box requesting a valid number, etc.
        // ...
        return; // leave button click event handler
    }

    - Wayne


    • Edited by WayneAKing Sunday, February 17, 2019 6:18 PM
    Saturday, February 16, 2019 10:21 PM

  •             string[] stringSeparators = new string[];//EG216455\r\nEG216456\r\nEG216457\r\nEG216458\r\nEG216459\r\nEG216460
    

    What is that line supposed to do? That wouldn't even compile without errors,
    so I don't know how you could be testing the code and getting an exception.

    - Wayne

    Sunday, February 17, 2019 12:02 AM
  • Hi   wonconfucius,

    >>also how would you add to the output numbers for each row.

    I will try the following method.

       string egg = "EG216455\r\nEG216456\r\nEG216457\r\nEG216458\r\nEG216459\r\nEG216460";
                try
                {
                    int k = Convert.ToInt32("8");
                    // did not put anything in k --- System.FormatException: 'Input string was not in a correct format.'
                    string[] stringSeparators = new string[] { "\r\n" };//EG216455\r\nEG216456\r\nEG216457\r\nEG216458\r\nEG216459\r\nEG216460
                    string[] s = egg.Split(stringSeparators, StringSplitOptions.None);
    
                    DataTable dtSerial = new DataTable();
                    DataTable table = new DataTable();
    
                    for (int i = 0; i < k; i++)
                    {
                        //ConfigurationManager.ConnectionStrings["pie"].ConnectionString;
                        string connString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=Database.mdf;Integrated Security=True";
                        MessageBox.Show(s[i]);
                        if(i+1>=s.Length)
                        {
                            return;
                        }
                        //using (SqlConnection con = new SqlConnection(connString))
                        //{
                        //    using (var cmd = new SqlCommand("SELECT ItemCode,ItemName FROM Table1  where ItemCode = @egg", con))//select eggcounter From [Product].[Counter01unit]  where eggcounter = @egg
                        //    {
                        //        cmd.Parameters.AddWithValue("@egg", s[i]); //Exception Unhandled -- System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'
                        //        con.Open();
                        //        SqlDataReader reader = cmd.ExecuteReader();
                        //        dtSerial.Load(reader);
                        //        table = dtSerial.Clone();
                        //        foreach (DataRow dr in dtSerial.Rows)
                        //        {
    
                        //            table.Rows.Add(dr.ItemArray);
                        //        }
                        //    }
                        //    con.Close();
                        //}
                    }
                }
    
                catch
                {
                    return;
                }
    
                // dataGridView1.DataSource = dtSerial;
    

    Best Regards,

    Yong Lu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, February 18, 2019 6:41 AM
    Moderator