Home > Software design >  Modifying and validating fields in a DataTable c#
Modifying and validating fields in a DataTable c#

Time:10-13

I have the following datatable:

Data from myDDBB

the field "court_case" has a different format and is not compact, the expected format would be: XXXX/XX ("4 digits" / "2 digits" )

For example:

12/13 -> 0012/13
2/1   -> 0002/10
/18   -> 0000/18
45/   -> 0045/00

I.e. complete with leading zeros if it is the case for the first part before the "/" and with leading zeros if it is the case after the "/".

private void bt_showDataTable_Click(object sender, EventArgs e)
{
    Cursor.Current = Cursors.WaitCursor;
    dataGridView2.DataSource = getDataTable();
}
    
public DataTable getDataTable()
{   
    DataTable dtTabla = new DataTable();
    try
    {
        MySqlConnection connection = new MySqlConnection();
        connection.ConnectionString = configuracion.conexion;
        connection.Open();
    
        string query = "SELECT * FROM CC_T.CONSIGNATION WHERE ACCOUNT IN ('error');"; //query from the image above
    
        MySqlCommand mycmd = new MySqlCommand(query, connection);
        mycmd.Connection = connection;
    
        MySqlDataReader reader = mycmd.ExecuteReader();
    
        dtTabla.Load(reader);

    }
    catch (MySqlException ex)
    {
        MessageBox.Show(ex.Message);
    }
    
    return dtTabla;
}

// METHOD TO VALIDATE COURT CASE
public static bool Validar_Cc(string CourtCase)
{
    int i = 0;
    string part1 = "";
    string part2 = "";
    
    bool result1 = false;
    bool result2 = false;
    
    if (CourtCase.Contains("/"))
    {
        part1 = CourtCase.Substring(0, CourtCase.IndexOf('/'));
    
        part2 = CourtCase.Substring(CourtCase.IndexOf('/')   1, CourtCase.Length - CourtCase.IndexOf('/') - 1);
    
        result1 = int.TryParse(part1, out i);
        result2 = int.TryParse(part2, out i);
    }
    
    if (!result1 || !result2)
    {
        return false;
    }
    else return true;
}

with this validation I only check that what comes for court_case is of type integer. but I do not check a validation of the format like: "XXXX/XX".

here I have to pass the method to validate:

private void btnCORRECT_ERROR_COURTCASE_Click(object sender, EventArgs e)
{
    string reply = "";
    foreach(DataColumn column in dataGridView2.Rows)
    {
                //
    }
}

I know this is wrong but I don't know how to continue. Any help??

CodePudding user response:

Well technically you want to split the string to 2 parts, handle each separately and add it together with added zeroes. Like:

var inputArray = new string[4] { "12/13", "2/1", "/18", "45/" };
var results = new List<string>();

foreach (var str in inputArray)
{
    var parts = str.Split(new string[] { "/" }, StringSplitOptions.None);

    var result = parts[0].PadLeft(4, '0')   "/"   parts[1].PadLeft(2, '0');
    results.Add(result);
}

CodePudding user response:

You can use string.PadLeft method to append leading zeros 0 (or other char) to some string:

static string AddLeadingZeros(string s, int amount)
{
    return s.PadLeft(amount, '0');
}

Usage example:

void FixCourtCases()
{
    string[] courtCases = new string[] 
    {
        "6906/2",
        "9163/2",
        "504/",
        "3/",
        "9/4",
        "4311/",
        "0/",
        "/6",
        "193/0",
        "0/2",
    };

    for (int i = 0; i < courtCases.Length; i  )
    {
         // Split left and right numbers by '/'
        string[] courtCase = courtCases[i].Split(new string[] { "/" }, StringSplitOptions.None);

        // Add leading zeros to left and right numbers
        string fixedLeftNumber = AddLeadingZeros(courtCase[0], 4);
        string fixedRightNumber = AddLeadingZeros(courtCase[1], 2)

        // Reassign value with fixed one
        courtCases[i] = fixedLeftNumber   "/"   fixedRightNumber;
    }
}

it will give you that kind of result:

enter image description here

CodePudding user response:

If you just want to check if the input (CourtCase) has the expected format (xxxx/xx) then you could change the Validar_Cc in this way.

public static bool Validar_Cc(string CourtCase)
{
    // First check, the string should be 7 character long, if not then fast exit
    if (CourtCase.Length != 7)
       return false;

    // Second check, try to split at /, if you get back an array with more or
    // less than two elements then fast exit
    string[] parts = CourtCase.Split('/');
    if(parts.Length != 2)
       return false;

    // Now check if the two elements are numbers or not. 
    // Again fast exit in case of error
    if(!Int32.TryParse(parts[0], out int number1))
       return false;
    if(!Int32.TryParse(parts[1], out int number2))
       return false;

    // If you reach this point then the data is correct
    return true;
}

This example assumes that you consider correct inputs like '0000/00' or '1234/00' or '0000/88'. If this is not the case then one more checks is needed. Just add these lines after the TryParse block

if(number1 == 0 || number2 == 0)
    return false;

And you could call the Validar_CC inside the loop over the grid rows

private void btnCORRECT_ERROR_COURTCASE_Click(object sender, EventArgs e)
{
    string reply = "";
    foreach(DataGridRow row in dataGridView2.Rows)
    {
       bool result = Validar_Cc(row.Cells["COURT_CASE"].Value.ToString());
       .... do whatever you need to do with false/true results
    }
}
  •  Tags:  
  • c#
  • Related