I am a bit new to C# and using DataGridViews, but I was able to connect my database to VS 2022 and display the data in a grid using the default code. I have edited my TableAdapter using the .xsd
and configuring it through the TableAdapter Configuration Wizard. I was able to set my Select and Insert commands here, but the Update and Delete commands seem to be escaping me. When I use the built in functions to save the data back to the DB, it will only work if a new line is added.
To put it simply, I am unable to add/change any information in existing rows, but I can add new rows to the table and update just fine.
When I try to change any existing row's data, I get an error:
Update requires a valid UpdateCommand when passed DataRow collection with modified rows
Now I am assuming this is because the UPDATE SQL query has not been set in the TableAdapter, and when I add a new line, it works fine because it relies on the Insert command, not the Update command.
My idea is to track when a row is changed so that I can create a custom UPDATE query each time, build a SQL command out of it, and then update only that row each time. I have gotten this far, but it doesn't seem to actually update the row at all.
namespace AssetListAccessTool_v1._2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void computersBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.computersBindingSource.EndEdit();
//this.tableAdapterManager.UpdateAll(this.computers);
UpdateRowToDB();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'computers._Computers' table. You can move, or remove it, as needed.
this.computersTableAdapter.Fill(this.computers._Computers);
}
//Tracks for PositionChanged event last row
private DataRow LastDataRow = null;
//Checks if there is a row with changes and writes to Data Base
private void UpdateRowToDB()
{
if (LastDataRow != null && LastDataRow.RowState == DataRowState.Modified)
{
this.computersTableAdapter.Update(LastDataRow);
}
}
private void regionBindingSource_PositionChanged(object sender, EventArgs e)
{
//if the user moves to a new row, check if the last row was changed
BindingSource thisBidingSource = (BindingSource)sender;
DataRow ThisDataRow = ((DataRowView)thisBidingSource.Current).Row;
if (ThisDataRow == LastDataRow)
{
//we need to avoid to write a datarow to the database when it is still processes.
//Otherwise we get a problem with the event handling of the data table
throw new ApplicationException("It seems the" + " PositionChanged event was fired twice for" + " the same row");
}
UpdateRowToDB();
//track the current row for next PositionChanged Event
LastDataRow = ThisDataRow;
}
private void ComputersForm_FormClosed(object sender, FormClosedEventArgs e)
{
UpdateRowToDB();
}
}
}
Please let me know where you see missing gaps or if you need extra info. Any help is appreciated!