I made a loop:
for (int i = 0; i < sumUSERS; i++ )
{
principal.UserPrincipalName = "bn" + txtbox_cusnumber.Text + "." + txt_user1.Text;
}
In my Form i have Text boxes with the following names :
txt_user1
txt_user2
txt_user3
How can I set the value i in txt_user(i).text?
I hope my question is understandable.
Make an array of the boxes, and use an index, like this:
var txt_user = new [] {txt_user1, txt_user2, txt_user3};
for (int i = 0; i < txt_user.Length ; i++ ) {
principal.UserPrincipalName += "bn" + txtbox_cusnumber.Text + "." + txt_user[i].Text;
}
Note that I replaced = with +=, otherwise the text would be the same as if you used txt_user3 by itself (i.e. only the last assignment would stay).
Related
I am making a code that decrements the line index in an array of strings. My array is like this:
1.ExampleFirst\n
SomeText\n
SomeOtherText\n
FinalLine\n\n
2.ExampleSecond\n
SomeText\n
SomeOtherText\n
FinalLine\n\n
and so on. The lengths of the lines are not the same.
I want the text to be like this:
0.ExampleFirst\n
SomeText\n
SomeOtherText\n
FinalLine\n\n
1.ExampleSecond\n
SomeText\n
SomeOtherText\n
FinalLine\n\n
I have made this code:
int s = 0;
while(s < lineCounter.Count())
{
if (int.TryParse(lineCounter[s].Substring(0, 1), out v) == true && lineCounter[s] != "\n")
{
int m = int.Parse(lineCounter[s].Substring(0,1));
lineCounter[s].Remove(0, lineCounter[s].IndexOf(".")).Insert(0, (m - 1).ToString());
Console.WriteLine(lineCounter[s]);
}
else
Console.WriteLine(lineCounter[s]);
s++;
The "if" is executed only when the line contains the number and when the line is not a new line. The else is executed to write the other lines in the array.(I'm using console.writeLine to see the results. I know I have to change that part)
When I execute this code, I get the following exception in the "if" statement:
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Additional information: Index and length must refer to a location within the string.
To me this means that "if" is executed even when the new line between the last line of the first text block and the first line of the second text block is encountered. I can't explain why. Help please!
Declaring dotIndex with combination of string.Remove() and string.Insert() may do the trick.
string[] lineCounter = new string[]{
"1.ExampleFirst\n",
" SomeText\n",
" SomeOtherText\n",
" FinalLine\n\n",
"2.ExampleSecond\n",
" SomeText\n",
" SomeOtherText\n",
" FinalLine\n\n"
};
for (int i = 0; i < lineCounter.Count(); ++i) {
int dotIndex = lineCounter[i].IndexOf('.');
if (dotIndex < 1) //must be at least in the position of 2 or above
continue;
int lineIndex = 0;
if (int.TryParse(lineCounter[i].Substring(0, dotIndex), out lineIndex)) { //if can be parsed
lineIndex--; //decrement lineIndex
lineCounter[i] = lineIndex.ToString() + lineCounter[i].Remove(0, dotIndex);
}
}
I prefer to use for-loop to make the loop more definite, but you could change that to while/do.
This works fine in my PC. Output:
Edit:
All the results should be in the lineCounter. If you want to see them along the function, you could do:
for (int i = 0; i < lineCounter.Count(); ++i) {
int dotIndex = lineCounter[i].IndexOf('.');
if (dotIndex < 1) { //must be at least in the position of 2 or above
//Print here
continue;
}
int lineIndex = 0;
if (int.TryParse(lineCounter[i].Substring(0, dotIndex), out lineIndex)) { //if can be parsed
lineIndex--; //decrement lineIndex
lineCounter[i] = lineIndex.ToString() + lineCounter[i].Remove(0, dotIndex);
}
//Print here also
}
you probably want this:
string[] lineCounter=new string[]{
"1.ExampleFirst\n",
" SomeText\n",
" SomeOtherText\n",
" FinalLine\n",
"\n",
"2.ExampleSecond\n",
" SomeText\n",
" SomeOtherText\n",
" FinalLine\n",
"\n"
};
int v = 0;
int s = 0;
while (s < lineCounter.Count())
{
if (int.TryParse(lineCounter[s].Substring(0, 1), out v) == true && lineCounter[s] != "\n")
{
int m = int.Parse(lineCounter[s].Substring(0, 1));
Console.WriteLine(lineCounter[s].Remove(0, lineCounter[s].IndexOf(".")).Insert(0, (m - 1).ToString()));
}
else
Console.WriteLine(lineCounter[s]);
s++;
}
I believe you may be having issues with empty lines on the string array.
Maybe something like this works for you.
IEnumerable<string> ShiftIndexes(IEnumerable<string> lines) {
foreach (string line in lines) {
if (!string.IsNullOrEmpty(line) && char.IsDigit(line, 0)) {
int dotPos = line.IndexOf('.');
int index = int.Parse(line.SubString(0, dotPos));
yield return (index - 1).ToString() + line.SubString(dotPos);
}
else
yield return line;
}
}
And then use it like this:
string[] shiftedLines = ShiftIndexes(originalLines).ToArray();
I'm making an application and i need get the same interval of space from a line in many items (strings). My code is something like that
p = "";
int contaletras = 0;
int maxPalavra = 14; int xpto;
contaletras = item.Length;
xpto = maxPalavra - contaletras;
for (int i = 0; i < xpto; i++)
{
p = p + " ";
}
StringBuilder m = new StringBuilder();
m.Append(item);
m.Insert(item.Length, p);
RTB_Exames.Text = RTB_Exames.Text + m.ToString() + " ";
So, my item.length is all the time 14 characteres. But
i dont know why i have this result when in textvisualizer in c# i have this. I will show some image in this link:
https://drive.google.com/file/d/0B5tH_Qo3-GvhSEJrOXVsTzhIQVk/edit?usp=sharing
https://drive.google.com/file/d/0B5tH_Qo3-GvhaTN5WUM1M2M3QVU/edit?usp=sharing
You can either set the font in the visual editor for the TextBox control or set it via:
RTB_Exames.FontFamily = new FontFamily("Consolas");
I want to automatically add parameters based on the input of control numbers.
the following code will give me sp_INSERT #COL5, sp_INSERT #COL4, so on...
control = 5;
while(1<=control)
column = '#COL'
string setValues = "sp_INSERT'" + column + control + "';"
control = control - 1;
What I want to achieve is sp_INSERT #COL5, #COL4, #COL3, so on...
Just... loop?
int control = 5;
string colPrefix = "#COL";
var sql = new StringBuilder("sp_INSERT ").Append(colPrefix).Append(control);
// note first item has different format due to comma
for(int i = control - 1; i > 0; i--)
{
sql.Append(", ").Append(colPrefix).Append(i);
}
sql.Append(';');
string s = sql.ToString();
Simple loop, not a complete solution, but it might help...
string myString = "INSERT ";
for (int i = 5; i > 0; i--)
myString = string.Format("{0} #COL{1}, ", myString, i);
I am trying To create check boxes list dynamically using c# and insert the check box text values to databse.But I dnt Understand How Can I Create and access its values to insert into db.Is there any one help me in this regard coz i have no strong idea except this.
public void CreateCheckBox(int n)
{
for (int i = 0; i <= n; i++)
{
Response.Write(#"<input type=""checkbox"" name=""link"" value=" + "CA0" + i +">"+"CA0"+ i +"<br>") ;
}
}
How Can I access its value to be inserted to db.Plz Help
you can assign an id attribute to the checkboxes like:
for (int i = 0; i <= n; i++)
{
Response.Write(#"<input id='check'" + i.ToString() + " type=""checkbox"" name=""link"" value=" + "CA0" + i +">"+"CA0"+ i +"<br>") ;
}
then on the event that you want to retrieve the values simply you can use the following:
for(int i=0;i<=n;i++)
{
var data=Request.Form["check" + i.ToString()]; // this should hold the value of the checkbox as string
}
hope that it will help
regards
I wish to implement a fairly simple CSV checker in my C#/ASP.NET application - my project automatically generates CSV's from GridView's for users, but I want to be able to quickly run through each line and see if they have the same amount of commas, and throw an exception if any differences occur. So far I have this, which does work but there are some issues I'll describe soon:
int? CommaCount = null;
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
String Str = null;
//This loops through all the headerrow cells and writes them to the stringbuilder
for (int k = 0; k <= (grd.Columns.Count - 1); k++)
{
sw.Write(grd.HeaderRow.Cells[k].Text + ",");
}
sw.WriteLine(",");
//This loops through all the main rows and writes them to the stringbuilder
for (int i = 0; i <= grd.Rows.Count - 1; i++)
{
StringBuilder RowString = new StringBuilder();
for (int j = 0; j <= grd.Columns.Count - 1; j++)
{
//We'll need to strip meaningless junk such as <br /> and
Str = grd.Rows[i].Cells[j].Text.ToString().Replace("<br />", "");
if (Str == " ")
{
Str = "";
}
Str = "\"" + Str + "\"" + ",";
RowString.Append(Str);
sw.Write(Str);
}
sw.WriteLine();
//The below code block ensures that each row contains the same number of commas, which is crucial
int RowCommaCount = CheckChar(RowString.ToString(), ',');
if (CommaCount == null)
{
CommaCount = RowCommaCount;
}
else
{
if (CommaCount!= RowCommaCount)
{
throw new Exception("CSV generated is corrupt - line " + i + " has " + RowCommaCount + " commas when it should have " + CommaCount);
}
}
}
sw.Close();
And my CheckChar method:
protected static int CheckChar(string Input, char CharToCheck)
{
int Counter = 0;
foreach (char StringChar in Input)
{
if (StringChar == CharToCheck)
{
Counter++;
}
}
return Counter;
}
Now my problem is, if a cell in the grid contains a comma, my check char method will still count these as delimiters so will return an error. As you can see in the code, I wrap all the values in " characters to 'escape' them. How simple would it be to ignore commas in values in my method? I assume I'll need to rewrite the method quite a lot.
var rx = new Regex("^ ( ( \"[^\"]*\" ) | ( (?!$)[^\",] )+ | (?<1>,) )* $", RegexOptions.ExplicitCapture | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);
var matches = rx.Matches("Hello,World,How,Are\nYou,Today,This,Is,\"A beautiful, world\",Hi!");
for (int i = 1; i < matches.Count; i++) {
if (matches[i].Groups[1].Captures.Count != matches[i - 1].Groups[1].Captures.Count) {
throw new Exception();
}
}
You could just use a regular expression that matches one item and count the number of matches in your line. An example of such a regex is the following:
var itemsRegex =
new Regex(#"(?<=(^|[\" + separator + #"]))((?<item>[^""\" + separator +
#"\n]*)|(?<item>""([^""]|"""")*""))(?=($|[\" + separator + #"]))");
Just do something like the following (assuming you don't want to have " inside your fields (otherwise these need some extra handling)):
protected static int CheckChar(string Input, char CharToCheck, char fieldDelimiter)
{
int Counter = 0;
bool inValue = false;
foreach (char StringChar in Input)
{
if (StringChar == fieldDelimiter)
inValue = !inValue;
else if (!inValue && StringChar == CharToCheck)
Counter++;
}
return Counter;
}
This will cause inValue to be true while inside fields. E.g. pass '"' as fieldDelimiter to ignore everything between "...". Just note that this won't handle escaped " (like "" or \"). You'd have to add such handling yourself.
Instead of checking the resulting string (the cake) you should check the fields (ingredients) before you concatenate (mix) them. That would give you the change to do something constructive (escaping/replacing) and throwing an exception only as a last resort.
In general, "," are legal in .csv fields, as long as the string fields are quoted. So internal "," should not be a problem, but the quotes may well be.