user3144416
user3144416

Reputation: 55

Problems adding data into a datatable C#

I am working on a school project that includes data-bases. I got the basiscs of SQL programming but I still getting problems. Now I'm stuck on the code that is supposed to add new data into the grid, but it's just not working for some reason.. I tried to find a solution for this problem (as you can see from the code), but nothing worked.. Here is the code.

private void InsertData()
    {
        string NewCode = GenerateCode();
        string NewLetter = txtNewData.Text;

        try
        {
            Connection.Open();
            string AddData = "INSERT INTO DictionaryTest (BinNumber,Letter) VALUE (@NewCode,@NewLetter)";
            //SqlDataAdapter DataIns = new SqlDataAdapter(AddData, Connection);
            SqlCommand DataAdd = new SqlCommand(AddData, Connection);
            DataAdd.Parameters.AddWithValue("@NewCode", "00" + NewCode);
            DataAdd.Parameters.AddWithValue("@NewLetter", NewLetter);
            //DataAdd.ExecuteNonQuery();
            //Connection.Open();
            //var dt = new DataTable();
            //DataIns.Fill(dt);
            Connection.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

The data that I'm getting from the fucntion GenerateCode() is ok, I tried to insert it into a text box and it was right.

Upvotes: 1

Views: 70

Answers (2)

Ross Dargan
Ross Dargan

Reputation: 6021

You need to execute the sqlcommand

try adding this before the close

DataAdd.ExecuteNonQuery();

But beware SqlConnection, and SqlCommand both implement IDisposable, so you should be calling .Dispose on them (or more preferably using a using statement).

This tends to be how I write sql queries:

using(SqlConnection connection = new SqlConnection("connection string"))
{
    using(SqlCommand command = new SqlCommand("command",connection);
    {
        //Add params as in your example
        connection.Open();
        command.ExecuteNonQuery(); // Or Execute reader to get results back
        connection.close(); //The using statement will close dispose, which will close the connection so this isn't strictly required.
    }
}

Hope that helps.

Upvotes: 2

Manian Rezaee
Manian Rezaee

Reputation: 1012

change value to values

INSERT INTO DictionaryTest (BinNumber,Letter) VALUES (@NewCode,@NewLetter)

Upvotes: 1

Related Questions