Ahsan Hussain
Ahsan Hussain

Reputation: 982

how to update data from table using C#.net

I've a form opened which is has loaded some sort of data (like username, CNIC, Contact no, etc etc) in Check boxes, now I want to update the data in such manner that I simply change the text in the text boxes and click on the save changes to save it. I've tried it but I am not able to do it in correct manner.

Let me show you how I've coded, the code I did in frmViewformList savechanges button is :

private void btnSaveChanges_Click(object sender, EventArgs e)
{
    string sql;
    string UserName;


    UserName = txtUserName.Text; // saving data loaded on run time to UserName 

    sql = "";
    sql += "UPDATE UserLogin";
    sql += "SET Name = "+ //how to access data I've changed in TextBox after loading +"";
    sql += "WHERE Name= " + //how to access data which was in text box right after loading + "";  //
}

I am a bit confused about how to refer to data, like the name already in the text box or the name which I have changed and how to write it in SQL query...

This question is a bit confusing, I know. Let me explain; the form is loaded, there are text boxes which is being populated with the data in database on load event, I change the data in text boxes and save on click so that the update query runs and changes the data in database as well. I'm not able to create logic here how to do this, can any one help me out, I am sorry I am a new developer of C# that's why I am a bit confused.

Upvotes: 0

Views: 2694

Answers (3)

Amicable
Amicable

Reputation: 3101

You should use Sql Parameters in order to avoid SQL Injection which could leave your database vulnerable to malicious exploitation.

It's a good idea to separate the logic for performing the update to the logic where you create your query so you don't have to repeat code and so that you can maintain your code easier.

Here is an example you can reference:

public void DoWork()
{
    // Build Query Use @Name Parameters instead of direct values to prevent SQL Injection
    StringBuilder sql = new StringBuilder();
    sql.Append("UPDATE UserLogin");
    sql.Append("SET Name = @UpdatedName");
    sql.Append("WHERE Name = @Name");

    // Create parameters with the value you want to pass to SQL
    SqlParameter name = new SqlParameter("@Name", "whatEverOldNameWas");
    SqlParameter updatedName = new SqlParameter("@UpdatedName", txtUserName.Text);

    Update(sql.ToString(), new [] { name, updatedName });
}

private static readonly string connectionString   = "Your connection string"
private static readonly DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient");

public static int Update(string sql, SqlParameter[] parameters)
{
    try
    {
        using (DbConnection connection = factory.CreateConnection())
        {
            connection.ConnectionString = connectionString;
            using (DbCommand command = factory.CreateCommand())
            {
                command.Connection  = connection;
                command.CommandText = sql;

                foreach (var parameter in parameters)
                {
                    if (parameter != null)
                        command.Parameters.Add(parameter);
                }

                connection.Open();
                return command.ExecuteNonQuery();
            }
        }
    }
    catch (Exception)
    {
        throw;
    }
}

Upvotes: 3

sakura-bloom
sakura-bloom

Reputation: 4594

The following is a code snippet to insert data into database using ADO.NET and assuming SQL Server database.

At the top of your .cs file you should have.

using System.Data.SqlClient;  // for sql server for other data bases you should use OleClient instead.

And inside your button click event you could put the following.

    // to know how to get the right connection string please check this site: http://www.connectionstrings.com
    string connString = "database connection string here";

    using (SqlConnection con = new SqlConnection(connString)) 
    {
        con.Open();
        //insert text into db
        string sql_insert = "INSERT INTO ....."; // Use parameters here.
        SqlCommand cmd_insert = new SqlCommand(sql_insert, con);
        int rowsAffected = cmd_insert.ExecuteNonQuery();    
    }

Hopefully this is enough to get you started.

Upvotes: 0

Rob G
Rob G

Reputation: 3526

You will want to strip all ', ", and ` characters out of your input so that people can't inject SQL. When you do SET Name = " +, you'll want to actually wrap whatever you're including in quotes because it's a string: SET Name = '" + UserName "' " +...

This is probably best done using

string.Format("UPDATE UserLogin SET Name = '{0}' WHERE Name = '{1}'", UserName, FormerUserName);

Then you will execute your query by using System.Data.SqlClient; and then work with SqlConnection to establish a connection to the server, and execute a SqlCommand of some kind; take a look at: http://www.codeproject.com/Articles/4416/Beginners-guide-to-accessing-SQL-Server-through-C

Upvotes: 0

Related Questions