简体   繁体   中英

Visual studio not loading data from Microsoft SQL Server Management Studio

I am try to retrieve the data from my table which I created on my SSMS. I created a list box in a form of visual studio, and I try to display the data from database, but it doesn't send anything when I try to load up the program. The database is seems to look good. That problem appear when I try to retrieve the movie_id and movie_title. Here is my code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DataBase
{
public partial class Form1 : Form
{
    DataTable dt = new DataTable();
    public void LoadData()
    {
        SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;"+
            "Initial Catalog=online_tv;Integrated Security=SSPI;");
        SqlCommand cmd = new SqlCommand("SELECT movie.* FROM movie", conn);
        SqlDataAdapter sa = new SqlDataAdapter(cmd);
        conn.Open();
        sa.Fill(dt);
        conn.Close();
        sa.Dispose();
        cmd.Dispose();
        conn.Dispose();
    }

    public class MyMovie
    {
        public int id;
        public string title;
        public override string ToString()
        {
            return title;
        }
    }

    public void ShowMovies()
    {
        int i;
        for (i = 0; i < dt.Rows.Count; i++)
        {
            MyMovie movie = new MyMovie();
            movie.id = Convert.ToInt32(dt.Rows[i]["movie_id"]);
            movie.title = Convert.ToString(dt.Rows[i]["movie_title"]);

            listBox1.Items.Add(movie);
        }
    }

    public Form1()
    {
        InitializeComponent();
    }

    public void Form1_Load(object sender, EventArgs e)
    {
        LoadData();
        ShowMovies();
    }

在此处输入图片说明

There are a bucketload of optimizations to be made here, but I'd like to post an answer that introduces a small but fundamental change that will make your life significantly easier. Nearly every single line of code you've written there, you can get Visual Studio to write for you; just like you get it to write code when you lay out a Form, you can have it do all of this data access stuff too, and if you've managed to get SSMS connected, then getting VS connected is virtually the same process and will mean it just works:

  • Add a DataSet type of file to your project, and open it
  • Right click on it and choose add a TableAdapter - this is like a DataAdapter on steroids
  • Add a new conenction - the dialog is virtually the same as SSMS so you should be able to connect your DB without any hassle
  • Say you want to write "a query that returns rows" - put SELECT * FROM movie in
  • Finish the wizard
  • Right click the "Fill" line in the tableadapter and choose Preview Data, hit the button and see your data. If you see no data, you connected to a database that is devoid of data
  • Go to your form, open the Data Sources window (View menu.. Other Windows)
  • Drag the movie node out of the Data Sources window and onto the form
  • Run the app

You'll see your data

Now that you've scratched the surface of this, you can start playing with other stuff. Throw the DataTable dt away; you won't need it. Your form has a dataset object on it, that contains a Movie property that is a MovieDataTable - a subclass of datatable that you can access in a more logical and modern manner than via "string column names" - you say, for example, yourdatasetnamehere.Movies[0].movie_title and it's already a string (time to swap your column names to PascalCase by the way) rather than somedatatable.Rows[0]["movie_title"].ToString()

To show your movies in a listbox,

  • add a listbox to the form
  • set the DataSource property to be the movieBindingSource
  • Set the DisplayMember to be movie_title

(All this is done visually on the forms designer, not in code)

You can consider throwing the Movie POCO away too; a MovieDataRow is created by the dataset generator; it has all the properties of your movie, in a strongly typed fashion, just like your POCO does. The tableadapter downloads the DB data and turns it into strongly typed MovieDataRow objects for you, meaning you can throw all the POCO mapping stuff in ShowMovies away too, and finally, databinding your listbox means you can toss out the bit where you build its items collection manually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM