Reputation: 165
I am trying to update values in a column like the following code block reading from a datatable. Currently, it is only updating the specified column value (string) for the first row but not going through the next rows and updating those. What am I doing wrong? Please advice.
public void UpdateDescription(DataTable dataTable)
{
if (dataTable != null && dataTable.Rows.Count > 0)
{
DataRow dr = dataTable.Rows[0];
string dataDesc = string.Empty;
int rowIndex = 0;
dataDesc = dr["DataDesc"].ToString();
if (rowIndex < dataTable.Rows.Count)
{
dr = dataTable.Rows[rowIndex];
if (!dr.IsNull("DataDesc"))
{
if (dataDesc.Contains("STATE"))
{
dataDesc = dataDesc.Replace("STATE", "").Trim();
}
if (dataDesc.Contains("HELLO ALL"))
{
dataDesc = dataDesc.Replace("HELLO ALL", "").Trim();
}
if (dataDesc.Contains("("))
{
dataDesc = dataDesc.Remove(dataDesc.IndexOf("(")).Trim();
}
}
dr["DataDesc"] = dataDesc;
}
rowIndex++;
}
}
Upvotes: 0
Views: 12842
Reputation: 4726
You need to loop the rows in the data table. You are just specifying a row, number 0 in this line:
DataRow dr = journalTable.Rows[0];
The following code should work for you:
public void UpdateDescription(DataTable dataTable)
{
if (dataTable != null && dataTable.Rows.Count > 0)
{
foreach (DataRow dr in dataTable.Rows)
{
String dataDesc = dr["DataDesc"].ToString();
if (!dr.IsNull("DataDesc"))
{
if (dataDesc.Contains("STATE"))
{
dataDesc = dataDesc.Replace("STATE", "").Trim();
}
if (dataDesc.Contains("HELLO ALL"))
{
dataDesc = dataDesc.Replace("HELLO ALL", "").Trim();
}
if (dataDesc.Contains("("))
{
dataDesc = dataDesc.Remove(dataDesc.IndexOf("(")).Trim();
}
}
dr["DataDesc"] = dataDesc;
}
}
}
Upvotes: 1
Reputation:
It looks like you are only reading the string
value dataDesc
once.
Perhaps you mean to read it for each row. I am not sure.
If so, try this version:
public void UpdateDescription(DataTable dataTable) {
if ((dataTable != null) && (0 < dataTable.Rows.Count)) {
int rowIndex = 0;
//DataRow dr = journalTable.Rows[0]; // What was this line for? "journalTable" is not defined here.
if (rowIndex < dataTable.Rows.Count) {
DataRow dr = dataTable.Rows[rowIndex];
if (!dr.IsNull("DataDesc")) {
string dataDesc = dr["DataDesc"].ToString();
if (dataDesc.Contains("STATE")) {
dataDesc = dataDesc.Replace("STATE", "").Trim();
}
if (dataDesc.Contains("HELLO ALL")) {
dataDesc = dataDesc.Replace("HELLO ALL", "").Trim();
}
if (dataDesc.Contains("(")) {
dataDesc = dataDesc.Remove(dataDesc.IndexOf("(")).Trim();
}
dr["DataDesc"] = dataDesc;
}
}
rowIndex++;
}
}
Upvotes: 2
Reputation: 19765
You have no loop. Try this:
while (rowIndex < dataTable.Rows.Count)
{
dr = dataTable.Rows[rowIndex];
...
dr["DataDesc"] = dataDesc;
rowIndex++;
}
or if you prefer...
for (int rowIndex = 0; rowIndex < dataTable.Rows.Count; ++rowIndex)
...
Also whatch out - if "dataDesc" is null for one row it will get the previous row's value in your logic!
Upvotes: 1