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
Related
sb.AppendLine("Employee Id,First Name,Last Name,Email,Username,Password,Role,Group Name,Country Code, Supervisor Id, Hire Date, Birth Date");
for (int i = 0; i < dt.Rows.Count; i++)
{
String[] empid = dt.Rows[i]["EmpId"].ToString().Split(new Char[] { '-' });
sb.AppendLine(Convert.ToInt32(empid[0]).ToString("000000") + "," + dt.Rows[i]["FirstName"] + "," + dt.Rows[i]["LastName"].ToString().Replace(",", " ") +
",," + dt.Rows[i]["Email"] + ",reward," + dt.Rows[i]["Role"] + ",CCCC," + ",," + ",," + dt.Rows[i]["EmployeeHireDate"] + "," + dt.Rows[i]["EmployeeBirthDate"]);
}
email field needs to be empty,
username needs to be the email,
country code needs to be empty,
supervisor id needs to be empty,
Replace this segement:
+ ",CCCC," + ",," + ",," +
with this:
+ ",CCCC,,," +
But you'll really do MUCH better with a dedicated csv library, of which there are several good options on NuGet.
Additionally, if you're using StringBuilder because you heard it's faster, remember that faster is relative. StringBuilder is faster than string concatenation for this kind of work, but if you're ultimately going to writing to a network stream, file, or web response you'll do even better using a StreamWriter
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.
private void btnAssemble_Click(object sender, EventArgs e)
{
txtAssembled.Text = (cboTitle.Text + txtFirstName.Text[0] + txtMiddle.Text + txtLastName.Text + "\r\n" +txtStreet.Text + "\r\n"+ cboCity.Text);
}
I'm trying to get 1 character white space inbetween cboTitle.Text, txtFirname.Text, txtMiddle.Text, and txtLastName, but they all output the information together, but I want them spaced evenly. what do I need to do? thanks in advance.
I'm going to post some other code thats below the one above in my project, just in case it might be relevant.
string AssembleText(string Title, string FirstName, string MiddleInitial, string LastName, string AddressLines, string City )
{
string Result = "";
Result += Title + " ";
Result += FirstName.Substring(0, 2) + " ";
// Only append middle initial if it is entered
if (MiddleInitial != "")
{
Result += MiddleInitial + " ";
}
Result += LastName + "\r\n";
// Only append items from the multiline address box
// if they are entered
if ( AddressLines != "")
{
Result += AddressLines + "\r\n";
}
//if (AddressLines.Length > 0 && AddressLines.ToString() != "")
//{
// Result += AddressLines + "\r\n";
//}
Result += City;
return Result;
}
}
}
If you just want a space between those specific fields in btnAssemble_Click, you can just insert them like this:
string myStr = foo + " " + bar + " " + baz;
So your first function would be modified to read:
private void btnAssemble_Click(object sender, EventArgs e)
{
txtAssembled.Text = (cboTitle.Text + " " + txtFirstName.Text[0] + " " + txtMiddle.Text + " " + txtLastName.Text + "\r\n" + txtStreet.Text + "\r\n" + cboCity.Text);
}
A few other comments:
It's not clear to me what the AssembleText() function you posted has to do with this. I am confused though, as I see a few lines appending spaces at the end just like I mentioned above.
Using the String.Format() function may make this code easier to read and maintain.
Using Environment.NewLine instead of "\r\n" will make the string contain the newline character defined for that specific environment.
Using a StringBuilder object may be faster over concatenation when building strings inside of a loop (which may not apply here).
Using String.format() should feet the bill. It also make your code easy to read.
txt.assembled.text = String.Format("{0} {1} {2} {3}",
cboTitle.Text,
txtFirstName.Text[0],
txtMiddle.Text,
txtLastName.Text
);
It would be like this
private void btnAssemble_Click(object sender, EventArgs e)
{
txtAssembled.Text = (cboTitle.Text + " " + txtFirstName.Text[0] + " " +txtMiddle.Text + " " + txtLastName.Text + "\r\n" +txtStreet.Text + "\r\n"+ cboCity.Text);
}
It seems that you want String.Join; whenever you want to combine strings with a delimiter, say, " " (space) all you need is to put
String combined = String.Join(" ",
cboTitle.Text,
txtFirstName.Text[0],
txtMiddle.Text,
txtLastName.Text);
Complete implementation (joining by space and new line) could be
txtAssembled.Text = String.Join(Environment.NewLine,
String.Join(" ",
cboTitle.Text,
txtFirstName.Text[0],
txtMiddle.Text,
txtLastName.Text),
txtStreet.Text,
cboCity.Text);
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.
I am creating a long string in my c# application. I want it to stay on one line as these are the headers for fields the user has selected to update in the database.
The string will be used in a log file.
When I select all the fields to be updated it seems that the string is to long to be displayed in a single line and is automatically wrapped.
I am confused as textfile should be able to handle a string of any length (Memory permitting) without wrapping.
It seems that once the string gets longer than about 1050 characters it does an Automatic wrap.
My code is below:
private void UpdateCustomer(string pCurrentFileName, ref StringBuilder log, string date, ref string directoryPath, ref string logFilePath)
{
// set the logfile paths for customer update
directoryPath = Path.Combine(pLogFilePath, "CustomerUpdate_Log_" + date.Replace("/", "").Replace(" ", "").Replace(":", ""));
logFilePath = Path.Combine(directoryPath, "CustomerUpdate.log");
DataSet customerUpdateDataSet = new CustomerUpdateValidator().ImportCustomersForUpdateFromExcelFileToDataSet(pCurrentFileName);
log.Append("-------------------------------------------------------------------------" + "\r\n");
log.Append("Bulk Maintenance Log: Customer Updatess" + "\r\n");
log.Append("-------------------------------------------------------------------------" + "\r\n");
log.Append(date + "\r\n\r\n");
log.Append("Total number of Customer to be updated: " + (customerUpdateDataSet.Tables["CustomerData"].Rows.Count - 2).ToString() + "\r\n\r\n");
log.Append("Data to be Inserted" + "\r\n");
log.Append("-".PadRight(300, '-') + "\r\n\r\n\r\n");
StringBuilder header = new StringBuilder("Row".PadRight(10, ' ') + "\t");
header.Append("URN".PadRight(40, ' ') + "\t");
int count = 0;
// for each row in the grid view
for (int i = 0; i < this.gridView1.DataRowCount; i++)
{
// if the value is checked
if (Convert.ToBoolean(this.gridView1.GetRowCellValue(i, "CheckMarkSelection")))
{
// get the fields from the checked column
string baxiDescription = this.gridView1.GetRowCellValue(i, "SimpleName").ToString();
int size = getSizeFromType(this.gridView1.GetRowCellValue(i, "Type").ToString());
header.Append(baxiDescription.PadRight(size, ' ') + "\t");
count = i;
}
}
header.Append("Result".PadRight(10, ' ') + "\t");
header.Append("Reason".PadRight(30, ' ') + "\t");
log.Append(header.ToString() + "\r\n");
log.Append(new StringBuilder("-".PadRight(header.Length + 60, '-') + "\r\n"));
}
Any ideas why this is happening?
My DataSet:
Wrapped LogFile:
It seems that as I am saving my generated string into a .txt file and then opening the textfile in my logfile browser that the problem is related to .txt files and not actually my code