How to handle substring on a changing string variable - c#

I am currently developing an Excel reader, that is inserting into a database. Things have been going smoothly untill I stumbled on some variation in the Excel sheet.
100 rows, somehwere in the middle of the sheet, have a different style than the rest of the sheet, and my substring fails.
To give some clarification here are how they usually look:
DMK.2003602
DMK.4663501
DMK.3307301
etc.
To get the number I use a substring on the column in the row like this
row[12].ToString().Substring(4).ToString());
Pretty simple. However at some point it changes to this
82AVG.A410201
And my substring does not work and I get a type error when insertion to the database.
Any clue on how to handle such a change during the loop of rows?
Here is my loop,
foreach (var row in albums)
{
if (row.ItemArray.Length == 33 && row.ItemArray[0].ToString() != ""
&& row.ItemArray[1].ToString() != ""
&& row.ItemArray[2].ToString() != ""
&& row.ItemArray[3].ToString() != ""
&& row.ItemArray[4].ToString() != ""
&& row.ItemArray[5].ToString() != "")
{
Order ord = new Order(
1,
maxTrNo +1,
row[6].ToString().Substring(row[6].ToString().Length - 5).ToString(),
1,
numVal,
row[13].ToString(),
"",
row[12].ToString().Substring(4).ToString()); //This is where it fails
orders.Add(ord);
maxTrNo++;
}
}

Use string.IndexOf('.') to get the characters after the dot,
string s = row[i].ToString();
string afterDot = s.Substring(s.IndexOf('.' + 1));
To handle the case when there is no dot
int dot = s.IndexOf('.');
string afterDot = dot == -1 ? string.Empty : s.Substring(dot + 1);

Just to get the part of string after '.', you can use (assuming you want empty string in cases of 'DMK2003602' or 'DMK2003602.')
var str = "DMK.2003602";
var subStr = str.IndexOf('.') > -1 && str.IndexOf('.') < str.Length -1 ? str.Substring(str.IndexOf('.') + 1) : string.Empty;
But for the database insertion error, there might be some other reason.

Related

Why is this false if statement running? (C#)

See the link:
http://i.imgur.com/gFcamd8.png
Notice the Autos window at the bottom shows that toParse = "". However toParse != "" evaluates as true anyway, causing the application to crash.
Here's the full method:
public void parseString(string toParse)
{
while (toParse != "")
{
string nextLine = readLine(ref toParse);
if (nextLine.IndexOf("//") == 0)
{
comments.Add(nextLine);
continue;
}
if (nextLine.IndexOf(".") == 0)
{
string[] declarationParts = nextLine.Split(' ');
string declarationString = declarationParts[0].Substring(1, declarationParts[0].Length - 1);
declarationString = char.ToUpper(declarationString[0]) + declarationString.Substring(1);
DirectiveEnum type = (DirectiveEnum)Enum.Parse(typeof(DirectiveEnum), declarationString);
string[] attributes = declarationParts.Skip(1).ToArray();
MSILNode newNode = new MSILNode(type);
newNode.addAttributes(attributes);
toParse = toParse.Trim();
if (toParse != "")
{
while (toParse[0] != '{' && toParse[0] != '.' && toParse.IndexOf("//") != 0)
{
nextLine = readLine(ref toParse);
attributes = nextLine.Split(' ');
newNode.addAttributes(attributes);
}
if (toParse[0] == '{')
{
readLine(ref toParse);
string inside = separate(ref toParse, "}");
newNode.parseString(inside);
}
}
subNodes.Add(newNode);
continue;
}
Console.WriteLine(nextLine);
}
}
It's difficult to see everything that's happening during the debugging session when only given this one snapshot. However, since toParse is passed by reference to the function readline() (line 57), it's value can be changed in the body of that function.
From the PNG image provided in the original question:
53 if (toParse != "")
54 {
55 while (toParse[0] != '{' && toParse[0] != '.' && toParse.IndexOf("//") != 0)
56 {
57 nextLine = readLine(ref toParse);
58 ...
At line 53, toParse is not empty. Then, during one of the iterations of the while loop, it is updated to an empty value. This would cause any accesses to array indices (i.e. toParse[0] in the while condition) to throw an exception.
For more information on the ref keyword in C#, see this StackOverflow issue or this official Microsoft documentation.
I hope this helps!
In the image, this line newNode.parseString(inside) is highlighted meaning that it's in the Callstack and was called before crashing. This line is probably mutating toParse to be "".

Want to get total of same string values in a column of gridview

There is checkbox column in the gridview from which string value "P" is getting on checked. So, I want to calculate all rows of this column having same "P" values. I tried below code:
int sumP = 0;
public void countpresent() //To count all Present Students in the gridview
{
for (int i = 0; i < (dgvAttendance.Rows.Count-1); i++)
{
if (dgvAttendance.Rows[i].Cells["Present"].Value.ToString() == "P")
{
sumP += 1;
}
}
lblPresent.Text = sumP.ToString();
}
it is working for all the sting "P" but when it shows value null, it throws an exception "Object reference notset to an instance of an object". In the exception detail it is showing "NullReferenceException".
Please any one suggest something to help
You may want to check if the dgv row isn't null before you do your operation:
In C#6:
if (dgvAttendance.Rows[i].Cells["Present"].Value?.ToString() == "P")
{
sumP += 1;
}
Or in older version:
if (dgvAttendance.Rows[i].Cells["Present"].Value != null && dgvAttendance.Rows[i].Cells["Present"].Value?.ToString() == "P")
{
sumP += 1;
}
Or actually, in older version, you could try use Convert.ToString, since it is designed to handle null
if (Convert.ToString(dgvAttendance.Rows[i].Cells["Present"].Value) == "P")
{
sumP += 1;
}
It throws an exception because:
dgvAttendance.Rows[i].Cells["Present"].Value
is null and you can't do a .ToString() on a null value.
You can check that it's not null first:
if (dgvAttendance.Rows[i].Cells["Present"].Value != null &&
dgvAttendance.Rows[i].Cells["Present"].Value.ToString() == "P")
with C# 6 you can do this in a single line:
if (dgvAttendance.Rows[i].Cells["Present"].Value?.ToString() == "P")
The ? is short hand for the != null &&

Find occurrences of each value of a datagridview column in a text and display each occurrence to the next column

I am having a problem here. I am trying to display how many times each one of the strings in datagridview column "Values" appear. I am trying to display each occurrence next to each value(for example I want this: 71->4, 83 ->7 , 0B->6 etc.). Here is my code. I'm only taking as a result the first one. Thanks in advance.
private void button4_Click(object sender, EventArgs e)
{
string Text = richTextBox1.Text;
string[] words = Text.Split(' ');
foreach (string word in words)
{
dataGridView1.Rows.Add(word);
}
string searchTerm = " " ;
foreach (DataGridViewRow r in dataGridView1.Rows )
{
if (searchTerm == null || searchTerm == String.Empty || searchTerm.Trim().Length == 0)
{
searchTerm = r.Cells["Value_Detected"].Value.ToString();
var matchQuery = from wor in words
where wor.ToUpperInvariant() == searchTerm.ToUpperInvariant()
select wor;
int wordCount = matchQuery.Count();
r.Cells["Occur"].Value = wordCount.ToString();
}
}
button4.Enabled = false;
}
Instead of
if (searchTerm == null || searchTerm == String.Empty || searchTerm.Trim().Length == 0)
it should be :
if (r.Cells["Value_Detected"].Value != null)

How to check for end of string in textbox in c#

I am a noob, I am stuck on this code.
I am taking input from user in a textbox and saving it in a string. Then I want to run a loop until the string ends and I put if condition for different characters....
string que;
que = textBlock1.Text;
while (!que[i].Equals('\0'))
{
int res;
if (int.TryParse(que[i].ToString(), out res) || que[i].ToString() == "x" || que[i].ToString() == "/" || que[i].ToString() == "^")
{
f[j] = f[j] + que[i].ToString();
}
if (que[i].ToString() == "+" || que[i].ToString() == "-")
j++;
i++;
}
Can someone please guide me? What should I do??
Use:
textBlock1.Text.Lenght
That way you can know the length of the string.
Have you tried foreach(char c in que){ /*your code*/ } ?
If you want to just run through the loop until the end of the string, a simple condition like this should do:
int i = 0;
while (i < que.Length )
{
// Your code
}

How to find out if first simbol is "_" and if true remove it and make first letter capital?

We have a string (0 .. N simbols long). How to find out if its first simbol is "_" and if true remove it and make first letter capital (fro example "_distance" => "Distance")?
I wondered in general - so stupid I am, while I was investigating creation of Unity3d CustomEditor Components visiable to Inspector. So idea was - if class feild starts with _ do parsing etc.
But it appeares that in Unity3d for private class fields which are usually written like _name when you flag it with something like [SerializeField] inspector will do such thing automatically.
Very trivial, actually:
if (s.StartsWith("_")) {
s = s.Substring(1, 1).ToUpper() + s.Substring(2);
}
Reads almost the same as your description, actually. And it will fail if N is less than 2. But you can check for that separately, e.g.:
if (s.Length >= 2 && s.StartsWith("_"))
Try
if (s != null && s.Length >= 2 && s[0] == '_') {
s = Char.ToUpper(s[1]) + s.Substring(2);
}
If you know that s cannot be null, drop the first test.
if (s.Length >= 2 && s[0] == '_') {
s = Char.ToUpper(s[1]) + s.Substring(2);
}
Messy one-liner:
String name = "_distance";
name = (name.StartsWith("_") ? (name.Length > 1 ? name.Substring(1, 1).ToUpper() + (name.Length > 2 ? name.Substring(2) : "") : "") : name);
Clearer version of the one-liner:
String name = "_distance";
if (name.StartsWith("_"))
{
if (name.Length > 1)
{
name = name.Substring(1, 1).ToUpper() + (name.Length > 2 ? name.Substring(2) : "");
}
else
{
name = "";
}
}
Extention version:
public static String ParseCapitalize(this String str)
{
if (str == null)
return "";
if (str.StartsWith("_"))
{
if (str.Length > 1)
{
return str.Substring(1, 1).ToUpper() + (str.Length > 2 ? str.Substring(2) : "");
}
else
{
return "";
}
}
return str;
}
//Usage:
String s = "_this is a string";
if(!String.IsNullOrEmpty(s))
s = s.ParseCapitalize();
These snippets will handle:
"" => ""
"_" => ""
"_a" => "A"
"_asd" => "Asd"
"asd" => "asd"
(For the extention only) null => ""

Categories