locked
SQLConnection RRS feed

  • Question

  • Now I want to connect my C#/XAML code to my sqlserver database and get the max id in the stock table.

    There's another problem that I hadn't made any Datasets or Connectionstrings through visual studio and when I try to .. I don't find my server while creating new connection for the new dataset, actually it's a null list.

    Here's my code

    int maxstockid; //Identify the maximum ID of current Stocks
                //Command to Get the maximum stock ID.
                string queryString = "select max (Inventory_ID) from dbo.Stocks;";
                using (SqlConnection connection = new SqlConnection("Data Source = MRBRILLIANTPC; Initial Catalog = AGDB; Integrated Security = True"))
                {
                    SqlCommand command = new SqlCommand( queryString, connection);
                    connection.Open();
                    SqlDataReader reader = command.ExecuteReader();
                    try
                    {
                        while (reader.Read())
                        {
                            maxstockid =  int.Parse(reader[1].ToString());
                        }
                    }
                    finally
                    {
                        // Always call Close when done reading.
                        reader.Close();
                    }
                }

    Friday, April 29, 2016 12:54 PM

Answers

  • XAML/WPF was desinged from ground up with the MVVM pattern in mind. You can work without it, but all those nice solutions won't work. I wrote a short introduction back in the days:
    Let's talk about MVVM

    Please put your code into codeblock (7th formating option).
    Also give us the excact line of the exception, it's type, it's message and the stacktrace.

    Since you only want one value from the DB, just use SQLCommand.ExecuteScalar() with your current Query. If it is not a table, a reader serves no purpose.

    • Proposed as answer by Papy Normand Sunday, May 1, 2016 8:03 PM
    • Marked as answer by Kristin Xie Friday, May 6, 2016 1:26 AM
    Friday, April 29, 2016 2:36 PM