I’m having some difficulties understanding how databases and SQL works. I’m trying to update a certain row in my database. I can remove a row, but when i use the InsertAt function, it is always appended to the end of my database. Also, it’s assigned a new identifier key.
I would like to just edit what is already in there. No need for a new key, and I would like the edited row to stay where it was.
I’ve tried to strip down the code to show the the problem.
public partial class MainWindow : Window
{
System.Data.SqlClient.SqlConnection con;
System.Data.SqlClient.SqlDataAdapter da;
DataSet sessions;
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
con = new System.Data.SqlClient.SqlConnection();
sessions = new DataSet();
con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\md\\PokerDataBase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
con.Open();
string sql = "SELECT * From Sessions";
da = new System.Data.SqlClient.SqlDataAdapter(sql, con);
da.Fill(sessions, "Sessions");
con.Close();
System.Data.SqlClient.SqlCommandBuilder cb;
cb = new System.Data.SqlClient.SqlCommandBuilder(da);
DataTable dt = sessions.Tables["Sessions"];
DataRow table = sessions.Tables["Sessions"].NewRow();
table[0] = "Some Data";
table[1] = "Some Data";
table[2] = "Some Data";
table[3] = 2;
table[4] = 3;
sessions.Tables["Sessions"].Rows[2].Delete();
sessions.Tables["Sessions"].Rows.InsertAt(table, 2);
da.Update(sessions, "Sessions");
}
}
Could anyone help me figure out what I’m doing wrong?
Error
You are creating a new row using
This will add new row to you database, it’s not going to update a row.
Solution
To update a row you need to select that specific row, something like:
then modify the row data and then update
da.This will the update existing row in your database.