C# – Modifying or replacing column values reading from the DataTable

cdatatable

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++;

    }
}

Best Answer

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++;

  }
}
Related Topic