public partial class Form1 : Form
{
OleDbConnection baglanti = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Burak YEŞİLYURT\Desktop\secret.accdb");
OleDbCommand komutcu;
OleDbDataAdapter adpt;
DataSet ds;
public Form1()
{
InitializeComponent();
baglanti.Open();
OleDbCommand komutcu = new OleDbCommand("SELECT * FROM todo", baglanti);
OleDbDataAdapter adpt = new OleDbDataAdapter(komutcu);
DataSet ds = new DataSet();
adpt.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
private void button1_Click(object sender, EventArgs e)
{
OleDbCommandBuilder komut = new OleDbCommandBuilder(adpt);
DataSet yeni = new DataSet();
yeni = ds.GetChanges(DataRowState.Modified); //here i get the error
adpt.Update(yeni.Tables[0]);
}
}
当我调试程序时,我在yeni = ds.GetChanges(DataRowState.Modified);
“对象引用未设置为对象的实例。”
我的目的:填写DataGridView
和用户编辑单元格后,保存单元格中的更改。
我无法解决这个问题。欢迎任何帮助。
感谢。
答案 0 :(得分:2)
修复构造函数
public Form1()
{
InitializeComponent();
baglanti.Open();
OleDbCommand komutcu = new OleDbCommand("SELECT * FROM todo", baglanti);
OleDbDataAdapter adpt = new OleDbDataAdapter(komutcu);
this.ds = new DataSet(); //there was an error in this line
..
}
您在构造函数中创建了DataSet
的本地实例,而您忘记保存对类变量ds
的引用。然后在button1_Click
中,您尝试访问未初始化的字段ds
(其值为null
)。
所以,而不是这一行
DataSet ds = new DataSet();
你应该写
this.ds = new DataSet();
答案 1 :(得分:0)
你已经定义了两次数据集oledbcommand和oldbDataAdapter所以它无法正常工作
public partial class Form1 : Form
{
OleDbConnection baglanti = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Burak YEŞİLYURT\Desktop\secret.accdb");
OleDbCommand komutcu;
OleDbDataAdapter adpt;
DataSet ds;
public Form1()
{
InitializeComponent();
baglanti.Open();
komutcu = new OleDbCommand("SELECT * FROM todo", baglanti);
adpt = new OleDbDataAdapter(komutcu);
ds = new DataSet();
adpt.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
private void button1_Click(object sender, EventArgs e)
{
OleDbCommandBuilder komut = new OleDbCommandBuilder(adpt);
DataSet yeni = new DataSet();
yeni = ds.GetChanges(DataRowState.Modified); //here i get the error
adpt.Update(yeni.Tables[0]);
}
}
答案 2 :(得分:0)
OleDbConnection baglanti = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Burak YEŞİLYURT\Desktop\secret.accdb");
OleDbCommand komutcu;
OleDbDataAdapter adpt;
DataSet ds = new DataSet();
public Form1()
{
InitializeComponent();
baglanti.Open();
OleDbCommand komutcu = new OleDbCommand("SELECT * FROM todo", baglanti);
OleDbDataAdapter adpt = new OleDbDataAdapter(komutcu);
//DataSet ds = new DataSet();
adpt.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}