Multiline textbox entries not seperated - c#

why other strings other than -ABC12 are not separated?
enter code here
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace multiline_textbox_seperation
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
String[] lines = textBox2.Text.Split(',');
List<string> List = new List<string>();
List.AddRange(lines);
for (int i = 0; i < List.Count; i++)
{
textBox1.Text += List[i] + "\r\n";
}
List<String> PossitiveList = new List<String> { };
List<String> NegativeList = new List<String> { };
for (int i = 0; i < List.Count; i++)
{
if (List[i].StartsWith("-")) { NegativeList.Add(List[i]); }
if (List[i].StartsWith("+")) { PossitiveList.Add(List[i]); }
}
listBox1.DataSource = NegativeList;
listBox2.DataSource = PossitiveList;
}
}
}
the result for the string:
string input = "-ABC12, +ABC12, -BAC12, -ACC12, +EAC12, -BBC12, -CBC12, +GABC12, +ACC12, +CBC12, +BBC12"
typed in textbox2 is:

If you look closely, you have spaces in between.
Instead of doing: List[i].StartsWith("-") or List[i].StartsWith("+"), do a:
List[i].Trim().StartsWith("-")
List[i].Trim().StartsWith("+")

I'd simplify a bit with:
private void button1_Click(object sender, EventArgs e)
{
var values = new List<string>(textBox2.Text.Split(','))
.Select(x => x.Trim()).ToList();
textBox1.Lines = values.ToArray(); // optional
var PositiveList = values.Where(x => x.StartsWith("+")).ToList();
var NegativeList = values.Where(x => x.StartsWith("-")).ToList();
listBox1.DataSource = NegativeList;
listBox2.DataSource = PositiveList;
}

Related

C# - amend values from column1 in DaraGridView and put them in new column

I have a section of code which splits an input string into rows and outputs it into a DataGridView.
These are all populated into column 1.
I want to further split the values in column 1 into column 2 and 3 etc.
The values for column 2 and 3 need to come from column 1 NOT THE ORIGINAL INPUT.
For example:
EDIT: More example inputs
Input String :
abc12, def, 56, jkl78, mno90
Current Code:
private void Button1_Click(object sender, EventArgs e)
{
List<string> eSplit = new List<string>(eInputBox.Text.Split(new string[] { "," }, StringSplitOptions.None));
DataGridViewTextBoxColumn eOutputGrid = new DataGridViewTextBoxColumn();
eOutputGrid.HeaderText = "Section";
eOutputGrid.Name = "Section";
eOutputDGV.Columns.Add(eOutputGrid);
foreach (string item in eSplit)
{
eOutputDGV.Rows.Add(item);
}
}
Desired Output: (if there is no value then it needs to be blank).
Section Letters Numbers
abc12 abc 12
def def
56 56
jkl78 jkl 78
mno90 mno 90
You have to add each column definition to your eOutputDGV and then to pass three parameters to each eOutputDGV.Row:
private void Button1_Click(object sender, EventArgs e)
{
List<string> eSplit = new List<string>(eInputBox.Text.Split(new string[] { "," }, StringSplitOptions.None));
DataGridViewTextBoxColumn eOutputGrid = new DataGridViewTextBoxColumn();
eOutputGrid.HeaderText = "Section";
eOutputGrid.Name = "Section";
eOutputDGV.Columns.Add(eOutputGrid);
eOutputGrid = new DataGridViewTextBoxColumn();
eOutputGrid.HeaderText = "Letters";
eOutputGrid.Name = "Letters";
eOutputDGV.Columns.Add(eOutputGrid);
eOutputGrid = new DataGridViewTextBoxColumn();
eOutputGrid.HeaderText = "Numbers";
eOutputGrid.Name = "Numbers";
eOutputDGV.Columns.Add(eOutputGrid);
foreach (string item in eSplit)
{
eOutputDGV.Rows.Add(item.Trim(), item.Trim().Substring(0, 3), item.Trim().Substring(3));
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace dgvAlphaNumbericSplit
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
dataGridView1.Rows.Clear();
dataGridView1.Rows.Add("abc12", "", "");
dataGridView1.Rows.Add("def", "", "");
dataGridView1.Rows.Add("56", "", "");
dataGridView1.Rows.Add("jkl78", "", "");
dataGridView1.Rows.Add("mno90", "", "");
}
private void Button1_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if(dataGridView1.Rows[row.Index].Cells[0].Value != null)
{
string str = dataGridView1.Rows[row.Index].Cells[0].Value.ToString();
int index = str.IndexOfAny(new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' });
string chars = "";
string nums = "";
if (index >= 0)
{
chars = str.Substring(0, index);
nums = str.Substring(index);
}
else
{
chars = str;
}
dataGridView1.Rows[row.Index].Cells[1].Value = chars;
dataGridView1.Rows[row.Index].Cells[2].Value = nums;
}
}
}
}
}
Here are the results: -
Assuming you have a list of string, you can shape it into the expected result using a linq query:
dataGridView1.DataSource = list.Select(x=>Process(x)).ToList();
And what is the Process method? It's a static method which is responsible to process the input string and convert it to the desired model, let's say you have a model like this:
public class MyModel
{
public string Letters { get; set; }
public int Numbers { get; set; }
public string Section
{
get
{
return $"{Letters}{Numbers}";
}
}
}
Then the process method is something like this:
pubic static MyModel Process(string s)
{
// some logic to extract information form `s`
return new MyModel(){ Letters = ..., Numbers = ... };
}

How do make the code display the information?

I'm trying to debug the C# code but can't find the logic error of why it's not displaying the data and no error message.
To begin with, the code was in large chunks so I then tried splitting the code into smaller methods but still unable to find the issue of where I'm going wrong.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace Drivers_license_exam
{
public partial class Form1 : Form
{
private string[] studentAnsArray = new string[20];
private string[] correctAnsArray = { "B", "D", "A", "A", "C", "A","B", "A", "C", "D", "B","C",
"D", "A", "D", "C","C", "B", "D", "A" };
public Form1()
{
InitializeComponent();
}
private void GetFile(out string fileName)
{
if (openFile.ShowDialog() == DialogResult.OK)
{
fileName = openFile.FileName;
}
else
{
fileName = "";
}
}
private void GetAndReadFile(string fileName)
{
string results;
StreamReader inputFile = File.OpenText(fileName);
while (!inputFile.EndOfStream)
{
results = inputFile.ReadLine();
studentAns.Items.Add(results);
//studentAnsArray[index] = inputFile.ReadLine();
//correctAns.Items.Add(studentAnsArray);
}
foreach (string answers in correctAnsArray)
{
correctAns.Items.Add(answers);
}
inputFile.Close();
}
private int TotCorrect()
{
int correct = 0;
for (int index = 0; index < correctAnsArray.Length; index++)
{
if (studentAnsArray[index]== correctAnsArray[index])
{
correctTxt.Text = index.ToString();
correct++;
}
}
return correct;
}
private int TotIncorrect()
{
int incorrect = 0, questNum = 1;
for (int index = 0; index < correctAnsArray.Length; index++)
{
if (studentAnsArray[index] == correctAnsArray[index])
{
incorrectAns.Items.Add("Question: " + questNum);
incorrectAns.Items.Add("Incorrect");
incorrect++;
}
}
return incorrect;
}
private bool PassedTest()
{
bool pass = false;
if (TotCorrect() >= 15)
{
passFailedTxt.Text = "Passed";
}
if (TotIncorrect() < 15)
{
passFailedTxt.Text = "Failed";
}
return pass;
}
private void displayRes_Click(object sender, EventArgs e)
{
string studentAns;
GetFile(out studentAns);
GetAndReadFile(studentAns);
TotCorrect();
TotIncorrect();
PassedTest();
}
private void exit_Click(object sender, EventArgs e)
{
this.Close();
}
private void Clear_Click(object sender, EventArgs e)
{
}
}
}
What I expected the code to do is output the following:
display the incorrect results
display pass or fail in a text box
display the total of correct and incorrect answers in a text box
The output that I'm getting from this code is:
- doesn't display the incorrect answers in the list box
- displays fail although the answers from the text and the array are correct
- doesn't display the total of correct and incorrect answers

Altering string array value with radio button

I'm having an issue with altering the value of a string array based on what radio button is selected, it's written in C# using Visual Studio 2013 professional.
Basically all that needs to happen is if the radio button called "smallCarRadBtn" is selected, then the string array call "carSize" has to hold the word "Small", and likewise for the other two radio buttons "medCarRadBtn" and "largeCarRadBtn".
At the moment it is telling me:
"Cannot implicitly convert type 'char' to 'string[]'
I have 'highlighted' the area that contains the code for this with asterisks'*'. Any help would be appreciated.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace Assignment2
{
public partial class Form1 : Form
{
TimeSpan daysHiredIn;
DateTime startDate, endDate;
DateTime dateToday = DateTime.Today;
public static string[] names = new string[50];
public static string[] carSize = new string[50];
public static int[] cardNumb = new int[50];
public static int[] cost = new int[50];
public static TimeSpan[] daysHired = new TimeSpan[50];
public static int entryCount = 0, cardNumbIn, carFee = 45, intDaysHired;
public Form1()
{
InitializeComponent();
smallCarRadBtn.Checked = true;
}
private void confirmBtn_Click(object sender, EventArgs e)
{
if (entryCount >= 50)
{
MessageBox.Show("Arrays are Full");//if array is full
}
else if (nameTxtBox.Text == "")
{
MessageBox.Show("You must enter a name");//Nothing entered
}
else if (!int.TryParse(cardNumbTxtBox.Text, out cardNumbIn))
{
MessageBox.Show("You must enter an integer number");
cardNumbTxtBox.SelectAll();
cardNumbTxtBox.Focus();
return;
}
else if (hireStartDatePicker.Value < dateToday)
{
MessageBox.Show("You cannot enter a date earlier than today");
}
else if (hireEndDatePicker.Value < dateToday)
{
MessageBox.Show("You cannot enter a date earlier than today");
}
else
{
*******************************************************************************************
if (smallCarRadBtn.Checked)
{
carSize = ("small"[entryCount]);
}
else if (MedCarRadBtn.Checked)
{
carSize = ("Medium"[entryCount]);
}
else if (largeCarRadBtn.Checked)
{
carSize = ("Large"[entryCount]);
}
*******************************************************************************************
names[entryCount] = nameTxtBox.Text;
cardNumb[entryCount] = cardNumbIn;
endDate = (hireEndDatePicker.Value);
startDate = (hireStartDatePicker.Value);
daysHiredIn = (endDate - startDate);
cost[entryCount] = (carFee * daysHiredIn);
daysHired[entryCount] = daysHiredIn;
entryCount++;
nameTxtBox.SelectAll();
nameTxtBox.Focus();
}
}
private void viewBtn_Click(object sender, EventArgs e)
{
for (entryCount = 0; entryCount < 50; entryCount++)
{
listBox1.Items.Add(names[entryCount]+"\t"+daysHired[entryCount].Days.ToString());
}
}
}
}
carSize is an array of strings but you are trying to assign it a char:
carSize = ("small"[entryCount]);
Here the "small" is a string, and "small"[entryCount] returns the character at the index entryCount
You should change carSize to char[] if you want to stores characters, and set the elements using indexer instead of assigning the array directly. Or if you want to store the text + entryCount then you should concatenate strings:
carSize[index] = "small" + entryCount;
Or if you just want to set carSize[entryCount] then:
carSize[entryCount] = "small";

scrollbar initializes DragMove() in WPF

i built a weather app that gets the weather for major cities in the world. i used wsdl to download the weather data in xml and then i get the desired data from the elements by using XmlDocument class. i display this information in a textbox. i set the HorizontalScrollBarVisibility & VerticalScrollBarVisibility of the textbox to auto so it displays a scrollbar should the text be too long. i have also implemented a _MouseLeftButtonDown listener because i have removed the title bar from my app. however everytime the scrollbar is displayed and i click it, the DragMove() method is called and thus i cannot scroll through the text.
how can i prevent this from happening?
here's my code, it only works with the GlobalWeather and Countries classes i converted from wsdl. if you want i can post the code or you can download the wsdl of these classes and convert it to .cs...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;
namespace WeatherApp
{
/// <summary>
/// Interaktionslogik für Window1.xaml
/// </summary>
public partial class Window1 : Window
{
// http://www.webservicex.net/globalweather.asmx?WSDL
private static GlobalWeather wetterObjekt;
//http://www.webservicex.net/ws/WSDetails.aspx?WSID=17&CATID=7
Country country;
private static string wetter;
private static string wetterAktuell;
private static List<string> countryList;
private static List<string> cityList;
public Window1 ()
{
InitializeComponent ();
wetterAktuell = "";
wetter = "";
wetterObjekt = new GlobalWeather ();
country = new Country ();
countryList = new List<string> ();
cityList = new List<string> ();
getCountries ();
string firstStr = "(keins ausgewählt)";
object firstItem = firstStr;
txtStadt.Items.Add(firstItem);
txtStadt.SelectedIndex = 0;
txtLand.SelectedIndex = 0;
txtWetter.IsEnabled = false;
txtLand.SelectionChanged += new SelectionChangedEventHandler ( txtLand_SelectionChanged );
}
private void txtLand_SelectionChanged ( object sender, SelectionChangedEventArgs e )
{
Console.WriteLine(cityList.Count);
if (cityList.Count > 0)
{
txtStadt.Items.Clear();
cityList.Clear();
string firstStr = "(keins ausgewählt)";
object firstItem = firstStr;
txtStadt.Items.Add(firstItem);
txtStadt.SelectedIndex = 0;
}
if ((string)(txtLand.SelectedValue) == "(keins ausgewählt)")
{
return;
}
else
{
string land = "";
land = txtLand.SelectedValue.ToString();
getStadt(land);
//Console.WriteLine(wetterObjekt.GetCitiesByCountry(land));
//Console.WriteLine(land);
}
}
private void getStadt (string land)
{
XmlDocument document = new XmlDocument();
document.LoadXml(wetterObjekt.GetCitiesByCountry(land));
XmlNodeList nl = document.GetElementsByTagName("NewDataSet");
for (int x = 0; x < nl[0].ChildNodes.Count; x++)
{
for (int y = 1; y < nl[0].ChildNodes[x].ChildNodes.Count; y += 2)
{
cityList.Add(nl[0].ChildNodes[x].ChildNodes[y].InnerText);
}
}
cityList.Sort();
for (int x = 0; x < cityList.Count; x++)
{
txtStadt.Items.Add(cityList[x]);
}
}
private void getCountries()
{
string countries = country.GetCountries ();
XmlDocument document = new XmlDocument ();
document.LoadXml ( countries );
XmlNodeList nl = document.GetElementsByTagName ( "NewDataSet" );
string firstStr = "(keins ausgewählt)";
object firstItem = firstStr;
txtLand.Items.Add(firstItem);
for ( int x = 0; x < nl [0].ChildNodes.Count; x++ )
{
for ( int y = 0; y < nl [0].ChildNodes [x].ChildNodes.Count; y++ )
{
countryList.Add ( nl [0].ChildNodes [x].ChildNodes [y].InnerText );
}
}
for ( int i = 0; i < countryList.Count; i++ )
{
txtLand.Items.Add ( countryList [i] );
}
}
private void getWeather ( string stadt, string land )
{
try
{
wetter = wetterObjekt.GetWeather(stadt, land);
xmlParsen(wetter);
txtWetter.Text = wetterAktuell;
}
catch (System.Xml.XmlException e)
{
clearWetterTextBox();
txtWetter.Text = "Keine Wetterdaten gefunden!";
//Console.WriteLine("Keine Wetterdaten gefunden!");
}
}
private void btnSchliessen_Click ( object sender, RoutedEventArgs e )
{
this.Close ();
}
private void xmlParsen (string wetter)
{
XmlDocument document = new XmlDocument ();
try
{
document.LoadXml(wetter);
XmlNodeList nl = document.GetElementsByTagName("CurrentWeather");
for (int i = 0; i < nl[0].ChildNodes.Count; i++)
{
wetterAktuell = wetterAktuell + (nl[0].ChildNodes[i].Name + ": " + nl[0].ChildNodes[i].InnerText) + "\n";
}
}
catch (System.Xml.XmlException e)
{
throw new System.Xml.XmlException();
}
}
private void btnGetWetter_Click ( object sender, RoutedEventArgs e )
{
clearWetterTextBox ();
getWeather (txtStadt.Text, txtLand.Text);
}
private void clearWetterTextBox ()
{
wetterAktuell = "";
this.txtWetter.Clear ();
}
private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
DragMove();
}
}
}

How do i loop through two Lists to compare items in both Lists?

I have this code:
private void removeDuplicates(List<string> currentSites, List<string> visitedSites)
{
for (int i = 0; i < currentSites.Count; i++)
{
for (int x = 0; x < visitedSites.Count; x++)
{
}
}
}
Im getting two Lists and i need first to compare each item in one List to the items in the other List to loop over all the items in the other List and compare. If one of the items exist in the other List mark it as NULL.
I need to check that visitedSites are in the currentSites to take one item move over all the Lists to check if exit if it is to mark as null.
In any case i need to use two loop's one ine the other one.
When i find its null to mark it null and after it make break;
Then i need to add another loop FOR to move over the List currentSites if im not wrong and remove all the marked NULL items.
The idea is to compare the Lists by mark the duplicated items as null then to remove all the null's.
This is the code from the beginning:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HtmlAgilityPack;
using System.IO;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using System.Net;
using System.Web;
namespace GatherLinks
{
public partial class Form1 : Form
{
List<string> currentCrawlingSite;
List<string> sitesToCrawl;
int actual_sites;
BackgroundWorker worker;
int sites = 0;
int y = 0;
string guys = "http://www.google.com";
public Form1()
{
InitializeComponent();
currentCrawlingSite = new List<string>();
sitesToCrawl = new List<string>();
actual_sites = 0;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private List<string> getLinks(HtmlAgilityPack.HtmlDocument document)
{
List<string> mainLinks = new List<string>();
var linkNodes = document.DocumentNode.SelectNodes("//a[#href]");
if (linkNodes != null)
{
foreach (HtmlNode link in linkNodes)
{
var href = link.Attributes["href"].Value;
mainLinks.Add(href);
}
}
return mainLinks;
}
private List<string> webCrawler(string url, int levels , DoWorkEventArgs eve)
{
HtmlAgilityPack.HtmlDocument doc;
HtmlWeb hw = new HtmlWeb();
List<string> webSites;// = new List<string>();
List<string> csFiles = new List<string>();
csFiles.Add("temp string to know that something is happening in level = " + levels.ToString());
csFiles.Add("current site name in this level is : " + url);
try
{
doc = hw.Load(url);
currentCrawlingSite.Add(url);
webSites = getLinks(doc);
removeDuplicates(currentCrawlingSite, webSites);
removeDuplicates(currentCrawlingSite, sitesToCrawl);
sitesToCrawl = webSites;
if (levels == 0)
{
return csFiles;
}
else
{
for (int i = 0; i < webSites.Count() && i < 20; i++) {
int mx = Math.Min(webSites.Count(), 20);
if ((worker.CancellationPending == true))
{
eve.Cancel = true;
break;
}
else
{
string t = webSites[i];
if ((t.StartsWith("http://") == true) || (t.StartsWith("https://") == true))
{
actual_sites++;
csFiles.AddRange(webCrawler(t, levels - 1,eve));
this.Invoke(new MethodInvoker(delegate { Texts(richTextBox1, "Level Number " + levels + " " + t + Environment.NewLine, Color.Red); }));
worker.ReportProgress(Math.Min((int)((double)i / mx * 100),100));
}
}
}
return csFiles;
}
}
catch
{
return csFiles;
}
}
So im calling the removeDuplicated function twice need to do in the removeDuplicated the things i wrote above then im not sure if to do sitesToCrawl = webSites; or ot add somehow the links in webSites to the sitesToCrawl. The idea is when i loop over the webSites that there will be no duplicated items when adding to the csFiles List.
Not sure if I understand your problem:
IEnumerable<string> notVisitedSites = currentSites.Except(visitedSites);

Categories