I am trying to read an XML file using LINQ. I have had no problem reading and parsing simple XML files but this one has me stumped.
Here is a portion of the file: The file is properly formed and valid.
<Activities>
<Activity Sport="Other">
<Id>2009-12-17T19:53:14Z</Id>
<Lap StartTime="2009-12-17T19:53:14Z">
<TotalTimeSeconds>820.5400000</TotalTimeSeconds>
<DistanceMeters>1510.3433838</DistanceMeters>
<MaximumSpeed>2.6089859</MaximumSpeed>
<Calories>104</Calories>
<AverageHeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t">
<Value>128</Value>
</AverageHeartRateBpm>
<MaximumHeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t">
<Value>139</Value>
</MaximumHeartRateBpm>
<Intensity>Active</Intensity>
<TriggerMethod>Manual</TriggerMethod>
...
and here is my code
XDocument document = XDocument.Load(myfileXml);
var query = from gtc in document.Descendants("Activities").Elements("Lap")
select new
{
Id = gtc.Parent.Element("Id").Value,
StartTime = gtc.Attribute("StartTime").Value,
TotalSeconds = gtc.Element("TotalTimeSeconds").Value,
DistanceMeters = gtc.Element("DistanceMeters").Value,
MaximumSpeed = gtc.Element("MaximumSpeed").Value,
Calories = gtc.Element("Calories").Value,
Intensity = gtc.Element("Intensity").Value,
TriggerMethod = gtc.Element("TriggerMethod").Value
};
dataGridView1.DataSource = query.ToList();
When I run this, I see the Headers in the DataGridView, but no data. Can someone please tell me where I am going wrong? Also in the solution can someone tell me how to read the value for the heart rates? Thank you!
Change Activities to Activity:
from gtc in document.Descendants("Activity").Elements("Lap")
And for the heartrate, add these two lines near the end of your select:
TriggerMethod = gtc.Element("TriggerMethod").Value,
AverageHeartRateBpm = gtc.Element("AverageHeartRateBpm").Element("Value").Value,
MaximumHeartRateBpm = gtc.Element("MaximumHeartRateBpm").Element("Value").Value
}
Here is my complete code. The only change I made apart from the two I mentioned was to remove the xsi:type attributes.
using System;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string xml = #"<Activities>
<Activity Sport=""Other"">
<Id>2009-12-17T19:53:14Z</Id>
<Lap StartTime=""2009-12-17T19:53:14Z"">
<TotalTimeSeconds>820.5400000</TotalTimeSeconds>
<DistanceMeters>1510.3433838</DistanceMeters>
<MaximumSpeed>2.6089859</MaximumSpeed>
<Calories>104</Calories>
<AverageHeartRateBpm >
<Value>128</Value>
</AverageHeartRateBpm>
<MaximumHeartRateBpm>
<Value>139</Value>
</MaximumHeartRateBpm>
<Intensity>Active</Intensity>
<TriggerMethod>Manual</TriggerMethod>
</Lap>
</Activity>
</Activities>
";
XDocument document = XDocument.Parse(xml);
var query = from gtc in document.Descendants("Activity").Elements("Lap")
select new
{
Id = gtc.Parent.Element("Id").Value,
StartTime = gtc.Attribute("StartTime").Value,
TotalSeconds = gtc.Element("TotalTimeSeconds").Value,
DistanceMeters = gtc.Element("DistanceMeters").Value,
MaximumSpeed = gtc.Element("MaximumSpeed").Value,
Calories = gtc.Element("Calories").Value,
Intensity = gtc.Element("Intensity").Value,
TriggerMethod = gtc.Element("TriggerMethod").Value,
AverageHeartRateBpm = gtc.Element("AverageHeartRateBpm").Element("Value").Value,
MaximumHeartRateBpm = gtc.Element("MaximumHeartRateBpm").Element("Value").Value
};
dataGridView1.DataSource = query.ToList();
}
}
}
Related
looks like a very simple task by i'm very new to c# and can't seem to find the right answer for this
i have the below xml structure (elements vary in quantity)
<config>
<extras>
<dir_update>C:\extension\update.exe</dir_update>
</extras>
<connection_MAIN>
<ip>LOCALHOST,1433</ip>
<bd>DATA</bd>
<user>sa</user>
<password>gzqs=</password>
</connection_MAIN>
<connection_LOBBY>
<ip>10.0.0.2,1433</ip>
<bd>DATA</bd>
<user>sa</user>
<password>I/wqqZIgzqs=</password>
<caixa>5yIz5GPu80s=</caixa>
<printer>cARrmGLQlztLiUDxIJqoPkvJabIiyI9ye4H7t+4muYk=</printer>
</connection_LOBBY>
<connection_FRONT>
<ip>10.0.0.5,1433</ip>
<bd>FIELDS</bd>
<user>sa</user>
<password>I/wqqZIgzqs=</password>
</connection_FRONT>
</config>
I'm already getting the elements that start with "connection_" in my combobox and i want the values inside the <ip>, <bd>, <user> and <password> when i select the connection on the combobox.
The problem i'm getting is that it's returning the word itself not the value inside on the code below
private void Form1_Load(object sender, EventArgs e)
{
using(DataSet ds = new DataSet())
{
ds.ReadXml(textBox1.Text);
foreach(DataTable dt in ds.Tables)
{
if (dt.ToString().Contains("conection_"))
{
comboBox1.Items.Add(dt.ToString().Replace("conection_", ""));
}
}
comboBox1.SelectedIndex = 0;
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
using(DataSet ds = new DataSet())
{
ds.ReadXml(textBox1.Text);
string v = comboBox1.Text.ToString();
string ip = ds.Tables[$"conection_{v}"].Columns[0].ToString();
}
}
Variable ip is getting the value "ip" and i want "LOCALHOST,1433" when i select the first option on my combobox in this example.
Also i want to search for column value by the name ("ip", "bd"), but i seem to only get results when using Columns[0], Columns[1].
I've followed some guides that i've looked around, but they seem to not work on this format of xml or i'm looking at it the wrong way.
Any help is appreciated.
There is no need to use DataSet and DataTable data types. The best API to handle XML is LINQ to XML.
Check it out below.
c#
void Main()
{
const string MAIN = "connection_MAIN";
string IP = string.Empty;
string bd = string.Empty;
string user = string.Empty;
string password = string.Empty;
XElement xml = XElement.Parse(#"<config>
<extras>
<dir_update>C:\extension\update.exe</dir_update>
</extras>
<connection_MAIN>
<ip>LOCALHOST,1433</ip>
<bd>DATA</bd>
<user>sa</user>
<password>gzqs=</password>
</connection_MAIN>
<connection_LOBBY>
<ip>10.0.0.2,1433</ip>
<bd>DATA</bd>
<user>sa</user>
<password>I/wqqZIgzqs=</password>
<caixa>5yIz5GPu80s=</caixa>
<printer>cARrmGLQlztLiUDxIJqoPkvJabIiyI9ye4H7t+4muYk=</printer>
</connection_LOBBY>
<connection_FRONT>
<ip>10.0.0.5,1433</ip>
<bd>FIELDS</bd>
<user>sa</user>
<password>I/wqqZIgzqs=</password>
</connection_FRONT>
</config>");
// get needed connection fragment
IEnumerable<XElement> fragment = xml.Descendants(MAIN);
// get all needed elements one by one
IP = fragment.Elements("ip")?.FirstOrDefault().Value;
bd = fragment.Elements("bd")?.FirstOrDefault().Value;
user = fragment.Elements("user")?.FirstOrDefault().Value;
password = fragment.Elements("password")?.FirstOrDefault().Value;
}
Using Xml Linq I put results in to a datatable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("name", typeof(string));
dt.Columns.Add("ip", typeof(string));
dt.Columns.Add("bd", typeof(string));
dt.Columns.Add("user", typeof(string));
dt.Columns.Add("password", typeof(string));
XDocument doc = XDocument.Load(FILENAME);
foreach(XElement connection in doc.Descendants().Where(x => x.Name.LocalName.StartsWith("connection_")))
{
dt.Rows.Add(new object[] {
((string)connection.Name.LocalName).Substring(((string)connection.Name.LocalName).IndexOf("_") + 1),
(string)connection.Element("ip"),
(string)connection.Element("bd"),
(string)connection.Element("user"),
(string)connection.Element("password")
});
}
Dictionary<string, DataRow> dict = dt.AsEnumerable()
.GroupBy(x => x.Field<string>("name"), y => y)
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
string ip = dict["LOBBY"].Field<string>("ip");
}
}
}
I'm really new to coding so I'm struggling to get an answer for my question directly.
I tried to find answer for my question on many ways (YouTube, stack overflow, google) but couldn't get my program to run correctly.
What I need my program to do is get a value from an m3u file into the appropriate cell on my data table and not read and add absolutely everything.
What I have found online is mainly how to read text/csv/excel and import all the data from the file itself, this is not what I really need or code that i do not understand how to implement for my use, like that question: Reading from .txt file, then exporting data to DataGridView.
I have defined cells that should "suck" the data from the m3u file.
The file m3u file structure is:
#EXTINF:-1 tvg-ID="" tvg-name="==== Example1 ====" tvg-logo="" group-title="",==== Example1 ====
thestreamingsource1.com
#EXTINF:-1 tvg-ID="" tvg-name="==== Example2 ====" tvg-logo="" group-title="",==== Example2 ====
thestreamingsource2.com
#EXTINF:-1 tvg-ID="" tvg-name="==== Example3 ====" tvg-logo="" group-title="",==== Example3 ====
thestreamingsource3.com
#EXTINF:-1 tvg-ID="" tvg-name="==== Example4 ====" tvg-logo="" group-title="",==== Example4 ====
thestreamingsource4.com
And I need the program to only get the following from the value structure:
tvg-ID (It's okay if it's empty).
tvg-name.
tvg-logo (It's okay if it's empty).
group-title.
So far i have the string that reads all the content of the file and the data grid ready to accept data.
The code behind the form is:
public class ThisClass
{
DataGridView my_datagridview = new DataGridView();
DataTable my_datatable = new DataTable();
// Constructor and other methods are in this class,
// but not showed here...
private void btnRead_Click(object sender, EventArgs e)
{
// Some codes are hidden here...
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string sFileName = openFileDialog1.FileName;
string[] alltext = File.ReadAllLines(sFileName);
foreach (string text_line in alltext)
{
// MessageBox.Show(text_line);
}
}
}
}
And the form looks like that:
I'm sorry If the question is already answered but i couldn't find a solution.
Glad if you could help.
Thanks.
This should get you going:
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
namespace DataGridView_45378237
{
public partial class Form1 : Form
{
DataGridView my_datagridview = new DataGridView();//the DataGridView which will be put on the form
BindingList<MyDatagridviewEntry> myDataGridviewSource = new BindingList<MyDatagridviewEntry>();//the BindingList from which the DataGridView will pull its data
public Form1()
{
InitializeComponent();
InitializeDataGridView();//set the initial settings of the DataGridView
}
private void InitializeDataGridView()
{
my_datagridview.Location = new Point(this.Location.X + 15, this.Location.Y + 15);//define where to place it in the form(you could obviously just place one directly where you want using the wysiwyg)
this.Controls.Add(my_datagridview);
my_datagridview.AutoSize = true;
my_datagridview.AutoGenerateColumns = true;
my_datagridview.DataSource = myDataGridviewSource;//link the DataGridView with the BindingSource
}
private void btnRead_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = #"C:\";
openFileDialog1.Title = "Browse Text Files";
openFileDialog1.CheckFileExists = true;
openFileDialog1.CheckPathExists = true;
openFileDialog1.DefaultExt = "m3u";
openFileDialog1.Filter = "All files (*.*)|*.*|m3u files (*.m3u)|*.m3u";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
openFileDialog1.ReadOnlyChecked = true;
openFileDialog1.ShowReadOnly = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string sFileName = openFileDialog1.FileName;
FillDataGridFromFile(sFileName);//send the file to get parsed
}
}
private void FillDataGridFromFile(string incomingFilePath)
{
//empty the list
myDataGridviewSource.Clear();//you may or may not want this... I don't know your full requirements...
//fill the list
using (StreamReader sr = new StreamReader(incomingFilePath))
{
string currentLine = string.Empty;
while ((currentLine = sr.ReadLine()) != null)
{
/*This is not how I would write the production code,
* but for the sake of this example, this format works well
so that you know what is being done and why.*/
string[] splittedString = currentLine.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
string f1 = splittedString.Length > 0 ? splittedString[0] : string.Empty;//if splittedString has more than 0 entries, the use entry[0], else use string.empty
string f2 = splittedString.Length > 1 ? splittedString[1] : string.Empty;//if splittedString has more than 1 entries, the use entry[1], else use string.empty
string f3 = GetTVGNameFromString(splittedString[0]);//Extract the text from within the string
string f4 = splittedString.Length > 3 ? splittedString[3] : string.Empty;//if splittedString has more than 3 entries, the use entry[3], else use string.empty
/**/
//add the entry to the BindingSource
myDataGridviewSource.Add(new MyDatagridviewEntry { Col1 = f1, Col2 = f2, Col3 = f3, Col4 = f4 });
}
}
}
private string GetTVGNameFromString(string incomingString)
{
string retval = string.Empty;
Regex rgx = new Regex("tvg-name=\"([^\"]*)\"");//use a grouping regex to find what you are looking for
if (rgx.IsMatch(incomingString))
{
return rgx.Matches(incomingString)[0].Groups[1].Value;
}
return retval;
}
}
public class MyDatagridviewEntry
{
public string Col1 { get; set; }
public string Col2 { get; set; }
public string Col3 { get; set; }
public string Col4 { get; set; }
}
}
My XML looks like this
<root>
<record>
<Object_Number> 1</Object_Number>
<Object_Level> 1</Object_Level>
<Object_Heading> Introduction</Object_Heading>
<Object_Text> </Object_Text>
<Milestones> </Milestones>
<Unique_ID> </Unique_ID>
<Field_type> Info</Field_type>
<SG_attribute> </SG_attribute>
<Object_Identifier>1</Object_Identifier>
<Object_URL>doors://D1DDBAPP04:36677/?version=2&prodID=0&view=0000001a&urn=urn:telelogic::1-432aa0956f684cff-O-1-00028f60</Object_URL>
</record>
...
records...
...
</root>
Is it possible bind a IEnumerable result to a DatgridView and automatic detect columns?
Initially, I've done this
ds = new DataSet();
ds.ReadXml(myXml);
Then, convert to a DataTable
dt = ds.Tables["record"]
And this can directly populate DGV
dgvDoors.DataSource = dt;
But now, I realize that it's more easily to manipulate data directly in XML (with LINQ) and need somehow to display that (filtered) results in DataGridView
IEnumerable<XElement> elements = xdoc.Element("root").Elements("record");
Now is it possible to display 'elements' to DataGridView and detect columns such in original XML?
Thank you,
PS.
var bs = new BindingSource { DataSource = elements};
dgvDoors.DataSource = bs;
This is not working correctly since instead of records, DGV will display some other columns such as
FirstAttribute
HasAttributes
HasElements
...
To make it working properly I would recommend converting your xml data to strongly typed View Models.
public class RecordViewModel
{
public string Number { get; set; }
public string Level { get; set; }
public string Heading { get; set; }
public string Milestones { get; set; }
}
Below implementation, please let know if it works as you expect:
var elements = xdoc.Element("root").Elements("record")
.Select(e => new RecordViewModel
{
Number = e.Element("Object_Number").Value,
Level = e.Element("Object_Level").Value,
Heading = e.Element("Object_Heading").Value,
Milestones = e.Element("Milestones").Value,
});
var bs = new BindingSource
{
DataSource = elements
};
dgvDoors.DataSource = bs;
The conversion between Xml Data and ViewModels above is not checking for nulls, so you can move the implementation to some mapper, where the logic of converting Xml data to ViewModel would be more complex.
Try following which matches your request
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication49
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
string[] columnNames = doc.Descendants("record").FirstOrDefault().Elements().Select(x => x.Name.LocalName).ToArray();
DataTable dt = new DataTable();
foreach (string col in columnNames)
{
dt.Columns.Add(col, typeof(string));
}
foreach (XElement record in doc.Descendants("record"))
{
DataRow newRow = dt.Rows.Add();
foreach (string columnName in columnNames)
{
newRow[columnName] = (string)record.Element(columnName);
}
}
}
}
}
<CustomerOrders>
<Customers>
<CustomerID>ALFKI</CustomerID>
<Orders>
<OrderID>10643</OrderID>
<CustomerID>ALFKI</CustomerID>
<OrderDate>1997-08-25</OrderDate>
</Orders>
<Orders>
<OrderID>10692</OrderID>
<CustomerID>ALFKI</CustomerID>
<OrderDate>1997-10-03</OrderDate>
</Orders>
<CompanyName>Alfreds Futterkiste</CompanyName>
</Customers>
<Customers>
<CustomerID>ANATR</CustomerID>
<Orders>
<OrderID>10308</OrderID>
<CustomerID>ANATR</CustomerID>
<OrderDate>1996-09-18</OrderDate>
</Orders>
<CompanyName>Ana Trujillo Emparedados y helados</CompanyName>
</Customers>
</CustomerOrders>
How do you retrieve OrderID,CustomerID and OrderDate? i have been trying it for hours already. Can someone help me? Thanks!
XmlNodeList xmlnode = doc.GetElementsByTagName("Customers");
HtmlGenericControl div = new HtmlGenericControl("div");
for(int i = 0; i < xmlnode.Count; i++)
{
Label lbl2 = new Label();
lbl2.Text = xmlnode[i].ChildNodes[1].Name;
div.Controls.Add(lbl2);
RadioButtonList rb1 = new RadioButtonList();
rb1.Items.Add(xmlnode[i].ChildNodes[1].InnerText+"<br>");
div.Controls.Add(rb1);
}
div1.Controls.Add(div);
You can use the XDocument class and its decendants. You can use XPath expressions to delve deeper into the code:
e.g.
using System.Xml.Linq
using System.Xml.XPath
....
XDocument doc= XDocument.Load("sample.xml");
XElement root= doc.Element("CustomerOrders");
var result= root.XPathSelectElements("Customers/CustomerId");
foreach(var customerid in result)
{
.....
}
Depending on what you want to achieve this should put you at the right track. While I was typing the answer, another answer proposes to use XmlDocument class. That should work as well, but when using XDocument you can use Linq, which adds a lot of flexibilty.
XmlDocument doc = new XmlDocument();
doc.LoadXml("yourxmldata");
XmlNodeList customers = doc.DocumentElement.SelectNodes("Customers");
foreach (XmlNode customer in customers)
{
XmlNodeList customerOrders = customer.SelectNodes("Orders");
string customername = customer["CustomerID"].InnerText;
foreach (XmlNode customerOrder in customerOrders)
{
string orderid = customerOrder["OrderID"].InnerText;
string orderdate = customerOrder["OrderDate"].InnerText;
}
}
Here is everything using Xml Linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication47
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
var results = doc.Descendants("Customers").Select(x => new
{
customerID = (string)x.Element("CustomerID"),
companyName = (string)x.Element("CompanyName"),
orders = x.Elements("Orders").Select(y => new {
orderID = (int)y.Element("OrderID"),
customerID = (string)y.Element("CustomerID"),
date = (DateTime)y.Element("OrderDate")
}).ToList()
}).ToList();
}
}
}
I want to below steps in using Visual studio in C#:
I read the .csv file but I can't pass the selected 2 rows to draw the graph in form.cs.please give help for me.if you can give any code example,it's a great advance for me.thank you.I coded it below as follows,I want to pass that selected column value and draw a graph in another form by using visual studio in C#.
my .csv file look like as follows:
Date,Cycle,Schedule,Step,AvT1,St1,TargetE1,AvE1,AvI1
7/2/2017,11:19,0,1,25.978,State1,0,-0.2248319,0.0066
7/2/2017 ,11:19,0,1,25.978,State1,0,-0.2264814,0.0088
7/2/2017,11:19,0,2,25.978,State1,0,-0.2322548,0.0088
7/2/2017 ,11:19,0,2,,25.978,State1,0,-0.2583174,0.0088
(consider AvE1 as x axis and AvI1 as y axis)
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 GraphCsvInput
{
public partial class Form1 : Form
{
DataGridView my_gridview = new DataGridView();
DataTable my_datatable = new DataTable();
//private Form2 frm2;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.Size = new Size(750,500);
my_gridview.Size = new Size(600,400);
my_gridview.Location=new Point(5,5);
string[] raw_txt = System.IO.File.ReadAllLines("C://Users//SampleGraphFile_CSV.csv");
string []data_col = null;
int x = 0;
foreach(string text_line in raw_txt)
{
data_col = text_line.Split(',');
if(x==0)
{for(int i=0;i<=data_col.Count()-1;i++)
{
my_datatable.Columns.Add(data_col[i]);
}
x++;
}
else
{
my_datatable.Rows.Add(data_col);
}
// MessageBox.Show(data_col[6]);
}
my_gridview.DataSource = my_datatable;
this.Controls.Add(my_gridview);
}
}
}
Try this...
Create a class to hold the values like...
public class GraphsData
{
public double XAxis { get; set; }
public double YAxis { get; set; }
}
Then call the following method which will produce the result pasted below.
public static void CreatGraph()
{
var raw_txt = System.IO.File.ReadAllLines(#"D:\\Projects\\GraphData.csv");
var v2 = from p in raw_txt.Skip(1)
select new GraphsData
{
XAxis = double.Parse((p.Split(','))[7]),
YAxis = double.Parse((p.Split(','))[8])
};
foreach (var item in v2)
{
Console.WriteLine(item.XAxis + " | " + item.YAxis);
}
}
This will produce following output
-0.2248319 | 0.0066
-0.2264814 | 0.0088
-0.2322548 | 0.0088
-0.2583174 | 0.0088
IMP
Your CSV is not correctly formed. In the last line, notice the 2 commas, which may produce wrong result.
UPDATE TO CREATE GRAPH
public void CreatGraph()
{
var raw_txt = System.IO.File.ReadAllLines(#"D:\\GraphData.csv");
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("x_axis");
dt.Columns.Add("y_axis");
DataTable myData = raw_txt.Skip(1)
.Select(x =>
{
var row = dt.NewRow();
row.SetField<string>("x_axis", x.Split(',')[7]);
row.SetField<string>("y_axis", x.Split(',')[8]);
return row;
}).CopyToDataTable();
chart1.Series.Add("test");
chart1.Series["test"].XValueMember = "x_axis";
chart1.Series["test"].YValueMembers = "y_axis";
chart1.DataSource = myData;
chart1.DataBind();
}
Insert a graph control on form (name of my control is "chart1"). Then on click of a button call this function.