我正在使用内部.mdf数据库,我想存储我正在从CSV读取的数据并显示到数据网格视图中。我已经尝试了一切,无法让数据库正确更新。数据正确地读入datagridview但是当我关闭表单并重新打开它时,数据不会填充到datagridview中。那么如何将更改从datagridview推送回mdf数据库?
private void btnOpenFile_Click(object sender, EventArgs e)
{
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "CSV Files|*.csv";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
string strFileName = openFileDialog1.FileName;
string[] strLines = File.ReadAllLines(strFileName);
string[] strFields;
strFields = strLines[0].Split(new char[] { ',' });
int intCols = 1;
DataTable dt = dsetPCInfo.tblPCInfo;
for (int intL = 1; intL < strLines.GetLength(0); intL++)
{
strFields = strLines[intL].Split(new char[] { ',' });
DataRow Row;
Row = dt.NewRow();
for (int f = 0; f < intCols; f++)
Row[f] = strFields[f];
dt.Rows.Add(Row);
tblPCInfoTableAdapter.Update(dsetPCInfo.tblPCInfo);
}
dgvPCInfo.DataSource = dsetPCInfo.tblPCInfo;
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
private void frmPCInfo_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'dsetPCInfo.tblPCInfo' table. You can move, or remove it, as needed.
//dgvPCInfo.DataSource = dsetPCInfo.tblPCInfo;
}
private void btnSave_Click(object sender, EventArgs e)
{
try
{
this.Validate();
this.tblPCInfoBindingSource.EndEdit();
this.tblPCInfoTableAdapter.Update(this.dsetPCInfo.tblPCInfo);
dsetPCInfo.tblPCInfo.AcceptChanges();
MessageBox.Show("Update Successful");
}
catch (System.Exception ex)
{
MessageBox.Show("Update failed");
}
}