Chart not labeling entire X Axis (dynamic) - c#

I am trying to display points from 7 files. Each file corresponds to a day, and I am trying to add a button where it takes the last 7 created files and displays them as x=dateTime and y= value. what this code currently does is that only displays the x axis on the left and right side.
private void button1_Click(object sender, EventArgs e)
{
chart1.Titles.Clear();
chart1.Series.Clear();
xAxis.Clear();
yAxis.Clear();
var Series1 = new Series
{
Name = comboBox2.Text,
Color = System.Drawing.Color.Green,
IsVisibleInLegend = false,
IsXValueIndexed = true,
ChartType = SeriesChartType.Area
};
this.chart1.Series.Add(Series1);
double measur = 0;
//clear graph
string Folder = #"\\Engineer\DI-808\outlooktest\";
var files = new DirectoryInfo(Folder).GetFiles("*_*");
string latestfile = "";
DateTime lastModified = DateTime.MinValue;
List<string> filesD = new List<string>();
DateTime endDate=DateTime.Now;
DateTime startDate= DateTime.Now.AddDays(-3);
DateTime dateToCheck;
Console.WriteLine(startDate + " " + endDate);
foreach (FileInfo file in files)
{
//Console.WriteLine(file.Name+"before");
string edited = file.Name.Remove(0, 6);
//Console.WriteLine(edited+"during");
char[] csv = { '.', 'c', 's', 'v'};
edited = edited.TrimEnd(csv);
//Console.WriteLine(edited + "after CSV");
edited = edited.Remove(10, 9);
// Console.WriteLine(edited+"after");
dateToCheck = Convert.ToDateTime(edited);
Console.WriteLine(dateToCheck+" date to check");
Console.WriteLine(startDate+" start");
Console.WriteLine(endDate+ " end" );
// if ( DateTime.Compare(dateToCheck,startDate)>=0dateToCheck >= startDate && dateToCheck <= endDate);
if (DateTime.Compare(dateToCheck, startDate)>=0 && DateTime.Compare(dateToCheck, endDate)<=0)
{
latestfile = file.Name;
filesD.Add(latestfile);
Console.WriteLine(latestfile+" dweeb");
}
}
Console.WriteLine(filesD.Count());
for (int i = 0; i < filesD.Count(); i++)
Console.WriteLine(files[i]);
string lineData;
try
{
for (int i=0;i<filesD.Count();i++) {
readData = new StreamReader(#"\\egvfps1.egv.mapes.local\Engineer\DI-808\outlooktest\" + filesD[i]);
for (int k = 0; k < 21; k++)
readData.ReadLine();
while ((lineData = readData.ReadLine()) != null)
{
if (Convert.ToDouble(lineData.Split(',')[comboBox2.SelectedIndex + 2]) <= 0.001)
measur = 0;
else
{
measur = Convert.ToDouble(lineData.Split(',')[comboBox2.SelectedIndex + 2]) * 110;
xAxis.Add(Convert.ToDateTime(lineData.Split(',')[1]));
yAxis.Add(measur);
}
}
}
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
readData.Close();
this.chart1.ChartAreas[0].AxisX.LabelStyle.Format = "HH:mm:ss";
this.chart1.Titles.Add(comboBox2.Text + "(" + xAxis[0].ToString("MM/dd/yyyy") + ")");
chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Hours;
chart1.ChartAreas[0].AxisX.Interval = 1;
// chart1.ChartAreas[0].AxisX.MajorGrd.Enabled = false;
//chart1.ChartAreas[0].AxisY.MajorGrid.Enabled = false;
chart1.ChartAreas.FirstOrDefault().AxisX.Interval = 1;
// chart1.ChartAreas.FirstOrDefault().AxisY.Interval = 1;
for (int i = 0; i < xAxis.Count(); i++)
{
chart1.Series[comboBox2.Text].Points.AddXY(xAxis[i], yAxis[i]);
}
chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Hours;
chart1.ChartAreas[0].AxisX.Interval = 1;
// chart1.ChartAreas[0].AxisX.MajorGrd.Enabled = false;
//chart1.ChartAreas[0].AxisY.MajorGrid.Enabled = false;
chart1.ChartAreas.FirstOrDefault().AxisX.Interval = 1;
// chart1.ChartAreas.FirstOrDefault().AxisY.Interval = 1;
chart1.ChartAreas[0].AxisX.Interval = 1;
chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Hours;
chart1.ChartAreas[0].AxisX.IntervalOffset = 1;
chart1.Series[0].XValueType = ChartValueType.DateTime;
}
enter image description here
I know its somewhere in the Xaxis interval type part,but I don't know what values to put in.
Any suggestions helps!

Related

ASP.NET MVC : accesing object properties

I'm converting my code for specific models to a generic (all models will be accepted) version so I'm converting my label border but I can't access data in model because of I was accessing them like this:
worksheet.Cells["A" + index].Value = temp[i - 2].CarID.ToString();
but now I converted this access to something like this:
worksheet.Cells[L + index].Value = temp[i - 2].names[j].ToString();
but it's not working. I understand first one accesses object values but second one tries to access different one so how can I access this object values? I'm past full code for this function can you give me some idea about this situation? Thanks for help
public void EEPCreateExcelGeneric(ReportRange reportRange)
{
using (ExcelPackage excel = new ExcelPackage())
{
// var temp = db.Database.SqlQuery<CarsTrxViewModel>(SqlCars.CarsTrxByID()).ToList();
var temp = db.Cars.ToList();
Cars cars = new Cars();
// var properties = temp.GetType().GetProperties();
var names = new List<string>();
var properties = cars.GetType().GetProperties();
foreach (var item in properties)
{
var attribute = (DisplayNameAttribute)item.GetCustomAttribute(typeof(DisplayNameAttribute), true);
if (attribute != null)
{
names.Add(attribute.DisplayName);
}
else
{
names.Add(item.Name);
}
}
// System.Diagnostics.Debug.WriteLine(properties);
DateTime startdate = reportRange.StartDate;// ?? new DateTime(2000, 10, 10, 1, 1, 1, 1);
DateTime enddate = reportRange.EndDate;// ?? DateTime.Now;
DateTime now = DateTime.Now;
string date = now.ToShortDateString();
string time = now.ToLongTimeString();
date = date + "-" + time;
// modeli çekerken db de temizlersek çok daha hızlı olur
foreach (var item in temp.ToList())
{
if (item.CreateDate < startdate || item.CreateDate > enddate)
{
temp.Remove(item);
}
}
int RowRange = temp.Count();
string name = "Report_";
date = date.Replace(" ", "_");
date = date.Replace(",", "_");
date = date.Replace(":", "-");
date = date.Replace("/", "_");
string sonu = ".xls";
date += sonu;
name += date;
ExcelRecords m = new ExcelRecords();
m.IsExist = false;
m.CreateDate = now;
m.EndDate = enddate;
m.StartDate = startdate;
m.GuidName = name;
db.ExcelRecords.Add(m);
db.SaveChanges();
excel.Workbook.Worksheets.Add("Worksheet1");
var worksheet = excel.Workbook.Worksheets["worksheet1"];
//worksheet.Cells["A1"].Value = "CarID";
//worksheet.Cells["B1"].Value = "CarBrand";
//worksheet.Cells["C1"].Value = "CarModel";
//worksheet.Cells["D1"].Value = "CreateDate";
//worksheet.Cells["A1"].Style.Font.Bold = true;
//worksheet.Cells["B1"].Style.Font.Bold = true;
//worksheet.Cells["C1"].Style.Font.Bold = true;
//worksheet.Cells["D1"].Style.Font.Bold = true;
for (int i = 0; i < names.Count(); i++)
{
string L = (Convert.ToChar(65+i)).ToString();
L += "1";
System.Diagnostics.Debug.WriteLine(L);
worksheet.Cells[L].Value = names[i];
worksheet.Cells[L].Style.Font.Bold = true;
}
for (int i = 2; i < (RowRange + 2); i++)
{
/*
string L = (Convert.ToChar(63 + i)).ToString();
string index = i.ToString();
worksheet.Cells[L + index].Value = temp[i - 2].CarID.ToString();
worksheet.Cells[L + index].Value = temp[i - 2].CarBrand.ToString();
worksheet.Cells[L + index].Value = temp[i - 2].CarModel.ToString();
worksheet.Cells[L + index].Value = temp[i - 2].CreateDate.ToString();
*/
string index = i.ToString();
for (int j = 0; j < names.Count; j++)
{
string L = (Convert.ToChar(65 + j)).ToString();
worksheet.Cells[L + index].Value = temp[i - 2].names[j].ToString();//<=
// its not working what is right way for doing this
}
worksheet.Cells["A" + index].Value = temp[i - 2].CarID.ToString();
worksheet.Cells["B" + index].Value = temp[i - 2].CarBrand.ToString();
worksheet.Cells["C" + index].Value = temp[i - 2].CarModel.ToString();
worksheet.Cells["D" + index].Value = temp[i - 2].CreateDate.ToString();
}
worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
string path = Path.Combine(Server.MapPath("~/"), ("Reports\\" + name));
FileInfo excelFile = new FileInfo(path);
excel.SaveAs(excelFile);
var bull = db.ExcelRecords.SingleOrDefault(b => b.GuidName == name);
if (bull != null)
{
bull.IsExist = true;
db.SaveChanges();
}
}
}

Cosine similarity calculation issue

I am having issues in calculation of cosine similarity between 2 strings.
I calculate the binary vector format of each string using a function. It gives out binary vectors which are in the form of, say, (1,1,1,1,1,0,0,0,0).
public static Tuple<int[],int[]> sentence_to_vector(String[] word_array1, String[] word_array2)
{
String[] unique_word_array1 = word_array1.Distinct().ToArray();
String[] unique_word_array2 = word_array2.Distinct().ToArray();
String[] list_all_words = unique_word_array1.Concat(unique_word_array2).ToArray();
String[] list_all_words_unique = list_all_words.Distinct().ToArray();
int count_all_unique_words = list_all_words_unique.Length;
int[] sentence1_vector = new int[count_all_unique_words];
int[] sentence2_vector = new int[count_all_unique_words];
for (int i = 0; i < count_all_unique_words; i++)
{
if (Array.IndexOf(unique_word_array1, list_all_words_unique[i]) >= 0)
{
sentence1_vector[i] = 1;
}
else
{
sentence1_vector[i] = 0;
}
}
for (int i = 0; i < count_all_unique_words; i++)
{
if (Array.IndexOf(word_array2, list_all_words_unique[i]) >= 0)
{
sentence2_vector[i] = 1;
}
else
{
sentence2_vector[i] = 0;
}
}
return Tuple.Create(sentence1_vector, sentence2_vector);;
}
After I calculate the vector representation, I go for cosine similarity calculation.
The code is attached herewith:
public static float get_cosine_similarity(int[] sentence1_vector, int[] sentence2_vector)
{
int vector_length = sentence1_vector.Length;
int i = 0;
float numerator = 0, denominator = 0;
int temp1 = 0, temp2 = 0;
double square_root1 = 0, square_root2 = 0;
for (i = 0; i < vector_length; i++)
{
numerator += sentence1_vector[i] * sentence2_vector[i];
temp1 += sentence1_vector[i] * sentence1_vector[i];
temp2 += sentence2_vector[i] * sentence2_vector[i];
}
//TextWriter tw = new StreamWriter("E://testpdf/date2.txt");
square_root1 = Math.Sqrt(temp1);
square_root2 = Math.Sqrt(temp2);
denominator = (float)(square_root1 * square_root2);
if (denominator != 0){
return (float)(numerator / denominator);
//return (float)(numerator);
}
else{
return 0;
}
}
I checked out a site where in I can specify 2 strings and find the cosine similarity between them. The site is attached herewith:
http://cs.uef.fi/~zhao/Link/Similarity_strings.html
function implementationCosin(){
var string1 = document.DPAform.str1.value;
var s1 = stringBlankCheck(string1);
var string2 = document.DPAform.str2.value;
var s2 = stringBlankCheck(string2);
if (s1.length < 1) {
alert("Please input the string1.");
return;
}
if (s2.length < 1) {
alert("Please input the string2.");
return;
}
document.DPAform.displayArea2.value = "";
var sDT = new Date();
// var begin = new Date().getTime();
var cosin_similarity_value = consinSimilarity(s1, s2);
document.DPAform.displayArea2.value += 'Cosin_Similarity(' + s1 + ',' + s2 + ')=' + cosin_similarity_value + '%\n';
var eDT = new Date();
var timediff = sDT.dateDiff("ms", eDT);
// var timediff = (new Date().getTime() - begin);
document.DPAform.displayArea2.value += "The total escaped time is: " + timediff + " (ms).\n";
}
Even if 2 sentences are 0% similar, my codes says that there is some amount of similarity between them.

c# line chart. Why does my line go to 0 instead of just staying at the last point?

So i made a button and when you press it displays a graph of the arrays, but it goes to 0 when its finished.
private void button14_Click(object sender, EventArgs e)
{
for (int i = 0; i <= period; i++)
{
xos[i] = i+1;
yos[i] = pot[i];
listBox1.Items.Add(xos[i]);
listBox1.Items.Add("y " + yos[i]);
}
for (int i = 0; i <= period; i++)
{
x2os[i] = i + 1;
y2os[i] = pot2[i];
listBox2.Items.Add(x2os[i]);
listBox2.Items.Add("y "+y2os[i]);
}
chart1.ChartAreas[0].AxisX.Minimum = 0;
chart1.Series["Potražnja"].Points.DataBindXY(xos, yos);
chart1.Series["Predviđanje"].Points.DataBindXY(x2os,y2os);
}
Here is a photo of chart
Don't create the arrays before you know how long they need to be, just declare the references:
public double[] xos;
public double[] yos;
public double[] y2os;
public double[] x2os;
Then when you use them, create the actual arrays:
private void button14_Click(object sender, EventArgs e)
{
xos = new double[period + 1];
yos = new double[period + 1];
x2os = new double[period + 1];
y2os = new double[period + 1];
for (int i = 0; i <= period; i++)
{
xos[i] = i+1;
yos[i] = pot[i];
listBox1.Items.Add(xos[i]);
listBox1.Items.Add("y " + yos[i]);
}
for (int i = 0; i <= period; i++)
{
x2os[i] = i + 1;
y2os[i] = pot2[i];
listBox2.Items.Add(x2os[i]);
listBox2.Items.Add("y "+y2os[i]);
}
chart1.ChartAreas[0].AxisX.Minimum = 0;
chart1.Series["Potražnja"].Points.DataBindXY(xos, yos);
chart1.Series["Predviđanje"].Points.DataBindXY(x2os,y2os);
}
To make the yellow line skip the first zero values, you would need to check for those first, and then create the arrays:
var start = 0;
while (start <= period && pot2[start] == 0) {
start++;
}
x2os = new double[period - start + 1];
y2os = new double[period - start + 1];
for (int i = 0; i <= period - start; i++)
{
x2os[i] = start + i + 1;
y2os[i] = pot2[start + i];
listBox2.Items.Add(x2os[i]);
listBox2.Items.Add("y "+y2os[i]);
}

After changing tabpage, the combobox crashes

I have a combobox outside my tabcontrol. In each tab control there is a datagridview full of values. In the combobox you can choose a conversion for all values. For example eV→meV.
When i am in the first tab and use the combobox there are no problems, but after i switch the tab and then wanna use the combobox the program list down however the whole combobox is full of try/catch
private void OpenB_Click(object sender, EventArgs e)
{
string[] result = new string[2];
bool lesen = false;
int Spalte = 0;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
//Datagridview will be rested, so all values and rows are removed
for (int i = 1; i < Anzahl; i++)
{
DGV[i].Rows.Clear();
}
Anzahl = openFileDialog1.FileNames.Length;
counter = new int[Anzahl];
try
{
if (tabControl1.TabCount < Anzahl)
{
for (int i = 1; i <= Anzahl; i++)
{
if (i > tabControl1.TabCount)
{
string title = "Tab " + (tabControl1.TabCount + 1).ToString();
TabPage myTabPage = new TabPage(title);
tabControl1.TabPages.Add(myTabPage);
DataGridView NewDGV = new DataGridView();
NewDGV.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells;
NewDGV.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
NewDGV.Columns.Add("Energy", "Energy");
NewDGV.Columns[0].ReadOnly = true;
NewDGV.Columns.Add("Count Rate", "Count Rate");
NewDGV.Columns[1].ReadOnly = true;
NewDGV.Location = new System.Drawing.Point(3, 3);
NewDGV.Name = "NewDGV" + Convert.ToString(i);
NewDGV.RowHeadersVisible = false;
NewDGV.Size = new System.Drawing.Size(276, 379);
NewDGV.TabIndex = i;
foreach (DataGridViewColumn col in NewDGV.Columns)
col.SortMode = DataGridViewColumnSortMode.NotSortable;
NewDGV.SelectionMode = DataGridViewSelectionMode.ColumnHeaderSelect;
DGV.Add(NewDGV);
tabControl1.TabPages[i - 1].Controls.Add(NewDGV);
}
}
}
else if (tabControl1.TabCount > Anzahl)
{
for (int i = tabControl1.TabCount - 1; i >= Anzahl; i--)
{
tabControl1.TabPages.Remove(tabControl1.TabPages[i]);
}
}
}
catch { }
try
{
//Double arrays and Datagridview will be attuned to the count of data
eV = new double[openFileDialog1.FileNames.Length][];
meV = new double[openFileDialog1.FileNames.Length][];
cm = new double[openFileDialog1.FileNames.Length][];
CR = new double[openFileDialog1.FileNames.Length][];
CRmax = new double[openFileDialog1.FileNames.Length][];
for (int i = 0; i < Anzahl; i++)
{
//Naming the columns after data names
string[] Dateiname = openFileDialog1.FileNames[i].Split('\\');
int L = Dateiname.Length;
tabControl1.TabPages[i].Text = Dateiname[L-1];
}
}
catch
{
}
//Datafiles will be read one by one
DataRead(result, ref lesen, ref Spalte);
}
}
/// Reading loop
///
/// double[] eV2 = Energy values of the current data file in eV
/// double[] meV2 = Energy values of the current data file in meV
/// double[] cm2 = Energy values of the current data file in cm^-1
/// double[] CR2 = Intensities of the current data file in CR
/// double[] CRmax2 = normalizied Intensities of the current data file in 1/CRmax
private void DataRead(string[] result, ref bool lesen, ref int Spalte)
{
for (Spalte = 0; Spalte < Anzahl; Spalte++)
{
string line;
lesen = false;
counter[Spalte] = 0;
try
{
Ursprung = openFileDialog1.FileNames[Spalte];
//initialize stream reader
System.IO.StreamReader file1 = new System.IO.StreamReader(openFileDialog1.FileNames[Spalte]);
//read line per line in stream reader
while (((line = file1.ReadLine()) != null))
{
counter[Spalte]++;
Count2 = counter[Spalte];
Count2 = Count2 / 2;
try
{
string[] splitter = line.Split(' ');
if ((splitter[0] == "S") && (splitter[1] == "0000"))
{
lesen = true;
counter[Spalte] = 0;
}
if (lesen == true)
{
//Rows will be filled an added with data value strings
if (counter[Spalte] % 2 == 0)
{
result[0] = splitter[2];
}
else
{
result[1] = splitter[2];
dataGridView1.Rows.Add();
DGV[Spalte].Rows.Add();
int Zeile = (counter[Spalte] - 1) / 2;
DGV[Spalte][0, Zeile].Value = result[0];
DGV[Spalte][1, Zeile].Value = result[1];
}
}
}
catch
{
continue;
}
}
//Streamreader is closed
file1.Close();
counter[Spalte] = counter[Spalte] / 2;
//Current datagridviw values are saved in arrays
//The conversions will be calculated and saved in new arrays
//So every unit gets its own array
double[] eV2 = new double[counter[Spalte]];
double[] meV2 = new double[counter[Spalte]];
double[] cm2 = new double[counter[Spalte]];
double[] CR2 = new double[counter[Spalte]];
double[] CRmax2 = new double[counter[Spalte]];
//Conversion calculation
for (int i = 0; i < counter[Spalte]; i++)
{
eV2[i] = Convert.ToDouble(DGV[Spalte][0, i].Value);
CR2[i] = Convert.ToDouble(DGV[Spalte][1, i].Value);
meV2[i] = 1000 * eV2[i];
cm2[i] = 8066 * eV2[i];
}
//Current file's arrays are saved in double arrays
eV[Spalte] = eV2;
CR[Spalte] = CR2;
meV[Spalte] = meV2;
cm[Spalte] = cm2;
for (int i = 0; i < counter[Spalte]; i++)
{
CRmax2[i] = CR2[i] / CR2.Max();
}
CRmax[Spalte] = CRmax2;
//Chosen conversion replaces values in datagridview
if (Hilfe == 1)
{
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][0, i].Value = meV2[i];
}
}
else if (Hilfe == 2)
{
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][0, i].Value = cm2[i];
}
}
if (Hilfe2 == 1)
{
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][1, i].Value = CRmax2[i];
}
}
}
catch
{
MessageBox.Show("Es ist ein Fehler beim Einlesen eingetreten");
}
}
}
/// Energy Unit
/// Choses between eV, meV, 1/cm
/// Datagridview values are replaced by the unit array values
/// Hilfe... Saves current energy unit
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int L = comboBox1.SelectedIndex;
try
{
if (L == 0)
{
Hilfe = 1;
try
{
for (int Spalte = 0; Spalte < Anzahl; Spalte++)
{
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][0, i].Value = meV[Spalte][i];
}
}
}
catch
{
}
}
if (L == 1)
{
Hilfe = 2;
try
{
for (int Spalte = 0; Spalte < Anzahl; Spalte++)
{
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][0, i].Value = cm[Spalte][i];
}
}
}
catch
{
}
}
if (L == 2)
{
Hilfe = 0;
try
{
for (int Spalte = 0; Spalte < Anzahl; Spalte++)
{
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][0, i].Value = eV[Spalte][i];
}
}
}
catch
{
}
}
}
catch { }
}
Accept these answer if you dont know how to post your own answer?.
Answer:
Problem fixed. The reason was the dgv.autosizemode , when i deactivate it before the conversions it runs.
for (int Spalte = 0; Spalte < Anzahl; Spalte++)
{
DGV[Spalte].AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][0, i].Value = meV[Spalte][i];
}
DGV[Spalte].AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
}

How to copy values from textbox into array of labels?

OK Here's what I did and the values which were set vertical are copied in the labels but horizontal. And only one column/row.
public partial class Form1 : Form
{
private Label l;
private Button bStart;
private TextBox txtVnes;
private Label[] pole;
public Form1()
{
InitializeComponent();
bStart = new Button();
bStart.Location = new Point(240, 165);
bStart.Width = 75;
bStart.Height = 25;
bStart.Text = "START";
txtVnes = new TextBox();
txtVnes.Location = new Point(240, 10);
txtVnes.Width = 160;
txtVnes.Height = 130;
txtVnes.Multiline = true;
int a = 0;
pole = new Label[42];
for (int i = 1; i <= 6; i++)
{
for (int j = 1; j <= 7; j++)
{
l = new Label();
l.Name = "label" + i.ToString() + j.ToString();
l.Text = "Z";
l.Width = 20;
l.Height = 20;
l.TextAlign = ContentAlignment.MiddleCenter;
l.Parent = this;
l.BackColor = Color.FromArgb(100, 149, 237);
l.Location = new Point(10 + (j - 1) * 25, 15 + (i - 1) * 25);
pole[a] = l;
this.Controls.Add(l);
a++;
}
}
this.Controls.Add(bStart);
this.Controls.Add(txtVnes);
bStart.Click += new EventHandler(bStart_Click);
}
private void bStart_Click(object sender, EventArgs e)
{
Regex regex = new Regex(#"^(\s)*(\d ){6}\d(\s)*$");
bool isValid = true;
string[] ts = txtVnes.Text.Split(new string[] { "\r\n" },
StringSplitOptions.RemoveEmptyEntries);
if (ts == null || ts.Length < 1 || ts.Length > 6)
{
MessageBox.Show("Not valid");
}
else
{
foreach (string t in ts)
{
if (regex.IsMatch(t) == false)
{
MessageBox.Show("Not valid");
break;
}
}
}
if (isValid)
{
for (int i = 0; i < 6; i++)
{
if (i < ts.Length && regex.IsMatch(ts[i]))
{
pole[i].Text = ts[i];
}
else
{
pole[i].Text = "not valid";
}
}
}
}
Here's a photo
So here is the problem: When I click on the button bStart only one value is copied and replaced in one labe from the array of labels.
This should work like this: After the user clicks on the button bStart, all values from the textbox txtVnes should be copied in each label in the array of labels. All the labels have text "Z", and after click on the button they should be changed with the values in the textbox txtVnes. As you can see i used l.Text = txtVnes.Text; to copy the values, but it doesn't work. I appreciate if you can help me, thank you!
You are always setting the text of the same label l. Since your labels are in the array pole, you should set the text to consecutive pole indices.
I you want all the valid texts at the beginning:
string[] ts = txtVnes.Text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
int k = 0;
for (int i = 0; i < ts.Length && k < 6; i++) {
if (IsValid(ts[i])) { // Where IsValid is a method containing your validation logic.
pole[k++].Text = ts[i];
}
}
// Fill remaining labels
for (int i = k; i < 6; i++) {
pole[i].Text = "not valid";
}
Or, if you want vaild and invalid texts mixed:
string[] ts = txtVnes.Text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < 6; i++) {
if (i < ts.Length && IsValid(ts[i])) { // Where IsValid is a method containing your validation logic.
pole[i].Text = ts[i];
} else {
pole[i].Text = "not valid";
}
}
Note that array indices begin at 0, not at 1.
EDIT #2:
The IsValid method would look like this:
private static Regex regex = new Regex(#"^(\s)*(\d ){6}\d(\s)*$");
private static bool IsValid(string s)
{
return regex.IsMatch(s);
}
To answer your question in the comment: Yes, my examples above have to be placed in bStart_Click.
And there is also another error in your form constructor. this.Controls.Add(l); should be placed inside the inner for-loop, just after pole[a] = l;, otherwise only one label will be visible on your form.
Finally after having implemented and anlyzed your code, I came to the conclusion that you want to be able to enter text in the following format into the textbox and then place the digits into corresponding labels:
1 2 3 4 5 6 7
2 3 4 6 7 8 0
0 1 2 6 6 6 7
1 2 3 4 5 6 7
2 3 4 6 7 8 0
0 1 2 6 6 6 7
The complete code should look like this:
public partial class Form1 : Form
{
private Button bStart;
private TextBox txtVnes;
private Label[] pole;
public Form1()
{
InitializeComponent();
bStart = new Button();
bStart.Location = new Point(240, 165);
bStart.Width = 75;
bStart.Height = 25;
bStart.Text = "START";
bStart.Click += new EventHandler(bStart_Click);
this.Controls.Add(bStart);
txtVnes = new TextBox();
txtVnes.Location = new Point(240, 10);
txtVnes.Width = 160;
txtVnes.Height = 130;
txtVnes.Multiline = true;
this.Controls.Add(txtVnes);
int a = 0;
pole = new Label[42];
for (int i = 1; i <= 6; i++) {
for (int j = 1; j <= 7; j++) {
var l = new Label();
l.Name = "label" + i.ToString() + j.ToString();
l.Text = "Z";
l.Width = 20;
l.Height = 20;
l.TextAlign = ContentAlignment.MiddleCenter;
l.Parent = this;
l.BackColor = Color.FromArgb(100, 149, 237);
l.Location = new Point(10 + (j - 1) * 25, 15 + (i - 1) * 25);
pole[a] = l;
this.Controls.Add(l);
a++;
}
}
}
private void bStart_Click(object sender, EventArgs e)
{
string[] ts = txtVnes.Text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
int row = 0;
for (int i = 0; i < ts.Length && row < 6; i++) {
if (LineIsValid(ts[i])) {
for (int col = 0; col < 7; col++) {
pole[row * 7 + col].Text = ts[i][2 * col].ToString();
}
row++;
}
}
// Fill remaining labels
for (; row < 6; row++) {
for (int col = 0; col < 7; col++) {
pole[row * 7 + col].Text = "Z";
}
}
}
private static Regex regex = new Regex(#"^(\s)*(\d ){6}\d(\s)*$");
private static bool LineIsValid(string line)
{
return regex.IsMatch(line);
}
}
Two nested loops are required in bStart_Click as well. One for the rows and one for the columns.

Categories

Resources