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.
Related
I have a file containing text and I can get it to populate a textbox on page load but it always adds a blank first line. Any ideas? I've tried skipping the first line in the array in case it was blank (both 0 and 1) but 0 does nothing and 1 skips the first line in the text file.
I've also tried to set the textbox to null and "" first in case it was appending to the textbox in some way.
//Populating the contents box
string[] str = null;
if (File.Exists(docPath + prefix + libIDPath + "\\" + oldFileName))
{
str = File.ReadAllLines(docPath + prefix + libIDPath + "\\" + oldFileName);
//str = str.Skip(0).ToArray();
//FDContentsBox.Text = null;
}
foreach (string s in str)
{
FDContentsBox.Text = FDContentsBox.Text + "\n" + s;
}
In your foreach you are appending the "\n" before appending the string itself. Try
FDContentsBox.Text = FDContentsBox.Text + s + "\n";
instead.
Please try this, there is no need to read all lines nor a foreach loop
var filePath = docPath + prefix + libIDPath + "\\" + oldFileName;
if (File.Exists(filePath))
{
FDContentsBox.Text = File.ReadAllText(filePath);
}
I have a textbox that contains all of the lines of a loaded file.
It looks like this:
I am able to load a specific line of the file that contains a specific string using this in the app:
How would I be able to update the file/main textbox after I press the "Edit Module" button, if any of the textboxes would be changed .
For example, I would change Exam Weighting: "0.4" to Exam Weighting: "0.6", then press the "Edit Module" button which would edit the main textbox(file content). Which then would allow me to save the file with the updated content.
This is the code I am using to get a specific line from the file based on string from a textbox:
private void editModuleButton_Click(object sender, EventArgs e)
{
citation = editModuleComboBox.Text;
citationChange();
}
private void citationChange()
{
List<string> matchedList = new List<string>();
string[] linesArr = File.ReadAllLines(fileName);
//find matches
foreach (string s in linesArr)
{
if (s.Contains(citation))
{
matchedList.Add(s); //matched
}
}
//output
foreach (string s in matchedList)
{
string citationLine = s;
string[] lineData = citationLine.Split(',');
selectedModuleLabel.Text = lineData[2];
moduleTitleTextBox.Text = lineData[3];
creditsTextBox.Text = lineData[4];
semesterTextBox.Text = lineData[5];
examWeightingTextBox.Text = lineData[6];
examMarkTextBox.Text = lineData[7];
testWeightingTextBox.Text = lineData[8];
testMarkTextBox.Text = lineData[9];
courseworkWeightingTextBox.Text = lineData[10];
courseworkMarkTexbox.Text = lineData[11];
}
}
If somebody with enough rep could insert the images to this post, that would be great. Thanks
This solution might not be the perfect, but should work for you. What you need to do is whenever the Edit Module button is pressed, create a new string based on the text fields and replace it with the original line. First declare a string variable private string ChangedString = ""; inside the class, then:
foreach (string s in matchedList)
{
string citationLine = s;
string[] lineData = citationLine.Split(',');
string Stream = lineData[0]; //Store this somewhere so that it can be accessed later
string Stage = lineData[1]; //Store this somewhere so that it can be accessed later
selectedModuleLabel.Text = lineData[2];
moduleTitleTextBox.Text = lineData[3];
creditsTextBox.Text = lineData[4];
semesterTextBox.Text = lineData[5];
examWeightingTextBox.Text = lineData[6];
examMarkTextBox.Text = lineData[7];
testWeightingTextBox.Text = lineData[8];
testMarkTextBox.Text = lineData[9];
courseworkWeightingTextBox.Text = lineData[10];
courseworkMarkTexbox.Text = lineData[11];
}
store Stream and Stage in any Textbox/ComboBox if you already haven't then replace them accordingly in the following line. Now in EditButton_Click [Click Event] write:
ChangedString = Stream + "," + Stage + "," + selectedModuleLabel.Text + "," + moduleTitleTextBox.Text
+ "," + creditsTextBox.Text + "," + semesterTextBox.Text + "," + examWeightingTextBox.Text + ","
+ examMarkTextBox.Text + "," + courseworkWeightingTextBox.Text + "," + courseworkMarkTexbox.Text;
Now replace this string with the original line.
Edit: As you would get the line number which is being edited, store it in a variable, let's say
int LineBeingEdited = 3 //Supposing line number three is being edited.
Then again in the same Click event you can write this:
ChangedString = Stream + "," + Stage + "," + selectedModuleLabel.Text + "," + moduleTitleTextBox.Text
+ "," + creditsTextBox.Text + "," + semesterTextBox.Text + "," + examWeightingTextBox.Text + ","
+ examMarkTextBox.Text + "," + courseworkWeightingTextBox.Text + "," + courseworkMarkTexbox.Text;
var lines = TextBox1.Lines;
lines[LineBeingEdited] = ChangedString;
TextBox1.Lines = lines;
EDIT 2: To get the line number I would suggest you to modify your for each loop to for loop. Also add a int variable to store the line number inside the class like : private int LineBeingEdited = 0;
Modify this for each :
foreach (string s in linesArr)
{
if (s.Contains(citation))
{
matchedList.Add(s); //matched
}
}
To for loop:
for (int a = 0; a < linesArr.Length; a++)
{
if (s.Contains(citation))
{
matchedList.Add(linesArr[a]); //matched
LineBeingEdited = a;
break; //breaks the loop when a match is found
}
}
The above method is being used, taking into consideration that there will always be a single match. LineBeingEdited will now have the line number and can be accessed from anywhere in the class
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
I have the following function which truncates a SQL Server varchar column and adds it to a string:
public void Pp()
{
strSql = #""; //query
using (SqlConnection conn = new SqlConnection(gstr))
{
try
{
SqlDataAdapter da = new SqlDataAdapter(strSql, conn);
myDataSet = new DataSet();
da.Fill(myDataSet);
string specific = "";
string generic = "";
string strTemp = "";
foreach (DataRow r in myDataSet.Tables[0].Rows)
{
if (r["MessageText"].ToString().Length <= 65)
{
strTemp = r["MessageText"].ToString();
}
else
{
strTemp = TruncateLongString(r["MessageText"].ToString(), 65);
}
specific += "</b><span class='hoverText' title='" + r["MessageText"] + "'>" + strTemp + "...</span>";
strTemp = "";
}
lblMessage.Text = "<b>SPECIFIC MESSAGES:</b> <br />" + specific;
}
catch (Exception ce)
{
}
}
}
public string TruncateLongString(string str, int maxLength)
{
return str.Substring(0, maxLength);
}
If the r["MessageText"] contains an appostrophe, it cuts off anything after it. (full text: no way no way HERE we go again but this is not working. Is it? or Is it not? I can't be too sure though. Can someone please check.)
Here is an example of a live preview (the title is shown but gets cut off because of the apostrophe):
Here is the source (the apostrophe is shown in the purple box. Also the color coding gets out of whack due to the apostrophe, which means the code is not correct):
How can I ensure it doesn't escape any escape characters, e.g. ', /, \.
You need to encode the HTML first.
Call this.Server.HtmlEncode( str ). This will also protect against other special characters like & and <.
That said, you're using single-quotes for attribute delimiters but HtmlEncode only encodes double-quotes, so you need to change your code to this:
specific = String.Format( CultureInfo.InvariantCulture, #"</b><span class=""hoverText"" title=""" + this.Server.HtmlEncode( r["MessageText"] ) + """>" + strTemp + #"...</span>";
.Replace(" ' ", "\\' "); You will probably want to do the same with double quote as well.
i have issue when using array and pass in to string = 0 .. its keep getting 0 although the excel sheet data got value. Kindly advice.
Below is the code sheetnameList = 0
string[] sheetnameList = GetExcelSheetName(#"" +
var_SourceFilePath + "MBF_Cancel_Temp.xlsx" + "");
foreach (string sheetName in sheetnameList)
{
if (sheetName.Contains("$"))
{
InsertLogFile("AMB SP15 Cancellation: Processing SheetName " + sheetName);
DeleteTable();
DataTable sheetTable = loadSingleSheet(#"" + var_SourceFilePath +
"MBF_Cancel_Temp.xlsx" + "", sheetName);
InsertDBMaster();
}
}
On a hunch, try this:
string[] sheetnameList = GetExcelSheetName(var_SourceFilePath + #"\\" + "MBF_Cancel_Temp.xlsx");
or even better:
var path = Path.Combine(var_SourceFilePath, "MBF_Cancel_Temp.xlsx");
var sheetnameList = GetExcelSheetName(path);