Array Index out of bounce in C# when string in splited

hello friend this is my code which i am using following code for splitting the string

            string s = dt.Rows[0]["tstrim"].ToString();
            for (int i = 0; i <= s.Length-1; i++)
                {
                var val = s.Split(',')[i];
                    SqlCommand cmd1 = new SqlCommand("select Value,Details from Travelling_Master where Value='" + val + "'", connLive);
                    SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
                    DataTable dt1 = new DataTable();
                    da1.Fill(dt1);
                    if (dt1 != null)
                    {
                        string val1 = dt1.Rows[0]["Value"].ToString();
                        if (val1 == "$1")
                        {
                            v1 = "Check Registerd CallerId.";
                        }
                        else if (val1 == "$7")
                        {
                            v2 = "Selecting Query From Customer.";
                        }
                        else
                        {
                        }
                        label2.Text = v1 + "," + v2;
                    }
                }

At this line error occurred when it come after last string spiting

var val = s.Split(',')[i];

array index is out of bounce this done when i am getting string from database and updating into another table so please help for solved this error

Jon Skeet
people
quotationmark

Yes, currently i can take every value within the length of s - and you're assuming that there are that many elements after splitting.

You should split once, and then iterate over that:

string s = dt.Rows[0]["tstrim"].ToString();
string[] bits = s.Split(',');
foreach (string val in bits)
{
    ...
}

In general you should prefer foreach when you don't need the index within the collection.

Also, it's far more conventional to write:

for (int i = 0; i < s.Length; i++)

than

for (int i = 0; i <= s.Length - 1; i++)

... exclusive upper bounds are very common in computer science, and it's worth getting used to them.

Important note

There's something else very wrong with your code, but not directly related to the exception you're seeing. You're currently building up a SQL string by concatenating a value in the middle of it:

new SqlCommand("select Value,Details from Travelling_Master where Value='" + val + "'", 
               connLive);

Don't do that. Really, really don't do that. Use parameterized SQL instead:

  • It avoids SQL injection attacks
  • It avoids conversion issues (particularly with dates and times)
  • It makes your code clearer (the SQL is just SQL, and the values are values)

people

See more on this question at Stackoverflow