The code below works exactly as it should when it runs against my DataTable the first time. The data table is loaded, it updates all of the column data specified using the string that is specified. Everything is closed (and presumably cleared) properly.
public void AppendKeyColumn(string appendText, params string[] columnNames)
{
string columns = "";
// Create a list of the columns to use, comma separated.
for (int column = 0; column < columnNames.Length; column++)
{
if ((column + 1) == columnNames.Length)
{
columns += columnNames.ElementAt(column);
}
else
{
columns += columnNames.ElementAt(column) + ", ";
}
}
// SQL Statement for querying the file. Change after FROM for proper table name.
string sql = "SELECT " + columns + " FROM " + TableName;
// Using to create a command variable (so it will be properly disposed after block execution).
using (OleDbCommand cmd = new OleDbCommand(sql, Connection))
{
// Open a connection to the data source.
Connection.Open();
// Open the datareader, load the datatable with the data in the reader, and then close the reader.
Data = cmd.ExecuteReader();
Table.Load(Data);
Data.Close();
foreach (string column in columnNames)
{
// Run UPDATE statement to append text to end of column name.
for (int row = 0; row < Table.Rows.Count; row++)
{
string sql2 = "UPDATE " + TableName + " SET " + column + " = @newName WHERE " +
column + " = @oldName";
using (OleDbCommand cmd2 = new OleDbCommand(sql2, Connection))
{
string oldString = Table.Rows[row][0].ToString();
string newString = oldString.Remove(oldString.Length - 1);
newString = newString.Insert(newString.Length, appendText);
cmd2.Parameters.AddWithValue("@newName", newString);
cmd2.Parameters.AddWithValue("@oldName", oldString);
if (!Equals(oldString.Substring(oldString.Length-1, 1), appendText))
{
cmd2.ExecuteNonQuery();
}
}
}
}
Table.Clear();
Connection.Close();
}
}
My issues lies with when I run this code for the second time. If I call it again on the same table, I get the following error (from this line string newString = oldString.Remove(oldString.Length - 1);
). The DataTable should not have any empty strings in the columns that this is being called against. On the first call, the DataTable loads and this works as expected. On the second run, it seems to acknowledge the correct number of rows in the DataTable, however it seems to be physically empty.
InnerException:
System.ArgumentOutOfRangeException: StartIndex cannot be less than zero.
Parameter name: startIndex
at System.String.Remove(Int32 startIndex)
I'm assuming I'm probably overlooking something basic, but could somebody please point my in the right direction?