简体   繁体   English

修改和验证数据表 c# 中的字段

[英]Modifying and validating fields in a DataTable c#

I have the following datatable:我有以下数据表:

来自 myDDBB 的数据

the field "court_case" has a different format and is not compact, the expected format would be: XXXX/XX ("4 digits" / "2 digits" )字段“court_case”具有不同的格式并且不紧凑,预期格式为:XXXX/XX(“4 位数字”/“2 位数字”)

For example:例如:

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

Ie 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.通过此验证,我只检查 court_case 的内容是否为整数类型。 but I do not check a validation of the format like: " XXXX/XX ".但我不检查格式的验证,如:“ 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??有什么帮助吗??

Well technically you want to split the string to 2 parts, handle each separately and add it together with added zeroes.好吧,从技术上讲,您希望将字符串拆分为 2 部分,分别处理每个部分并将其与添加的零一起添加。 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);
}

You can use string.PadLeft method to append leading zeros 0 (or other char) to some string:您可以使用string.PadLeft方法将前导零0 (或其他字符)附加到某个字符串:

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:它会给你这样的结果:

在此处输入图片说明

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.如果您只想检查输入 (CourtCase) 是否具有预期格式 (xxxx/xx),那么您可以通过这种方式更改Validar_Cc

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'.此示例假设您考虑正确的输入,例如“0000/00”或“1234/00”或“0000/88”。 If this is not the case then one more checks is needed.如果不是这种情况,则需要再进行一项检查。 Just add these lines after the TryParse block只需在 TryParse 块之后添加这些行

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

And you could call the Validar_CC inside the loop over the grid rows您可以在网格行上的循环内调用 Validar_CC

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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM