My code searches through a list and then if it finds a match, it displays the object in my listbox. My problem is that if there is more than 1 object in the list (if im searching for Alex and there is two objects with the name Alex), it returns it all on the same line instead of separating them to separate lines.
I coulda swore match += request + "\n"; was how to do it correctly, but it's not working.
Edit: One thing I dont understand is that if i just have match += request; it will allow me to use the horizontal scroll bar on my listbox to see everything written. And if i use match += request + "\n"; or match += request + Environment.NewLine; it doesn't let me use the scroll box and just cuts off.
public string SearchRequest(string keyword)
{
bool found = false;
string noMatch = "No requests with the name " + "'" + keyword + "'" + " were found";
string match = "";
foreach (ServiceRequest request in Requests)
{
if (request.searchKeywords(keyword))
{
match += request + "\n";
found = true;
}
}
if (found)
return match;
else
return noMatch;
}
/
public bool searchKeywords(string keyword)
{
if (keyword == name)
return true;
else
return false;
}
/
private void btnSearch_Click(object sender, EventArgs e)
{
lstSearch.Items.Clear();
lstSearch.Items.Add(myRequest.SearchRequest(txtSearch.Text));
}
Try
match += request + Environment.NewLine;
If you put all the results in a single string then it will still be a single item in the list.
Return an array of strings from the method instead of a single string:
public string[] SearchRequest(string keyword) {
List<string> match = new List<string>();
foreach (ServiceRequest request in Requests) {
if (request.searchKeywords(keyword)) {
match.Add(request.ToString());
}
}
if (match.Count > 0) {
return match.ToArray();
} else {
return new string[] { "No requests with the name " + "'" + keyword + "'" + " were found" };
}
}
Then use AddRange to add the strings as separate items in the list:
lstSearch.Items.AddRange(myRequest.SearchRequest(txtSearch.Text));
In Windows OS, the new line is two characters, the Carriage Return \r followed by Line Feed: \n. You can use Environment.NewLine as a shortcut (preferred) or append "\r\n" yourself. See further wikipedia entry on newline
Use one of these:
match += request + "\r\n";
Use an string literal:
match += request + #"
";
OR only at runtime will this resolve:
match += request + System.Environment.NewLine;
On Unix "\n"
You can't add a string with newlines to a listbox and expect it to show up as multiple items. Either split the string on newline and add each line separately to the listbox, or return a list of strings from your search function to begin with, avoiding the need for a split afterwards.
Related
I'm trying to write some code for unity in c#. I am having a problem wring \n into a List. Heres my code.
public static List<string> ChatHeads = null;
public void Start()
{
ChatHeads = new List<string>();
}
void Update()
{
ChatBoxMessage.text = GetChatHead();
}
string GetChatHead()
{
return string.Join(System.Environment.NewLine, ChatHeads.ToArray());
}
public void MainFunc()
{
string FinalMessage = "";
if (FinalMessage.Length >= 82 || !.inWorld)
{
FinalMessage = Message + "\n";
ChatHeads.Add(FinalMessage);
}
else
{
FinalMessage = "[" + username + "] " + MainWorld.ChatTag + Message + "\n";
ChatHeads.Add(FinalMessage);
}
}
The issue is GetChatHead() only returns the first array string if \n isnt the last part of the string. code works fine as long as the \n appears but it NEVER does always disappears.
thanks.
Pic to List array, No \n at end of any lines.
[2
Solved. Apparently Encoding.Default.GetString() wont allow you to add anything to the string.
Message = Encoding.Default.GetString(packet.ReadBytes((int)Length));
No Good
Message = packet.ReadString();
Worked.
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
Struggling with a C# Component. What I am trying to do is take a column that is ntext in my input source which is delimited with pipes, and then write the array to a text file. When I run my component my output looks like this:
DealerID,StockNumber,Option
161552,P1427,Microsoft.SqlServer.Dts.Pipeline.BlobColumn
Ive been working with the GetBlobData method and im struggling with it. Any help with be greatly appreciated! Here is the full script:
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
string vehicleoptionsdelimited = Row.Options.ToString();
//string OptionBlob = Row.Options.GetBlobData(int ;
//string vehicleoptionsdelimited = System.Text.Encoding.GetEncoding(Row.Options.ColumnInfo.CodePage).GetChars(OptionBlob);
string[] option = vehicleoptionsdelimited.Split('|');
string path = #"C:\Users\User\Desktop\Local_DS_CSVs\";
string[] headerline =
{
"DealerID" + "," + "StockNumber" + "," + "Option"
};
System.IO.File.WriteAllLines(path + "OptionInput.txt", headerline);
using (System.IO.StreamWriter file = new System.IO.StreamWriter(path + "OptionInput.txt", true))
{
foreach (string s in option)
{
file.WriteLine(Row.DealerID.ToString() + "," + Row.StockNumber.ToString() + "," + s);
}
}
Try using
BlobToString(Row.Options)
using this function:
private string BlobToString(BlobColumn blob)
{
string result = "";
try
{
if (blob != null)
{
result = System.Text.Encoding.Unicode.GetString(blob.GetBlobData(0, Convert.ToInt32(blob.Length)));
}
}
catch (Exception ex)
{
result = ex.Message;
}
return result;
}
Adapted from:
http://mscrmtech.com/201001257/converting-microsoftsqlserverdtspipelineblobcolumn-to-string-in-ssis-using-c
Another very easy solution to this problem, because it is a total PITA, is to route the error output to a derived column component and cast your blob data to a to a STR or WSTR as a new column.
Route the output of that to your script component and the data will come in as an additional column on the pipeline ready for you to parse.
This will probably only work if your data is less than 8000 characters long.
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 fairly new to c# and am working on a little project but got stuck on this. I have a file that contains some assembly code. I want my program to search this file for a string, actually a value right after my string. One of the strings i am searching for is:
setproperty QName(PackageNamespace(""), "font")
getlocal 4
pushint
My search code is this:
private void searchFile(String searchText)
{
System.IO.StreamReader reader = new System.IO.StreamReader(file);
String text = reader.ReadToEnd();
if (Regex.IsMatch(text, searchText))
{
MessageBox.Show(searchText + " was found in the given file", "Finally!!");
}
else
{
MessageBox.Show("Sorry, but " + searchText + " could not be found in the given file", "No Results");
}
}
//when i click a button//
searchFile(#"setproperty QName(PackageNamespace(""""), ""font"")
getlocal 4
pushint ");
I know that the string is in the file but the result comes up with not found. I don't know if it is the quotes or tabs or both that is causing this.
Here is part of the file:
getlocal 4
pushstring "Verdana"
setproperty QName(PackageNamespace(""), "font")
getlocal 4
pushint 16764170
setproperty QName(PackageNamespace(""), "color")
getlocal 4
pushbyte 12
setproperty QName(PackageNamespace(""), "size")
My second question is how can i get the value of the first int after my search result?
Thanks in advance.
-Leen
You should change your method like this:
private static string searchFile(String searchText)
{
System.IO.StreamReader reader = new System.IO.StreamReader("test.txt");
String text = reader.ReadToEnd();
int poz = text.IndexOf(searchText);
if (poz >= 0)
{
int start = poz + searchText.Length;
int end = text.IndexOf("\n", start);
Console.WriteLine(searchText + " was found in the given file", "Finally!!");
return text.Substring(start, end - start);
}
else
{
Console.WriteLine("Sorry, but " + searchText + " could not be found in the given file", "No Results");
return string.Empty;
}
}
The call:
string val = searchFile("setproperty QName(PackageNamespace(\"\"), \"font\")\r\n\r\n getlocal 4\r\n pushint ");
So I think you may be use to VB.net. C-based languages (like c#) used the backslash character "\" as an escape character.
So in a searching for a double-quote in a string you would need to escape it using \".
I believe what you're looking for is:
searchFile(#"setproperty QName(PackageNamespace(\"\"), \"font\")
getlocal 4
pushint ");
But this isn't really a regular expression, which is what the Regex class is meant for. So I would (well not really, I would clean it up a bit, like not mix my UI and bizlogic) do this:
// Added String as the function type so you can return the matched "Integer" as a string, you could always do a Int32.TryParse(...)
private String searchFile(String file, String searchText)
{
System.IO.StreamReader reader = new System.IO.StreamReader(file);
String text = reader.ReadToEnd();
int32 index = text.IndexOf(searchText);
if (index >= 0) //We could find it at the very beginning
{
MessageBox.Show(searchText + " was found in the given file", "Finally!!");
int32 start = index + searchText.Length;
int32 end = Regex.Match(text, "[\n\r\t]", index).Index; // This will search for whitespace
String value = text.Substring(start, end - start);
// Now you can do something with your value, like...
return value;
}
else
{
MessageBox.Show("Sorry, but " + searchText + " could not be found in the given file", "No Results");
return "";
}
}