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();
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 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));
I am adding records to my database via a windows form. But when ever I add a new record it doesnt update until I close the app and then start again. Even though I think I am telling it to update (Im obv not!!)
Do I need a new varibale to update the database? Im a little stuck.
EDIT: All code on this..
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 MediaManagementSystem
{
public partial class AddMedia : Form
{
//database var
OleDbConnection m_cnADONetConnection = new OleDbConnection();
OleDbDataAdapter m_daDataAdapter;
OleDbDataAdapter m_cbCommandBuilder;
DataTable m_dtMedia = new DataTable();
int m_rowPosition = 0;
public AddMedia()
{
InitializeComponent();
}
private void BrowseButton_Click(object sender, EventArgs e)
{
//load up file dialog and find media
if (addFileDialog.ShowDialog() == DialogResult.OK)
{
//add media file name to file path text box
txtFilePath.Text = addFileDialog.FileName;
}
}
private void CancelButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void AddButton_Click(object sender, EventArgs e)
{
//add the new record to the database
DataRow drNewRow = m_dtMedia.NewRow();
drNewRow["FilePath"] = txtFilePath.Text;
drNewRow["Subject"] = txtSubject.Text;
drNewRow["Title"] = txtTitle.Text;
drNewRow["Keywords"] = txtKeywords.Text;
drNewRow["MediaType"] = AddComboBox.Text;
m_dtMedia.Rows.Add(drNewRow);
m_daDataAdapter.Update(m_dtMedia);
m_rowPosition = m_dtMedia.Rows.Count - 1;
this.ShowCurrentRecord();
this.Close();
}
private void AddMedia_Load(object sender, EventArgs e)
{
//link to the database and conect to database
m_cnADONetConnection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Max\Documents\Visual Studio 2010\Projects\MediaManagementSystem\MediaManagementSystem\bin\Debug\MediaDB.mdb";
m_cnADONetConnection.Open();
OleDbConnection objConnection = new OleDbConnection(m_cnADONetConnection.ConnectionString);
m_daDataAdapter = new OleDbDataAdapter("Select * From Media", m_cnADONetConnection);
OleDbCommandBuilder m_cbCommandBuilder = new OleDbCommandBuilder(m_daDataAdapter);
m_daDataAdapter.Fill(m_dtMedia);
m_daDataAdapter.Update(m_dtMedia);
}
public void ShowCurrentRecord()
{
m_daDataAdapter.Update(m_dtMedia);
if (m_dtMedia.Rows.Count == 0)
{
txtFilePath.Text = "";
txtSubject.Text = "";
txtTitle.Text = "";
txtKeywords.Text = "";
AddComboBox.Text = "";
return;
}
txtFilePath.Text = m_dtMedia.Rows[m_rowPosition]["FilePath"].ToString();
txtSubject.Text = m_dtMedia.Rows[m_rowPosition]["Subject"].ToString();
txtTitle.Text = m_dtMedia.Rows[m_rowPosition]["Title"].ToString();
txtKeywords.Text = m_dtMedia.Rows[m_rowPosition]["Keywords"].ToString();
AddComboBox.Text = m_dtMedia.Rows[m_rowPosition]["MediaType"].ToString();
}
}
}
It would best if you use DataSet and then update the records in it. Finally you need to call AcceptChanges() after the update() command to commit the changes with dataset something as below also reload the data after to enter to get the recent data info:
dataset.AcceptChanges()
After you open AddMedia form from your MAIN form, you need to RALOAD all your records again. Look how the form is doing it when it opens and do the same AFTER you open your AddMedia form ;)
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)