I'd like to use a polar chart in my test application. I've a data table with a couple of columns where the column with the name of "X" should provide the x value members, the others should be the y value members. I found a tutorial on MSDN but it doesn't really work because the line
chart1.DataBindTable(dt, "X");
won't compile. Any tip is welcome and thank you.
Here is the code :
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 System.Windows.Forms.DataVisualization.Charting;
namespace PolarChartTest_01
{
public partial class Form1 : Form
{
public DataTable dt;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dt.Rows.Clear();
dt.Columns.Clear();
chart1.Series.Clear();
dt.Columns.Add("X", typeof(int));
dt.Columns.Add("Y", typeof(int));
for (int j = 0; j < 7; j++)
{
DataRow dr = dt.NewRow();
dr["X"] = j * 45;
dr["Y"] = j;
dt.Rows.Add(dr);
}
chart1.DataBindTable(dt, "X");
}
}
}
It won't compile because DataTable doesn't implement IEnumerable interface.
Try:
var enumerableTable = (dt as System.ComponentModel.IListSource).GetList();
chart1.DataBindTable(enumerableTable , "X");
This may help you
Write this on page load
chart.DataSource = dataqtableName;
chart.Series["seriesName"].XValueMember = "columNameUwantToBind";
chart.Series["seriesName"].YValueMembers = "columNameUwantToBind";
chart.DataBind();
Another solution might be:
chart1.DataBindTable(dt.DefaultView, "X");
As a bonus, the DataView this returns can be used for sorting and filtering, besides being "databindable".
Related
I’m stuck renaming files.
I have a directory with pdf-files and I want to rename them automatically.
I read a CSV-file and show it in a datagrid with C#.
First column is the old filename and second is the new filename.
The old filenames have numbers before .pdf
The new filenames have numbers, letters and equel signes in the names before .pdf
I tired several code examples but the don't work for me. I’m a newbe. Below the code for creating the datagrid (array). How do I use the rows of the array to search fort he old name and rename it with the new name?
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 VerplaatsenEnHernoemen
{
public partial class Form1 : Form
{
DataGridView my_datagridview = new DataGridView();
DataTable my_datatable = new DataTable();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.Size = new Size(750, 500);
my_datagridview.Size = new Size(600, 400);
my_datagridview.Location = new Point(5, 5);
string[] raw_text = System.IO.File.ReadAllLines("D:\\names.csv");
string[] data_col = null;
int x = 0;
foreach (string text_line in raw_text)
{
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);
}
}
my_datagridview.DataSource = my_datatable;
this.Controls.Add(my_datagridview);
}
}
}
I am having some trouble with this code, I am passing rows from one Grid View to another, but the Grid View is not displaying the data in order.
System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class PuntoVenta : Page
{
DataTable dtband = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dtbind = new DataTable();
dtbind.Columns.Add("Id");
dtbind.Columns.Add("Qnt");
dtbind.Columns.Add("Unit");
dtbind.Columns.Add("Name");
dtbind.Columns.Add("Rel");
dtbind.Columns.Add("Price");
dtbind.Columns.Add("Class");
Session["ss"] = dtbind;
}
}
protected void GridViewA_SelectedIndexChanged(object sender, EventArgs e) {
dtband = (DataTable)Session["ss"];
DataRow dataRow;
dataRow = dtband.NewRow();
int i2 = 0;
for (int i = 0; i < dataRow.Table.Columns.Count; i++)
{
dataRow[i] = GridViewA.SelectedRow.Cells[i2].Text;
i2++;
}
dtband.Rows.Add(dataRow);
GridViewB.DataSource = dtband;
GridViewB.DataBind();
}
}
When I run the code, The GridViewB is populated but its first Column is empty, furthermore, the values that should be displayed in the first column, are displayed in the second column.
You can set DiplayIndex property of Gridview Column,
//Here 1 is index of desired column
datagridview1.Columns["ColumnName"].DisplayIndex = 1;
Add below code in your application
dtbind.Columns.Add("Id");
dtbind.Columns["Id"].DisplayIndex = 0;
dtbind.Columns.Add("Qnt");
dtbind.Columns["Qnt"].DisplayIndex = 1;
//Like onwards
For more info on DisplayIndex property refer This Link
I have a c# form. I have a ComboBox that is the controller. I want to populate labels to display fields from the same row as the selected item in my drop down list.
for example, items is my ComboBox, so if I select an item from my ComboBox, then I want "description" to populate my label, as item ComboBox is selected.
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Sql; //Dir used to connect to sql DB
using System.Data.SqlClient; //Dir used to connect to sql DB
namespace items_Form
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'syteLine_AppDataSet.item' table. You can move, or remove it, as needed.
this.itemTableAdapter.Fill(this.syteLine_AppDataSet.item);
//creating the connection to database.
SqlConnection con_str = new SqlConnection("Data Source=SL1;Initial Catalog=SyteLine_App;Integrated Security=True");
SqlDataAdapter dta_ad = new SqlDataAdapter("SELECT item, description, lead_time, product_code, p_m_t_code, stocked, matl_type, family_code, low_level, days_supply, order_min, order_mult, plan_code,accept_req, shrink_fact, var_lead, decifld1, decifld2, decifld3, datefld, pass_req, order_max, uf_Active, uf_BoughtOff, uf_Old, uf_ProjectEngineer FROM dbo.item", con_str);
DataTable dta_tbl = new DataTable();
dta_ad.Fill(dta_tbl);
for (int i = 0; i < dta_tbl.Rows.Count; i++)
{
cbxItem.Items.Add(dta_tbl.Rows[i]["item"]);
}
}
public void cbxItem_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbxItem.SelectedIndex == -1)
{
label1.Text = string.Empty;
}
else
{
label1.Text = cbxItem.SelectedItem.ToString();
}
}
}
}
I would only retrieve 1 or 2 columns on page load, JUST to show the dropdown.
I would do a second query in the cbxItem_SelectedIndexChanged method passing in the selected value:
DataTable dt = SomeFunctionThatGetsTheDataForTheSelectedValue(cbxItem.SelectedValue)
lblDescription = dt.Rows[0]["Description"];
I have created a data table using disconnected class, also created the data set,xml file, now I want to load that table in a grid. I wrote all my code under program.cs, but when I tried to access the data set object from the form load method, the data set object is not recognized. The code is here:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Data;
using System.IO;
namespace DisconnectedClassDemo
{
public class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
DataTable studentInfo = new DataTable("studentinfo");
DataColumn StudentID = new DataColumn("studentID");
StudentID.DataType = typeof(int);
StudentID.Caption="StudentID";
StudentID.AutoIncrement = true;
StudentID.AutoIncrementSeed = 1;
StudentID.AutoIncrementStep = 1;
DataColumn Name = new DataColumn("StudentName", typeof(string));
Name.MaxLength = 50;
Name.AllowDBNull = false;
Name.Caption = "StudentName";
DataColumn Roll = new DataColumn("StudentRoll", typeof(int));
Roll.Caption = "StudnetRoll";
studentInfo.Columns.Add(StudentID);
studentInfo.Columns.Add(Name);
studentInfo.Columns.Add(Roll);
studentInfo.PrimaryKey = new DataColumn[] { StudentID };
//DataRow rowobj = studentInfo.NewRow();
//rowobj["studentName"] = "Badhon";
//rowobj["studentRoll"] = "004";
//studentInfo.Rows.Add(rowobj);
DataSet ds = new DataSet("dataset");
ds.Tables.Add(studentInfo);
ds.WriteXmlSchema("D:\\Student.xsd");
ds.WriteXml("D:\\student.xml");
ds.ReadXmlSchema("d:\\student.xsd");
ds.ReadXml("D:\\student.xml");
}
}
}
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 System.IO;
namespace DisconnectedClassDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//dataGridView1.DataSource=
//dataGridView1.DataMember=
}
}
}
Why are you writing the data set to the file system? Aren't you trying to create an in memory dataset and the access that dataset? Try declaring the dataset on the form itself.
Try this:
DataTable studentInfo = new DataTable("studentinfo");
DataColumn StudentID = new DataColumn("studentID");
StudentID.DataType = typeof(int);
StudentID.Caption = "StudentID";
StudentID.AutoIncrement = true;
StudentID.AutoIncrementSeed = 1;
StudentID.AutoIncrementStep = 1;
DataColumn Name = new DataColumn("StudentName", typeof(string));
Name.MaxLength = 50;
Name.AllowDBNull = false;
Name.Caption = "StudentName";
DataColumn Roll = new DataColumn("StudentRoll", typeof(int));
Roll.Caption = "StudnetRoll";
studentInfo.Columns.Add(StudentID);
studentInfo.Columns.Add(Name);
studentInfo.Columns.Add(Roll);
studentInfo.PrimaryKey = new DataColumn[] { StudentID };
DataSet ds = new DataSet("dataset");
ds.Tables.Add(studentInfo);
var rw = ds.Tables[0].NewRow();
rw["StudentName"] = "Badhon";
rw["StudentRoll"] = 004;
ds.Tables[0].Rows.Add(rw);
MessageBox.Show(ds.Tables[0].Rows.Count.ToString());
dataGridView1.DataSource = ds.Tables[0];
You are creating the form before the dataset
Application.Run(new Form1());
Move this line down below the creation of the dataset.
Like Preet Sangha says, you're creating and running the form before the dataset.
Also, the dataset is a local variable inside your Main method so the form class has no knowledge of it. Try creating the dataset inside the form or passing it as a parameter to the constructor:
public class Form1(Dataset ds) : Form
...
...
Application.Run(new Form1(ds));
Im trying to implement a search function for when the user enters text in a textbox (tbPartNum) and then clicks the "Find" button it then searches the cells in dataGridView1 and once its found it, it highlights the entire row yellow. My code is as follows which obviously doesn't work it throws an error which states:
"NullReferenceException was unhandled"
and underneath it:
"Object reference not set to an instance of an object."
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 System.Data.OleDb;
namespace GBstock
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// populate the dataGridView with the Excel File
string connectionString = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", #"C:\Documents and Settings\rghumra\Desktop\Visual Studio\GBstock\GBstock\bin\Debug\FORM TEST.xlsx");
string query = String.Format("select * from [{0}$]", "Sheet1");
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
dataGridView1.DataSource = dataSet.Tables[0];
// populates the comboBox (cbSuppList) with all column headers
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
cbSuppList.Items.Add(col.HeaderText);
}
}
private void btnFind_Click(object sender, EventArgs e)
{
// Code to search the alphanumneric Part Number (in Column1 header called "PART NUMBER") and highlihgt the row
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells["PART NUMBER"].Value.ToString().Equals(tbPartNum.Text))
{
dataGridView1.Rows[row.Index].DefaultCellStyle.BackColor = Color.Yellow;
}
}
}
private void fileToolStripMenuItem_Click(object sender, EventArgs e)
{
Instructions instructionForm = new Instructions();
instructionForm.Show();
}
private void partToolStripMenuItem_Click(object sender, EventArgs e)
{
NewPart newPartForm = new NewPart();
newPartForm.Show();
}
private void supplierToolStripMenuItem_Click(object sender, EventArgs e)
{
NewSupplier newSuppForm = new NewSupplier();
newSuppForm.Show();
}
}
}
NullReferenceException you're experiencing most likely comes from the fact that your grid contains null cell values, which get scanned in the foreach of your find handler. Try changing the following line:
if (row.Cells["PART NUMBER"].Value.ToString().Equals(tbPartNum.Text))
To
var cellValue = row.Cells["PART NUMBER"].Value;
if (cellValue != null && cellValue.ToString() == tbPartNum.Text)