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));
Related
I use OPC-UA SDK of treager. I have variable created be PLC S7-1200
.
It displayed the value on Console.WriteLine, but I cant show it on listView
.
Can someone help me show the variable changes on listView1 ?
If I note listView1.Items.Add(itm); It will show that
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Opc.Ua.Client;
using Opc.UaFx;
using Opc.UaFx.Client;
namespace Test_OPC
{
public partial class OPCUA : Form
{
private readonly OpcClient client;
public static OpcValue isRunning;
string[] arr = new string[4];
ListViewItem itm;
public OPCUA()
: base()
{
this.client = new OpcClient("opc.tcp://192.168.1.200:4840");
InitializeComponent();
}
private void OPCUA_Load(object sender, EventArgs e)
{
client.Connect();
OpcSubscription subscription = client.SubscribeDataChange("ns=4;i=15",HandleDataChanged);
//ListViewItem listView1 = new ListViewItem();
//ListViewItem itemHienThi = new ListViewItem();
//Add Item vào ListView
arr[0] = "01";
arr[1] = "100";
arr[2] = "10";
itm = new ListViewItem(arr);
listView1.Items.Add(itm);
}
private void HandleDataChanged(object sender,OpcDataChangeReceivedEventArgs e)
{
OpcMonitoredItem item = (OpcMonitoredItem)sender;
//Add the attribute name/value to the list view.
arr[0] = item.NodeId.ToString();
arr[1] = e.Item.Value.ToString();
itm = new ListViewItem(arr);
listView1.Items.Add(itm);
Console.WriteLine("Data Change from NodeId '{0}': {1}",item.NodeId,e.Item.Value);
}
}
}
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'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".
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)
I have two datagridview inside a winform. I need to reload with a button the second datagridview 2 when I change the data inside the datagridview1.
datagriview1 modified ---> click button update ---> reload datagridview 2.
it's not working I don't know why.
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 WindowsFormsApplication6
{
public partial class Form1 : Form
{
DataSet ds = new DataSet();
DataSet dv = new DataSet();
public Form1()
{
InitializeComponent();
FileStream stream = new FileStream("file.xml",FileMode.Open);
ds.ReadXml(stream);
stream.Close();
dataGridView1.DataSource = ds.Tables[0];
FileStream stream1 = new FileStream("file.xml", FileMode.Open);
dv.ReadXml(stream1);
stream1.Close();
dataGridView2.DataSource = dv.Tables[0];
//DateTime Today = DateTime.Now;
}
private void updateData_Click(object sender, EventArgs e)
{
ds.WriteXml("file.xml");
//reload the datagridview 2 after modification intot the datagridview1
dv.reset();
FileStream stream1 = new FileStream("file.xml", FileMode.Open);
dv.ReadXml(stream1);
stream1.Close();
dataGridView2.DataSource = dv.Tables[0];
dataGridView2.ResetBindings();
}
}
}
There's a ResetBindings function on DataGrid that should do what you want.
dataGridView2.ResetBindings();