1

I was wondering if it is possible for the update button to save the changes made in the table. I wrote this code but I have no idea how it could possibly work

This is the code i wrote for the update button:

string conString = "Data Source=MIRANDA-PC;Initial Catalog=Futebol do Rosa;Integrated Security=True";
SqlConnection con = new SqlConnection(conString);
string selectSql = "Update Players$ set Player Name='" + dataGridView2.Text + "";
SqlCommand cmd = new SqlCommand(selectSql, con);
con.Open();

This is the table I want to update the values in:

enter image description here

4 Answers 4

4

Well, you just need to execute your query with ExecuteNonQuery.

But more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.

Also use using statement to dispose your SqlConnection and SqlCommand.

And if your table or column names more than one word, you need to use them with [] as [Player Name]. And honestly, it is a little bit weird to use $ sign in a table name.

using(SqlConnection con = new SqlConnection(conString))
using(SqlCommand cmd = con.CreateCommand())
{
    cmd.CommandText = "Update Players$ set [Player Name] = @name";
    cmd.Parameters.Add("@name", SqlDbType.NVarChar, 16).Value = dataGridView2.Text;
    con.Open();
    cmd.ExecuteNonQuery();
}
Sign up to request clarification or add additional context in comments.

Comments

1

You have to execute your SQL query with your db object.

dbinstance.ExecuteSqlCommand(string sqlcommand, object[] params);

This method is both for DDL and DML. you can also use ExecuteNonQuery method.

Comments

0
 cmd.CommandText = "Update Players$ set [Player Name] = @Playername";
    cmd.Parameters.Add("@Playername", SqlDbType.NVarChar, 16).Value = dataGridView2.Text;
    con.Open();
    cmd.ExecuteNonQuery();

Comments

0

The best solution (if possible) to to convert your DAL (Data Access Layer) to Entity-framework based, instead of writing your own SQL queries. This is safe-by-design and never is vulnerable to SQL Injection of any kind. Here is some mockup code:

using (AppEntities currDb = new AppEntities)
{
    Players PlayerToEdit =
    from player in currDb.Players
    where player.PlayerID == lngPlayerID
    select player.First();

    PlayerToEdit.PlayerName = dataGridView2.Text;
    currDb.SaveChanges();
}

You can read about it some more here: https://msdn.microsoft.com/en-us/data/ef.aspx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.