I read from a text file, then save the contain of a file to an array
string[] SingleArray = new string[] {};
SingleArray[i] = File.ReadAllLines(path);
So now I would like to perform something like:
LnkmyValues_+Convert.ToString(i)+".Text" = singleArray[i];
Or If the above can't be done can I have an example on how to putting dynamic linklabel of array on each row or col to a tablelayoutpanel
Assuming that you are using Windows Forms with a Form called Form1 that contains a TableLayoutPanel called tableLayoutPanel1, here is a working example of how you could achieve what you want:
private void Form1_Load(object sender, EventArgs e)
{
string[] singleArray = File.ReadAllLines("path to your file");
// alternatively, for testing:
//string[] singleArray = {"http://www.google.com", "http://www.microsoft.com", "http://www.stackoverflow.com"};
tableLayoutPanel1.ColumnCount = 1;
tableLayoutPanel1.RowCount = singleArray.Length;
for (int i = 0; i < singleArray.Length; i++)
{
// create a new link label and set some properties
LinkLabel linkLabel = new LinkLabel();
linkLabel.Text = "I am link label #" + i;
LinkLabel.Link linkLabelLink = new LinkLabel.Link();
linkLabelLink.LinkData = singleArray[i];
// tell the label to open a browser upon a click
linkLabel.LinkClicked += (o, args) => System.Diagnostics.Process.Start(args.Link.LinkData as string);
linkLabel.Links.Add(linkLabelLink);
// add new link label to row i in colum 0
tableLayoutPanel1.Controls.Add(linkLabel, 0, i);
}
}
Related
I plotted a graph by using .csv file.Now user enable to select the chart area and clicking export button then selected data want to write another .csv file.
In here I want to approach this methods.User want to get chart1.ChartAreas[0].CursorX.SelectionStart,chart1.ChartAreas[0].CursorX.SelectionEndthen want to read .csv file and deleting others raw that in not selected area.
Note:the user want to select multiple chart area also.Please give me a clarification about this.This is winform application and I use MsChart.
my code as follows;
private void btnExport_Click(object sender, EventArgs e)
{
List<Graph> ObservingData = new List<Graph>(); // List to store all available Graph objects from the CSV
int index = 0;
using (StreamWriter sw = new StreamWriter(#"D:\CSVFile\NEWFile\Export\NewFile.csv"))
{
// Loops through each lines in the CSV
foreach (string line in System.IO.File.ReadAllLines(pathToCsv))
{
// here line stands for each line in the csv file
string[] CsvLine = line.Split(',');
// creating an object of type Graph based on the each csv line
// and adding them to the List<Graph>
Graph Instance1 = new Graph();
if (index == 0)
{
sw.WriteLine(line);
}
else
{
//Add the code here..
// if (((chart1.ChartAreas[0].CursorX.SelectionStart))<= && ( <= (chart1.ChartAreas[0].CursorX.SelectionEnd)))
{
sw.WriteLine(line);
}
}
index++;
}
sw.Close();
}
MessageBox.Show("Data are copied to the new .CSV file");
}
Following code for my multiple selection for chart area.
SizeF curRange = SizeF.Empty;
List<SizeF> ranges = new List<SizeF>();
List<int> selectedIndices = new List<int>();
private void chart1_SelectionRangeChanged(object sender, CursorEventArgs e)
{
ranges.Add(curRange);
selectedIndices.Union(collectDataPoints(chart1.Series[0],curRange.Width, curRange.Height)).Distinct();
StripLine sl = new StripLine();
sl.BackColor = Color.FromArgb(255, Color.LightSeaGreen);
sl.IntervalOffset = Math.Min(curRange.Width, curRange.Height);
sl.StripWidth = Math.Abs(curRange.Height - curRange.Width);
chart1.ChartAreas[0].AxisX.StripLines.Add(sl);
}
List<int> collectDataPoints(Series s, double min, double max)
{
List<int> hits = new List<int>();
for (int i = 0; i < s.Points.Count; i++)
if (s.Points[i].XValue >= min && s.Points[i].XValue <= max) hits.Add(i);
return hits;
}
private void chart1_SelectionRangeChanging(object sender, CursorEventArgs e)
{
curRange = new SizeF((float)e.NewSelectionStart, (float)e.NewSelectionEnd);
}
Following code is plotted graph;
private void Output_Load(object sender, EventArgs e)
{
List<Graph> ObservingData = new List<Graph>(); // List to store all available Graph objects from the CSV
// Loops through each lines in the CSV
foreach (string line in System.IO.File.ReadAllLines(pathToCsv).Skip(1)) // .Skip(1) is for skipping header
{
// here line stands for each line in the csv file
string[] InCsvLine = line.Split(',');
// creating an object of type Graph based on the each csv line
Graph Inst1 = new Graph();
Inst1.Date = DateTime.ParseExact(InCsvLine[0], dateFormatString, CultureInfo.InvariantCulture);
Inst1.AvE = double.Parse(InCsvLine[15]);
Inst1.AvI = double.Parse(InCsvLine[16]);
chart1.Series["Speed"].YAxisType = AxisType.Primary;
chart1.Series["Velocity"].YAxisType = AxisType.Secondary;
chart1.Series["Speed"].Points.AddXY(Inst1.Date.TimeOfDay.ToString(), Inst1.AvE);
chart1.Series["Speed"].ChartType = SeriesChartType.FastLine;
chart1.Series["Velocity"].Points.AddXY(Inst1.Date.TimeOfDay.ToString(), Inst1.AvI);
chart1.Series["Velocity"].ChartType = SeriesChartType.FastLine;
ChartArea CA = chart1.ChartAreas[0];
CA.AxisX.ScaleView.Zoomable = false;
CA.AxisY.ScaleView.Zoomable = false;
CA.CursorX.AutoScroll = true;
CA.CursorX.IsUserSelectionEnabled = true;
}
}
This is out put of graph
Here is an example you may want to study.
It assumes that the x-values are added as DateTimes; set the XValueType!
eachSeries.XValueType = ChartValueType.DateTime;
It also assumes that you have a class level List of sereis to be exported:
var series2Export = new List<Series>() { chart.Series[0], chart.Series[1]};
It assumes further that the points in the series are added in parallel, so that you want to export the same range together, e.g. to first 20 or points from index 33-66..
Now you can for example code the SelectionRangeChanged event (or, of course a Save Button click):
private void chart_SelectionRangeChanged(object sender, CursorEventArgs e)
{
ChartArea ca = chart.ChartAreas[0];
var d0 = (int) ca.CursorX.SelectionStart;
var d1 = (int) ca.CursorX.SelectionEnd;
var spoints = series2Export[0].Points
.Where(x => x.XValue >= d0 && x.XValue <= d1).ToList();
string del1 = ";";
string del2 = "\t";
string fmt1 = "yyyy.MM.dd";
string fmt2 = "#0.0";
SaveFileDialog sfd = new SaveFileDialog();
sfd.FileName = suggestedFilePath;
sfd.Title = (d1 - d0) + " points selected. Save data to..";
if (sfd.ShowDialog() == DialogResult.OK)
{
StringBuilder sb = new StringBuilder();
foreach (var dp0 in spoints)
{
int pi = chart.Series[0].Points.IndexOf(dp0);
string st = "";
foreach (var s in series2Export)
{
DataPoint dp = s.Points[pi];
st += (DateTime.FromOADate(dp.XValue)).ToString(fmt1) +
del1 + dp.YValues[0].ToString(fmt2) + del2;
}
sb.AppendLine(st);
}
File.WriteAllText(sfd.FileName, sb.ToString());
}
}
}
Note that I have used strings for both the delimiters and the formts of the data. You can adapt them as needed..
The above code is exporting the data from all participating series in the format: x-value1, yvalue1..; this means it assumes that..
the datapoints contain all the information you want to export and
you want to export the x-values for each point.
If you want to export just the csv line as you had read it in, the simplest way is to store that line with each DataPoint, of, say the 1st series. The natural spot to store them in are the Tags.
Here are two functions to create a list of data points from a line and to restore that line from a series:
List<DataPoint> PointsFromCsvLine(string line)
{
var parts = line.Split(',').ToList(); // use your separator
DateTime dt = Convert.ToDateTime(parts[0]); // add checks!
double d1 = Convert.ToDouble(parts[1]); // use..
double d2 = Convert.ToDouble(parts[4]); // ..your..
double d3 = Convert.ToDouble(parts[9]); // ..numbers!
var points = new List<DataPoint>();
points.Add(new DataPoint( dt.ToOADate(), d1));
points.Add(new DataPoint( dt.ToOADate(), d2));
points.Add(new DataPoint( dt.ToOADate(), d3));
points[0].Tag = line;
return points;
}
string CsvLineFromPoint(Series series0, int index )
{
DataPoint dp = series0.Points[index]; // check index
string s = dp.Tag.ToString();
return s;
}
I have a bunch of code that dynamicly creates some controls. It looks in a folder and lists the filenames in it. For each file in the folder it creates a checklistbox item, listbox item and two checkboxes. This is working great and as intended:
private void getAllFiles(string type)
{
try
{
string listPath = "not_defined";
if (type == "internal_mod")
{
int first_line = 76;
int next_line = 0;
int i = 0;
CheckBox[] chkMod = new CheckBox[100];
CheckBox[] chkTool = new CheckBox[100];
listPath = this.internalModsPath.Text;
string[] filesToList = System.IO.Directory.GetFiles(listPath);
foreach (string file in filesToList)
{
if (!internalModsChkList.Items.Contains(file))
{
internalModsChkList.Items.Add(file, false);
string fileName = Path.GetFileName(file);
internalModNameList.Items.Add(fileName);
//-----------------
// Draw Checkboxes
//-----------------
chkMod[i] = new CheckBox(); chkTool[i] = new CheckBox();
chkMod[i].Name = "modChk" + i.ToString(); chkTool[i].Name = "modChk" + i.ToString();
//chkMod[i].TabIndex = i; //chkTool[i].TabIndex = i;
chkMod[i].Anchor = (AnchorStyles.Left | AnchorStyles.Top); chkTool[i].Anchor = (AnchorStyles.Left | AnchorStyles.Top);
chkMod[i].Checked = true; chkTool[i].Checked = false;
chkMod[i].AutoCheck = true; chkTool[i].AutoCheck = true;
chkMod[i].Bounds = new Rectangle(549, first_line + next_line, 15, 15); chkTool[i].Bounds = new Rectangle(606, first_line + next_line, 15, 15);
groupBox7.Controls.Add(chkMod[i]); groupBox7.Controls.Add(chkTool[i]);
//-----------------
next_line += 15;
i++;
}
}
}
Now my problem is that I also want the user to be able to delete all these thing again based on the checklistbox' checked items.. I have no problems deleting the items in the checklistbox or the items in the listbox, but I want to remove the two checkboxes I create too ..
This is what I got to remove the items in the checklistbox, and the listbox
private void internalModListDel_btn_Click(object sender, EventArgs e)
{
int count = internalModsChkList.Items.Count;
for (int index = count; index > 0; index--)
{
if (internalModsChkList.CheckedItems.Contains(internalModsChkList.Items[index - 1]))
{
internalModsChkList.Items.RemoveAt(index - 1);
internalModNameList.Items.RemoveAt(index - 1);
groupBox7.Controls.Remove(modChk[index - 1]);
}
}
}
As you can see I have also tried to write something to remove the checkbox but it doesn't work and I have no idea how to make it work
Can you assist ?
Try using UserControls.
Use the ListBox controller to show those UserControls,
The user control can be built with those checkboxes, and the labels you want .
Another suggestion is to bind this list to an ObservableCollection which will contain the UserContorols you have created.
This way, it will be much more simlpe to add/remove/change the items inside.
I have this code, which dynamically creates some textfields for me. k is taken from user btw.
for (int i = 0; i < k; i++)
{
TextBox t1 = new TextBox();
t1.Parent = groupBox2;
t1.Left = textBox2.Left;
t1.Top = textBox2.Top + (i + 1) * 40;
t1.Name = "text" + (i + 1);
t1.Enabled = true;
groupBox2.Controls.Add(t1);
}
What i want to do is, after this creating phase is done, when the user presses groupbox2's "OK" button, I want to take the created textfields' text properties, but so far I don't know how could this be done, since I gave textfields a name, I tried this but didn't work.
private void button3_Click(object sender, EventArgs e)
{
node1.name = textBox2.Text;
for (int i = 0; i < k; i++)
{
node1.array[i] = Convert.ToInt32("text"+(i+1).Text);
}
}
Any help would be nice, thanks.
Try this method:
private void button3_Click(object sender, EventArgs e)
{
node1.name = textBox2.Text;
for (int i = 0; i < k; i++)
{
TextBox txtBox = (TextBox)groupBox2.FindControl("text" + (i + 1));
if (txtBox != null)
{
node1.array[i] = txtBox.Text;
}
}
}
Loop through your text boxes in groupBox1 and get their names,Try this:
List<string> TextBoxesName=new List<string>();
foreach (Control item in groupBox1.Controls)
{
if (item is TextBox)
{
TextBoxesName.Add((item as TextBox).Text);
}
}
Set to your dynamic texboxes ID and than you can do groupBox2.FindControl("dynamic_texbox_id") to get your text box
Easiest solution is to put your listboxes in a collection of some sort
List<ListBox> listboxes = new List<ListBox>();
for (...)
{
...
listboxes.add(listbox);
}
Then you can refer back to them whenever you want
Or since you're adding them to a groupbox, why not go through that collection?
HI I have requirement that
1) display given no.of textboxes dynamically and save to DB
2) if I change the number then new textboxes should append to UI
EX: TextBox AddButton
If I give 2 in textbox and click on add
Then 2 textboxes should appear. I filled some data in those textboxes. Now When I change the value 2 to 5 then 3 more textboxes should append(condition:old textboxes data should retain)
If the second value is less than or equal to first value then do nothing.
My code is
void Append()
{
string Data = string.Empty;
TextBox tb;
if (Convert.ToInt32(hdnCnt.Value) < Convert.ToInt32(txtNoofGames.Text))
{
for (int i = 0; i < Convert.ToInt16(txtNoofGames.Text); i++)
{
if (i <= Convert.ToInt32(hdnCnt.Value))
{
tb = (TextBox)Form.FindControl("txtGame1");
Data = tb.Text;
}
TextBox Newtb = new TextBox();
Newtb.ID = "txtGame" + i;
Form.Controls.Add(Newtb);
if (i <= Convert.ToInt32(hdnCnt.Value))
{
Newtb.Text = Data;
}
}
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
if (hdnCnt.Value != "")
Append();
hdnCnt.Value = txtNoofGames.Text;
for (int i = 0; i < Convert.ToInt16(txtNoofGames.Text); i++)
{
TextBox tb = new TextBox();
tb.ID = "txtGame" + i;
Form.Controls.Add(tb);
}
}
I am getting exception "object reference not set to an instance of object" at Data = tb.Text; in append method.
You didn't initialize it from the looks of it
TextBox tb = new TextBox();
Hope that helps,
Instead of Form.Controls.Add(tb);
Please try with Page.Form.Controls.Add(tb);
I need to dynamically create radio buttons based on dynamic list. Scenario is like I have list of files shown as Radio button in WinForm. A user clicks on radio button to select file and move forward.
I tried doing following as an example
for (int i = 0; i < 10; i++)
{
ii = new RadioButton();
ii.Text = i.ToString();
ii.Location = new Point(20, tt);
tt = tt + 20;
panel1.Controls.Add(ii);
}
The problem is how would I check which value got selected by user?
A simple way to do it is by using the RadioButtons CheckChanged event to set a variable that specifies the file that they have chosen by using the RadioButtons text or Tag property which you could set to be the file itself?
e.g.
private File f = null;
for (int i = 0; i < 10; i++)
{
ii = new RadioButton();
ii.Text = i.ToString();
ii.Location = new Point(20, tt);
ii.Tag = fileArray[i]; // Assuming you have your files in an array or similar
ii.CheckedChanged += new System.EventHandler(this.Radio_CheckedChanged);
tt = tt + 20;
panel1.Controls.Add(ii);
}
private void Radio_CheckedChanged(object sender, EventArgs e)
{
RadioButton r = (RadioButton)sender;
f = (File)r.Tag;
}
It's certainly not the most elegant way but it would work.