Modifying and validating fields in a DataTable c# - c#

I have the following datatable:
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??

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

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:

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

Related

Picking specific numbers out of text file and assign to variable

Someone here at works needs some calculations done from some numbers within a text file. I know how to do the calculation but I haven't worked with text file before. So I spent the night reading and wrote a little something for the first number I needed but it doesn't work.
So here is an example of the file.
So that first number that comes after FSD: 0.264 I need to read that number and save to a variable. The number will always be different per file. Then I need the first 3.4572 number read to a variable. and the last number of that column as well which you don't see here but for the example it can be the last one shown in the image of 3.3852 read and saved to a variable.
Maybe I'm making this much harder than it needs to be but this is what I was playing around with
public partial class FrmTravelTime : Form
{
string file = "";
public FrmTravelTime()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
file = openFileDialog1.FileName;
}
}
private void button2_Click(object sender, EventArgs e)
{
var sLines = File.ReadAllLines(file)
.Where(s => !s.StartsWith("FSD:"))
.Where(s => !string.IsNullOrWhiteSpace(s))
.Select(s => new
{
SValue = Regex.Match(s, "(?<=S)[\\d.]*").Value,
})
.ToArray();
string Value = "";
for (int i = 0; i < sLines.Length; i++)
{
if (sLines[i].SValue == "")
{
Value = (sLines[i].SValue);
}
}
}
}
EDIT FOR #Ramankingdom
So if you see here all lines have an ending column of 0.00 until we get to
3.0164 7793 1 0 0.159 0.02
So what I'd like to do, is edit what we did to skip everything that has a column with 0.00 in that last column and make the first non 0.00 the info.firstvalue so in this case 3.0164
Now I tried this on my own and used
var data = lines.Where(line => (!line.Contains(Data_Start_Point_Identifier) && !line.Contains(FSD__Line_Identifier) && !line.EndsWith("0.00"))).ToList();
But that breaks info.startvalue and data = dataWithAvgVolts[dataWithAvgVolts.Count - 1].Split(splitter);
So I'd figured I'd check with you.
So I tried this but I keep getting invalid data error on info.startvalue
FileInfo info = new FileInfo();
var lines = File.ReadAllLines(row.Cells["colfilelocation"].Value.ToString());
var fsdLine = lines.FirstOrDefault(line =>
line.Contains(FSD__Line_Identifier));
info.FSD = fsdLine.Substring(fsdLine.IndexOf(FSD_Identifier) + FSD_Identifier.Length, 7);
var dataWithAvgVolts = lines.SkipWhile(line => !line.Contains(Data_Start_Point_Identifier)).ToList();
int index =1;
while(index < dataWithAvgVolts.Count())
{
var data = dataWithAvgVolts[index].Split(splitter);
if(data.Count() >1)
{
if(!Convert.ToDouble(data[data.Count()-1]) == 0)
{
//set start info
break;
}
}
index++;
}
the reverse loop you can run to set the end value
Here is the code
class Program
{
const string FSD_Identifier = "FSD:";
const string FSD__Line_Identifier = "Drilling Data";
const string Data_Start_Point_Identifier = "AVG_VOLTS";
static readonly char[] splitter = {' ','\t'};
static void Main(string[] args)
{
var result = GetFileInfo("c:\\sample.txt");
}
private static MyFileInfo GetFileInfo(string path)
{
MyFileInfo info = new MyFileInfo();
try
{
var lines = File.ReadAllLines(path);
var fsdLine = lines.FirstOrDefault(line => line.Contains(FSD__Line_Identifier));
info.FSD = fsdLine.Substring(fsdLine.IndexOf(FSD_Identifier) + FSD_Identifier.Length, 10); // take lenght you can specify or your own logic
var dataWithAvgVolts = lines.SkipWhile(line => !line.Contains(Data_Start_Point_Identifier)).ToList<string>();
if (dataWithAvgVolts.Count() > 1)
{
var data = dataWithAvgVolts[1].Split(splitter);
info.startvalue = Convert.ToDouble(data[0]);
data = dataWithAvgVolts[dataWithAvgVolts.Count-1].Split(splitter);
info.endvalue = Convert.ToDouble(data[0]);
}
}
catch (Exception ex)
{
//logging here
}
return info;
}
}
public class MyFileInfo
{
public string FSD;
public double startvalue;
public double endvalue;
}

Text file to two string arrays in wpf using streamreader

I'm trying to read a text file to two string arrays. Array1 is to be all the odd lines, array2 all the even lines. I then add all the items of array1 to a combobox and when that is selected, or as it gets typed, outputs array2 to a textbox.
So far, I have tried a few methods from here, but the big issue seems to be creating the arrays. I tried to get help here before, but the answers didn't actually answer my question. They must be arrays, not lists (which I tried and worked well). I am really confused by this whole thing and my attempted code is now rubbish:
private void ReadFile(string filePath, string customerPhone, string customerName)
{
string line = string.Empty;
var fileSR = new StreamReader(filePath);
bool number = true;
while((line = fileSR.ReadLine()) != null)
{
if (number)
{
customerPhone(line);
number = false;
}
else
{
customerName(line);
number = true;
}
}
fileSR.Close();
}
I'm losing confidence in this whole process, but I need to find a way to make it work, then I can learn why it does.
You are almost there, just use the List<string>.
private void ReadFile(string filePath, string customerPhone, string customerName)
{
string line = string.Empty;
using (var fileSR = new StreamReader(filePath))
{
bool number = true;
List<string> customerPhone = new List<string>();
List<string> customerName = new List<string>();
while((line = fileSR.ReadLine()) != null)
{
if (number)
{
customerPhone.Add(line);
number = false;
}
else
{
customerName.Add(line);
number = true;
}
}
fileSR.Close();
}
}
If you are interested only in Arrays, you could simply call customerName.ToArray() to convert it to an array.
Linq Solution
Alternatively you could use Linq and do this.
var bothArrays = File.ReadLines("filepath") // Read All lines
.Select((line,index) => new {line, index+1}) // index each line
.GroupBy(x=> x/2) // Convert into two groups
.SelectMany(x=> x.Select(s=>s.line).ToArray()) // Convert it to array
.ToArray();
You should use collections to return data, say IList<String>:
private static void ReadFile(String filePath,
IList<String> oddLines,
IList<String> evenLines) {
oddLines.Clear();
evenLines.Clear();
int index = 1; //TODO: start with 0 or with 1
foreach (String line in File.ReadLines(filePath)) {
if (index % 2 == 0)
evenLines.Add(line);
else
oddLines.Add(line);
index += 1;
}
}
using
List<String> names = new List<String>();
List<String> phones = new List<String>();
ReadFile(#"C:\MyDate.txt", names, phones);
// If you want array representation
String[] myNames = names.ToArray();
String[] myPhones = phones.ToArray();
// Let's print out names
Console.Write(String.Join(Envrironment.NewLine, names));
Please, notice, that using File.ReadLines usually more convenient than StreamReader which should be wrapped in using:
// foreach (String line in File.ReadLines(filePath)) equals to
using (var fileSR = new StreamReader(filePath)) {
while ((line = fileSR.ReadLine()) != null) {
...
}
}
This worked! I have these class level strings:
string cFileName = "customer.txt";
string[] cName = new string[0];
string[] cPhone = new string[0];
And then this in the Window Loaded event, but could be used in it's own method:
private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
//read file on start
int counter = 0;
string line;
StreamReader custSR = new StreamReader(cFileName);
line = custSR.ReadLine();
while (custSR.Peek() != -1)
{
Array.Resize(ref cPhone, cPhone.Length + 1);
cPhone[cPhone.Length - 1] = line;
counter++;
line = custSR.ReadLine();
Array.Resize(ref cName, cName.Length + 1);
cName[cName.Length - 1] = line;
counter++;
line = custSR.ReadLine();
phoneComboBox.Items.Add(cPhone[cPhone.Length - 1]);
}
custSR.Close();
//focus when program starts
phoneComboBox.Focus();
}

String formatting in C#?

I have some problems to format strings from a List<string>
Here's a picture of the List values:
Now I managed to manipulate some of the values but others not, here's what I used to manipulate:
string prepareStr(string itemToPrepare) {
string first = string.Empty;
string second = string.Empty;
if (itemToPrepare.Contains("\"")) {
first = itemToPrepare.Replace("\"", "");
}
if (first.Contains("-")) {
int beginIndex = first.IndexOf("-");
second = first.Remove(beginIndex, first.Length - beginIndex);
}
return second;
}
Here's a picture of the Result:
I need to get the clear Path without the (-startup , -minimzed , MSRun , double apostrophes).
What am I doing wrong here?
EDIT my updated code:
void getStartUpEntries() {
var startEntries = StartUp.getStartUp();
if (startEntries != null && startEntries.Count != 0) {
for (int i = 0; i < startEntries.Count; i++) {
var splitEntry = startEntries[i].Split(new string[] { "||" }, StringSplitOptions.None);
var str = splitEntry[1];
var match = Regex.Match(str, #"\|\|""(?<path>(?:\""|[^""])*)""");
var finishedPath = match.Groups["path"].ToString();
if (!string.IsNullOrEmpty(finishedPath)) {
if (File.Exists(finishedPath) || Directory.Exists(finishedPath)) {
var _startUpObj = new StartUp(splitEntry[0], finishedPath,
"Aktiviert: ", new Uri("/Images/inWatch.avOK.png", UriKind.RelativeOrAbsolute),
StartUp.getIcon(finishedPath));
_startUpList.Add(_startUpObj);
}
else {
var _startUpObjNo = new StartUp(splitEntry[0], finishedPath,
"Aktiviert: ", new Uri("/Images/inWatch.avOK.png", UriKind.RelativeOrAbsolute),
StartUp.getIcon(string.Empty));
_startUpList.Add(_startUpObjNo);
}
}
var _startUpObjLast = new StartUp(splitEntry[0], splitEntry[1],
"Aktiviert: ", new Uri("/Images/inWatch.avOK.png", UriKind.RelativeOrAbsolute),
StartUp.getIcon(string.Empty));
_startUpList.Add(_startUpObjLast);
}
lstStartUp.ItemsSource = _startUpList.OrderBy(item => item.Name).ToList();
}
You could use a regex to extract the path:
var str = #"0Raptr||""C:\Program Files (x86)\Raptr\raptrstub.exe"" --startup"
var match = Regex.Match(str, #"\|\|""(?<path>(?:\""|[^""])*)""");
Console.WriteLine(match.Groups["path"]);
This will match any (even empty) text (either an escaped quote, or any character which is not a quote) between two quote characters preceeded by two pipe characters.
Similarly, you could simply split on the double quotes as I see that's a repeating occurrence in your examples and take the second item in the split array:
var path = new Regex("\"").Split(s)[1];
This is and update to your logic without using any Regex:
private string prepareStr(string itemToPrepare)
{
string result = null;
string startString = #"\""";
string endString = #"\""";
int startPoint = itemToPrepare.IndexOf(startString);
if (startPoint >= 0)
{
startPoint = startPoint + startString.Length;
int EndPoint = itemToPrepare.IndexOf(endString, startPoint);
if (EndPoint >= 0)
{
result = itemToPrepare.Substring(startPoint, EndPoint - startPoint);
}
}
return result;
}

How can I call this method for retrieved data in C#?

I'm working on a program that allows you to select a customer ID from a dropdown box. Once the customer ID is selected, the customer's information is pulled from a CSV file and displayed in textboxes.
The phone number information is unformatted, but I want it to be displayed formatted (ex. (800)674-3452). I have written a method for this, but I'm not sure how to call it. Can you please help?
-Sorry if this is a dumb question. I'm still learning.
private void idBox_SelectedIndexChanged(object sender, EventArgs e)
{
try // catch errors
{
string selectedCustomer; // variable to hold chosen customer ID
selectedCustomer = idBox.Text; // retrieve the customer number selected
chosenIndex = 0;
bool found = false; // variable if customer ID was found
while (!found && chosenIndex < allData.Length) // loop through the 2D array
{
if (allData[chosenIndex, 0] == selectedCustomer) // make sure it's the right customer
{
found = true; // Yes (true) found the correct customer
}
chosenIndex++; // add one row
}
chosenIndex -= 1; // subtract one because add 1 before exiting while
/* 0 = customer ID
* 1 = name
* 2 = address
* 3 = city
* 4 = state
* 5 = zip
* 6 = phone
* 7 = email
* 8 = charge account - yes/no
* 9 = good standing - yes/no
*/
nameBox.Text = allData[chosenIndex, 1]; // put name in nameBox
addressBox.Text = allData[chosenIndex, 2]; // put address in addressBox
cityBox.Text = allData[chosenIndex, 3]; // put city in cityBox
stateBox.Text = allData[chosenIndex, 4]; //puts state in stateBox
zipBox.Text = allData[chosenIndex, 5]; // puts zip in zipBox
phoneBox.Text = allData[chosenIndex, 6]; // puts phone number in phoneBox
emailBox.Text = allData[chosenIndex, 7]; // puts email in emailBox
if (allData[chosenIndex, 8] == "Yes") // check if charge account
{
yesChargeRadio.Checked = true; // true if Yes
}
else // otherwise
{
noChargeRadio.Checked = true; // true if No
}
if (allData[chosenIndex, 9] == "Yes") // check for good standing
{
yesStandingRadio.Checked = true; // true if Yes
}
else // otherwise
{
noStandingRadio.Checked = true; // true if No
}
}
catch (Exception errorInfo) // catch error
{
MessageBox.Show("errors: " + errorInfo, "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error); // error message
}
}
Here is the method(s) to check the length and format:
private bool numberCheck(string str)
{
const int NUMBER_LENGTH = 10;
bool valid = true;
if (str.Length == NUMBER_LENGTH)
{
foreach (char ch in str)
{
if (!char.IsDigit(ch))
{
valid = false;
}
}
}
else
{
valid = false;
}
return valid;
}
private void formatPhone(ref string str)
{
str = str.Insert(0, "(");
str = str.Insert(4, ")");
str = str.Insert(8, "-");
}
You are almost done with your code. What you need to do is, before you set your phoneBox.Text you can call the method as below:
if(numberCheck(allData[chosenIndex, 6]))
{
formatPhone(ref allData[chosenIndex, 6]);
}
phoneBox.Text = allData[chosenIndex, 6];
As you have your method with ref parameter, the formatted text will be updated in your arary and you can then assign it to your phoneBox
I hope I understand what part specifically you're asking about: you call methods you define just like the static methods IsDigit or MessageBox.Show, except you do not need to prefix the method name with a name and then a period because the method is part of the object calling it.
So, for example if I had a method:
public void ShowSomething()
{
MessageBox.Show("stuff");
}
From within the class, I could call it like this:
ShowSomething();
To pass parameters, I would list them in the parenthesis, as you do with MessageBox.Show, for example.
You can use the value a method like numberCheck returns as any other boolean, so you could do any of these:
bool b = numberCheck(someString);
if (numberCheck(someString))
{
//Do something, like displaying the phone number
}
This MSDN document might help you: http://msdn.microsoft.com/en-us/library/ms173114.aspx
Is this what you're looking for? :
.......
phoneBox.Text = numberCheck(allData[chosenIndex, 6]) ?
formatPhone(allData[chosenIndex, 6]) :
allData[chosenIndex, 6];
.......
private string formatPhone(string str)
{
str = str.Insert(0, "(");
str = str.Insert(4, ")");
str = str.Insert(8, "-");
return str;
}
Codes above will check validity of phone data, if it is valid set phoneBox.Text to formatted phone number, else set phoneBox.Text to raw unformatted phone data.
For reference in case you're not familiar with ternary operator (?).

asp.net flip string (swap words) between character

My scenario is i have a multiline textbox with multiple values e.g. below:
firstvalue = secondvalue
anothervalue = thisvalue
i am looking for a quick and easy scenario to flip the value e.g. below:
secondvalue = firstvalue
thisvalue = anothervalue
Can you help ?
Thanks
protected void btnSubmit_Click(object sender, EventArgs e)
{
string[] content = txtContent.Text.Split('\n');
string ret = "";
foreach (string s in content)
{
string[] parts = s.Split('=');
if (parts.Count() == 2)
{
ret = ret + string.Format("{0} = {1}\n", parts[1].Trim(), parts[0].Trim());
}
}
lblContentTransformed.Text = "<pre>" + ret + "</pre>";
}
I am guessing that your multiline text box will always have text which is in the format you mentioned - "firstvalue = secondvalue" and "anothervalue = thisvalue". And considering that the text itself doesn't contain any "=". After that it is just string manipulation.
string multiline_text = textBox1.Text;
string[] split = multiline_text.Split(new char[] { '\n' });
foreach (string a in split)
{
int equal = a.IndexOf("=");
//result1 will now hold the first value of your string
string result1 = a.Substring(0, equal);
int result2_start = equal + 1;
int result2_end = a.Length - equal -1 ;
//result1 will now hold the second value of your string
string result2 = a.Substring(result2_start, result2_end);
//Concatenate both to get the reversed string
string result = result2 + " = " + result1;
}
You could also use Regex groups for this. Add two multi line textboxes to the page and a button. For the button's onclick event add:
using System.Text.RegularExpressions;
...
protected void Button1_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
Regex regexObj = new Regex(#"(?<left>\w+)(\W+)(?<right>\w+)");
Match matchResults = regexObj.Match(this.TextBox1.Text);
while (matchResults.Success)
{
string left = matchResults.Groups["left"].Value;
string right = matchResults.Groups["right"].Value;
sb.AppendFormat("{0} = {1}{2}", right, left, Environment.NewLine);
matchResults = matchResults.NextMatch();
}
this.TextBox2.Text = sb.ToString();
}
It gives you a nice way to deal with the left and right hand sides that you are looking to swap, as an alternative to working with substrings and string lengths.

Categories