-2

Thanks to Nate M. I've got this running, using the second part of code, and some schooling in SQL Server (it's my first day) So it's solved. Thank you everyone for the help.

I can't figure this out. I'm using Visual Studio 2015, SQL Server 2014, that works, but I can't figure out how to insert data on the click of a button. I've tried stuff on MSDN, nothing works, they have about 100 different ways. I'm confused. Here's what I've got.

private void btnTheWorst_Click(object sender, EventArgs e)
{
    lblMood.Text = "The Worst :(";
    lblMood.ForeColor = System.Drawing.Color.Navy;

    SqlConnection cmood = new SqlConnection("my connection string"); {

    cmood.Rows.Add(new Object[] { 1, "Smith" });
}

This is where I get the error.

SqlConnection does not contain a definition for 'Rows' and no extension method 'Rows' accepting a first argument of type 'SqlConnection' could be found.

sandorfalot
  • 1,042
  • 1
  • 10
  • 19
  • 4
    You're really going to want to start with an introductory tutorial on ADO.NET. Interacting with a database is covered by many, many tutorials and there are *countless* examples online. As the error states, a `SqlConnection` object doesn't have a property called `Rows`. Never has. – David Mar 09 '16 at 20:44
  • Possible duplicate of [Inserting values into a SQL Server database using ado.net via C#](http://stackoverflow.com/questions/13573380/inserting-values-into-a-sql-server-database-using-ado-net-via-c-sharp) – vittore Mar 09 '16 at 20:46
  • I was using code off the MSDN website... but none of their methods have worked. – sandorfalot Mar 09 '16 at 21:27
  • "I'm using Visual Studio 2015, SQL Server 2014, that works..." thanks GOD! If that didn't work, we all would be in trouble. I hope you read and laugh – T.S. Mar 09 '16 at 23:06
  • I'm voting to close this question as off-topic because it is not based on issue but rather on lack of research. Quick google "inserting rows sql server c#" would answer this – T.S. Mar 09 '16 at 23:08

2 Answers2

3

The comments are completely correct. There is a particular sequence of events you need to do to interact with a database. I keep a piece of code on a scratch pad because I use it so much which outlines the basic structure of what you need to be doing.

using(var conn = new SqlConnection(<connection string here>))
{
    try
    {
        conn.Open();
        string sql = "<sql query here>";
        using(var cmd = new SqlCommand(sql,conn))
        {
            using(var reader = cmd.ExecuteReader())
            {
                if(reader.HasRows)
                {
                    while(reader.Read())
                    {
                        //Here is where you get your data..
                        int imReadingAnInt = (int)reader["myIntColumnHeader"];
                        string imReadingAString = reader["myStringColumnHeader"].ToString();
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        string err = ex.Message;
    }
}

On inserts:

You can draft a sql insert using the above method, and use cmd.ExecuteNonQuery() to perform the insert. An Example..

using(var conn = new SqlConnection(<connection string here>))
{
    try
    {
        conn.Open();
        string sql = "insert into [table_name] values (@column1Value,@column2Value,...);";
        using(var cmd = new SqlCommand(sql,conn))
        {
            cmd.Parameters.AddWithValue("@column1Value",1);//Presuming column 1 is an int
            cmd.Parameters.AddWithValue("@column2Value","Smith"); //Presuming column 2 is a varchar (string)
            cmd.ExecuteNonQuery();
        }
    }
    catch (Exception ex)
    {
        string err = ex.Message;
    }
}

Note the above code uses paramaterization (sp) to prevent SQL injection. You could hard code the values into the SQL Query string, but it is not considered best practices from a security standpoint.

W3 Schools SQL Insert

My brain keeps churning on this.. Just a note on the fundamental concepts here. With the Objects SqlConnection, SqlCommand etc, you are not actually establishing direct access to the database (ie you can't just go grab a row and manually edit it). Instead, you are setting up a connection through which you can perform SQL queries which are a well structured method of reading and editing the database. There is of course tons of information out there on how to construct said queries, so once you understand the purpose of the C# objects in question, accessing and changing a database will make a lot more sense.

Nate M.
  • 822
  • 6
  • 14
  • Thank you, the second fix worked. I had been playing with Insert INTO, but screwed it up. This works. – sandorfalot Mar 09 '16 at 21:20
  • Glad to hear you worked the problem out. – Nate M. Mar 09 '16 at 21:21
  • Well, it's not inserting into the DB.. Playing with that. Looking at the .xsd file, it's not updating, but no errors are coming up. – sandorfalot Mar 09 '16 at 21:24
  • hrm.. well, inserting data may be a locked down privilege, depending on how your database is configured. I would verify your connection string and make sure your user has appropriate permissions to insert data into the database you are working with. Additionally, make sure your table name is correct, and that when you fill in each column (the area in parentheses) that you fully populate the data. By this, I mean if you have a table with 5 columns, that you are supplying 5 values of appropriate type. Lastly, put a breakpoint in the catch statement and see if it gets hit while debugging. – Nate M. Mar 09 '16 at 21:28
  • Thanks. Going to check my SQL Server settings carefully now. – sandorfalot Mar 09 '16 at 21:34
  • I want to say check security folder > logins > whatever username you are using to log in, right click select properties, then look at user mapping. The user should have a checkbox next to the DB you are wanting to modify. When you left click the DB in question, there should be roles in the bottom pane that enable read / write. I haven't done too much with this so.. might be some other spots but I think thats the key permissions. I'd definitely make sure the code isn't hitting the catch also. Many times you can have an error in your sql statement and it will throw an exception – Nate M. Mar 09 '16 at 21:38
  • This could get complicated. I installed MS SQL Server 2014 from the MS website. I'm not sure what version it is, and I can't figure it out. SQLEXPRESS is running. The database is in the Visual Studio folder, which I gave permissions to. I'm not getting an exception when I run it. – sandorfalot Mar 09 '16 at 21:58
  • I'm just confused. Here's my connection string and insert. using (var conn = new SqlConnection("Data Source=SANDORFALOT\\SQLEXPRESS;Initial Catalog=msdb;Integrated Security=True")) insert into crazyMoods VALUES(1, 1)"; – sandorfalot Mar 09 '16 at 21:59
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/105849/discussion-between-nate-m-and-sandorfalot). – Nate M. Mar 09 '16 at 21:59
0

Check this out, which gives fair knowledge on how to insert data to database. You can check Insert New Records Using Command Objects section https://msdn.microsoft.com/en-us/library/ms233812.aspx

T.Andy
  • 106
  • 4