C# textbox to Array - c#

I'm sure this is really simple to do but i'm struggling.
private void button1_Click(object sender, EventArgs e)
{
SaveBtn();
void SaveBtn()
{
string savetext = textBox1.Text;
string savetext2 = textBox2.Text;
File.AppendAllText(#"C:\Riot Games\AccountSwitcher.txt", savetext + Environment.NewLine + savetext2 + Environment.NewLine + Environment.NewLine);
MessageBox.Show("Your ID: " + savetext + " and you PWD: " + savetext2 + " has been saved.");
}
}
As you can see i have 2 textbox and when i'm clicking the button "save" both input are saved into a file.txt. This code works like a charm but i'd rather save these 2 inputs into an array so i could use them individually.
Thanks your help, i'm pretty noob as you can see so please keep it simple :D <3

Use:
string[] savetexts = new string[]{ savetext , savetext2 };

Alternatively, you could convert the entire string and save it in a char array.
char[] savetext = savetext.ToCharArray();
char[] savetext2 = savetext2.ToCharArray();
Hope this helps.!

P.S It is much easier to use a List instead of hard-coded arrays like above.
List<String> myStrings = new List<String>();
myStrings.add(savetext);
myStrings.add(saveText2);
.....etc
then to get them back you iterate over myStrings
foreach(String s in myStrings){
Console.writeline(s);
}
Or you can access them directly
String text1 = myStrings[0];
String text2 = myString[1];
This is a bit more than what you are asking, but using List becomes much easier in the long run. Best of luck.

Related

Preventing duplicate entries to excel

I'm creating a program in my free time to store info about my trading card collection. I was wondering is there any way to prevent duplicate entries into excel using the File.AppendAllText method. My current code is:
private void btnAdd_Click(object sender, EventArgs e)
{
Global.card.Add(new Card(lblCardNoFinal.Text, lblCardNameFinal.Text, lblCardRarityFinal.Text, lblCardTypeFinal.Text));
string file = ("..\\Debug\\LOB.csv");
string delimiter = ",";
StringBuilder sb = new StringBuilder();
foreach (Card card in Global.card)
{
sb.AppendLine(card.CardNo + delimiter + card.CardName + delimiter + card.CardRarity + delimiter + card.CardType);
}
File.AppendAllText(file, sb.ToString());
MessageBox.Show("Card Added");
}
When I try to add more than one card, the data of the previous one is entered into the excel file so it appears twice when I don't want it to. Thanks
Try File.WriteAllText instead. File.AppendAllText will add the text to the bottom of the file.
Alternatively, you could do File.AppendAllLines for the card you are adding, like this:
private void btnAdd_Click(object sender, EventArgs e)
{
string file = ("..\\Debug\\LOB.csv");
string delimiter = ",";
var card = new Card(lblCardNoFinal.Text, lblCardNameFinal.Text, lblCardRarityFinal.Text, lblCardTypeFinal.Text)
Global.card.Add(card);
File.AppendAllLines(file, new[] {card.CardNo + delimiter + card.CardName + delimiter + card.CardRarity + delimiter + card.CardType});
MessageBox.Show("Card Added");
}
It looks that whenever you add single card you're appending all cards from Global.card, so I would get rid of foreach loop. You can just append this single card.
Try something like:
Card newCard = new Card(lblCardNoFinal.Text, lblCardNameFinal.Text, lblCardRarityFinal.Text, lblCardTypeFinal.Text)
Global.card.Add(newCard)
File.AppendAllText(file, newCard.CardNo + delimiter + newCard.CardName + delimiter + newCard.CardRarity + delimiter + newCard.CardType);
You also don't need StringBuilder, but I would work on ToString method for your Card class.

CSV To SQL Converter

I'm currently having some issues with my CSV to SQL Converter. With this being my third week of learning C# I'm starting to grasp some stuff but this is going over my head a bit.
What I'm trying to do is have the Top row/Titles taken down split into each individual title and then for the SQL code through that rather than entering it manually like I've done. Below you can see some of my code that I've built so far.
private void Form1_Load(object sender, EventArgs e)
{
try
{
// your code here
string CSVFilePathName = #"C:\\CSV\\reg.csv";
string[] Lines = File.ReadAllLines(CSVFilePathName);
string[] Fields;
//1st row must be column names; force lower case to ensure matching later on.
// get regs from filename
// get fieldnames from Lines[0] (first line of file)
// create a loop for fields array
string hdr = Lines[0];
for (int i = 1; i < Lines.Length; i++)
{
Fields = Lines[i].Split(new char[] { ',' });
CSVTextBox.AppendText(Fields[0] + "," + Fields[1] + "," + Fields[2] + "," + Fields[3] + Environment.NewLine);
// need a for loop for each field
// for (
SQLTextBox.AppendText("INSERT INTO[dbo].[REGS]([SESTYPE],[REG],[LFL],[SUBVER]) VALUES('" + Fields[3] + "'" + Fields[0] + "'" + Fields[1] + "'" + Fields[2] + ")" + Environment.NewLine);
// }
}
}
catch (Exception ex)
{
MessageBox.Show("Error is " + ex.ToString());
throw;
}
}
This all runs at the moment, I'm just struggling to get the titles to become part of the code. Any help would be appreciated.
Cheers,
First: Remove the try catch. If you get an Exception, you should read, understand and clear off.
For your SQLTextBox: I recommend to use the String.Format function. This allows you to create strings with different values, but is much, much easier to read.
For the titles: Use your variable hdr This should contain the title. Then you can split it via string.Split(',') or string.Split(';'), depending on your delimiter

accessing data from database and displaying it in textbox

I am using this code for accessing data from database and displaying it in textboxes,but i am getting whole string columns in 1st textbox ,how do i split and display in respective textboxes,i am getting this exception Index was outside the bounds of the array. at this line of code txtOption2.Text = coldata[2];
public EditQuestionMaster(int qid_value)
{
InitializeComponent();
string columns = db.GetEditQuestions(qid_value);
string[] coldata=columns.Split('$');
txtQuestion.Text = coldata[0];
txtOption1.Text = coldata[1];
txtOption2.Text = coldata[2];
txtOption3.Text = coldata[3];
txtOption4.Text = coldata[4];
}
GetEditQuestions(qid_value) Code
public string GetEditQuestions(int qid)
{
string data = "";
try
{
string sql = "select QID,Question,Opt1,Opt2,Opt3,Opt4,AnsOp,Marks from Questions where QID IN(" + qid + ") ";
cmd = new OleDbCommand(sql, acccon);
rs = cmd.ExecuteReader();
if (rs.Read())
{
data = rs[0].ToString() + "~" + rs[1].ToString() + "~" + rs[2].ToString() + "~" + rs[3].ToString() + "~" + rs[4].ToString() + "~" + rs[5].ToString() + "~" + rs[6].ToString() + "~" + rs[7].ToString() + "$";
}
}
catch (Exception err)
{
}
return data;
}
thank you in advance for any help
You appear to split the string by $ but you build the string up using ~ as the separator. You need to split the string by ~ to get the appropriate number of columns i.e.
string[] coldata = columns.Split("~")
You are seeing that error because you only have 2 items in coldata. Try debugging and view the length of the coldata array to see how many items it contains.
Change your code to use this split instead:
string[] coldata=columns.Split('~');
Looking at your code sample you just need to change:
string[] coldata=columns.Split('$');
To
string[] coldata=columns.Split('~');
As your columns are delimited by the ~ character.

C# Converting/Splitting a String with numeric and letters

I tried to split a String into a parts array and combine them at the end into a result String.
But while I tested a little bit, I get a message.
By pressing convert_click:
"NullRefenceException was unhandeled"
Object reference not set to an instance of an object.
Here the main code:
public string []parts { get; set; }
public string inputStr { get; set; }
private void inputText_TextChanged(object sender, EventArgs e)
{
String inputStr = inputText.ToString();
//example
//inputStr = "984, fenceshit2, 0, 1994.56025813, -1592.16428141, 16.105, 0.653280779782, 0.270598520636, 0.653281646552, 0.270598879665, -1";
}
private void convert_Click(object sender, EventArgs e)
{
String creObj = "CreateObject(";
String result;
String[] parts = inputStr.Split(new char[] { ',' });
result = creObj +
parts[0] + "," +
parts[2] + "," +
parts[3] + "," +
//...up to "parts[10"
");";
outputText.Text = result;
//output(should be in this case):
//"CreateObject(984, 1994.56025813, -1592.16428141, 16.105, 0.653280779782, 0.270598520636, 0.653281646552, 0.270598879665, -1);"
}
//If I need to creat a code line in the main Designer.cs, please let me know.
I just want to split a String and combine them in the end into 1 string and send this into a text box.
If someone wants the sourcecode, pm me.
Because you are assigning inputText.toString() to local inputStr. Inside function inputText_TextChanged, just write
inputStr = inputText.Text;
You are declaring a local copy of input string, when you really want to be assigning to the public one.
Instead of
String inputStr = inputText.ToString();
Just do this:
inputStr = inputText.ToString();

RegEx -- getting rid of double whitespaces?

I have an app that goes in, replaces "invalid" chars (as defined by my Regex) with a blankspace. I want it so that if there are 2 or more blank spaces in the filename, to trim one. For example:
Deal A & B.txt after my app runs, would be renamed to Deal A   B.txt (3 spaces b/w A and B). What i want is really this: Deal A B.txt (one space between A and B).
I'm trying to determine how to do this--i suppose my app will have to run through all filenames at least once to replace invalid chars and then run through filenames again to get rid of extraneous whitespace.
Can anybody help me with this?
Here is my code currently for replacing the invalid chars:
public partial class CleanNames : Form
{
public CleanNames()
{
InitializeComponent();
}
public void Sanitizer(List<string> paths)
{
string regPattern = (#"[~#&$!%+{}]+");
string replacement = " ";
Regex regExPattern = new Regex(regPattern);
StreamWriter errors = new StreamWriter(#"S:\Testing\Errors.txt", true);
var filesCount = new Dictionary<string, int>();
dataGridView1.Rows.Clear();
try
{
foreach (string files2 in paths)
{
string filenameOnly = System.IO.Path.GetFileName(files2);
string pathOnly = System.IO.Path.GetDirectoryName(files2);
string sanitizedFileName = regExPattern.Replace(filenameOnly, replacement);
string sanitized = System.IO.Path.Combine(pathOnly, sanitizedFileName);
if (!System.IO.File.Exists(sanitized))
{
DataGridViewRow clean = new DataGridViewRow();
clean.CreateCells(dataGridView1);
clean.Cells[0].Value = pathOnly;
clean.Cells[1].Value = filenameOnly;
clean.Cells[2].Value = sanitizedFileName;
dataGridView1.Rows.Add(clean);
System.IO.File.Move(files2, sanitized);
}
else
{
if (filesCount.ContainsKey(sanitized))
{
filesCount[sanitized]++;
}
else
{
filesCount.Add(sanitized, 1);
}
string newFileName = String.Format("{0}{1}{2}",
System.IO.Path.GetFileNameWithoutExtension(sanitized),
filesCount[sanitized].ToString(),
System.IO.Path.GetExtension(sanitized));
string newFilePath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(sanitized), newFileName);
System.IO.File.Move(files2, newFilePath);
sanitized = newFileName;
DataGridViewRow clean = new DataGridViewRow();
clean.CreateCells(dataGridView1);
clean.Cells[0].Value = pathOnly;
clean.Cells[1].Value = filenameOnly;
clean.Cells[2].Value = newFileName;
dataGridView1.Rows.Add(clean);
}
}
}
catch (Exception e)
{
errors.Write(e);
}
}
private void SanitizeFileNames_Load(object sender, EventArgs e)
{ }
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
The problem is, that not all files after a rename will have the same amount of blankspaces. As in, i could have Deal A&B.txt which after a rename would become Deal A B.txt (1 space b/w A and B--this is fine). But i will also have files that are like: Deal A & B & C.txt which after a rename is: Deal A   B   C.txt (3 spaces between A,B and C--not acceptable).
Does anybody have any ideas/code for how to accomplish this?
Do the local equivalent of:
s/\s+/ /g;
Just add a space to your regPattern. Any collection of invalid characters and spaces will be replaced with a single space. You may waste a little bit of time replacing a space with a space, but on the other hand you won't need a second string manipulation call.
Does this help?
var regex = new System.Text.RegularExpressions.Regex("\\s{2,}");
var result = regex.Replace("Some text with a lot of spaces, and 2\t\ttabs.", " ");
Console.WriteLine(result);
output is:
Some text with a lot of spaces, and 2 tabs.
It just replaces any sequence of 2 or more whitespace characters with a single space...
Edit:
To clarify, I would just perform this regex right after your existing one:
public void Sanitizer(List<string> paths)
{
string regPattern = (#"[~#&$!%+{}]+");
string replacement = " ";
Regex regExPattern = new Regex(regPattern);
Regex regExPattern2 = new Regex(#"\s{2,}");
and:
foreach (string files2 in paths)
{
string filenameOnly = System.IO.Path.GetFileName(files2);
string pathOnly = System.IO.Path.GetDirectoryName(files2);
string sanitizedFileName = regExPattern.Replace(filenameOnly, replacement);
sanitizedFileName = regExPattern2.Replace(sanitizedFileName, replacement); // clean up whitespace
string sanitized = System.IO.Path.Combine(pathOnly, sanitizedFileName);
I hope that makes more sense.
you can perform another regex replace after your first one
#" +" -> " "
As Fosco said, with formatting:
while (mystring.Contains(" ")) mystring = mystring.Replace(" "," ");
// || || |
After you're done sanitizing it your way, simply replace 2 spaces with 1 space, while 2 spaces exist in the string.
while (mystring.Contains(" ")) mystring = mystring.Replace(" "," ");
I think that's the right syntax...

Categories