繁体   English   中英

C#Visual Studio-将SQL表数据输出到Datagridview

[英]C# Visual Studio - Outputting SQL table data to Datagridview

抱歉,如果已解决。 我似乎发现的例子比我需要的要复杂得多

单击“显示所有记录”按钮时,我试图将SQL表的全部内容输出到DatagridView

我有点麻烦,这是我到目前为止所遇到的

  private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            {

                string query = "select * from student";
                SqlCommand cmd = new SqlCommand(query, con);
                con.Open();


                SqlDataAdapter da = new SqlDataAdapter(cmd);

                da.Fill(DataGridView);
                con.Close();
                da.Dispose();
            }

这是我的所有代码,如果您需要参考

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Text.RegularExpressions;

namespace WpfApplication4
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True");



        public MainWindow()
        {
            InitializeComponent();
            establishConnection();


        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {


            Boolean postSuccess = false;

            if (validation() == true)
            {

                SqlCommand details = new SqlCommand("INSERT INTO Student (Firstname, LastName, MatriculationNo, GradeOne, GradeTwo, GradeThree) VALUES (@FirstName, @LastName, @MatriculationNo, @GradeOne, @GradeTwo, @GradeThree)", con);
                details.Parameters.AddWithValue("@FirstName", firstnameTextbox.Text);
                details.Parameters.AddWithValue("@LastName", lastnameTextbox.Text);
                details.Parameters.AddWithValue("@MatriculationNo", matriculationnoTextbox.Text);
                details.Parameters.AddWithValue("@GradeOne", Component1Textbox.Text);
                details.Parameters.AddWithValue("@GradeTwo", Component2Textbox.Text);
                details.Parameters.AddWithValue("@GradeThree", Component3Textbox.Text);
                con.Open();
                details.ExecuteNonQuery();
                postSuccess = true;

                if (postSuccess)
                {
                    MessageBox.Show("Details entered succesfully!");
                    firstnameTextbox.Clear();
                    lastnameTextbox.Clear();
                    matriculationnoTextbox.Clear();
                    Component1Textbox.Clear();
                    Component2Textbox.Clear();
                    Component3Textbox.Clear();

                }

                else
                {
                    MessageBox.Show("Data not entered succesfully, please check DB connection");
                }
                con.Close();
            }

        }
        private void establishConnection()
        {
            try
            {
                con.Open();
                System.Diagnostics.Debug.Print("Connected to SQL database");

                connectionLabel.Content = "Connected to SQL Database";

                con.Close();
            }
            catch (Exception)
            {

                connectionLabel.Content = "not connected to sql database";
            }
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            firstnameTextbox.Clear();  //Clears the first name textbox
            lastnameTextbox.Clear();   //Clears the last name textbox
            matriculationnoTextbox.Clear(); //Clears the Matriculation Number textbox
            Component1Textbox.Clear(); //Clears the component one textbox
            Component2Textbox.Clear(); //Clears the component two textbox
            Component3Textbox.Clear(); //Clears the component three textbox
        }


        private Boolean validation()
        {
            if (!Regex.Match(firstnameTextbox.Text, "^[A-Z][a-zA-Z]*$").Success)
            {
                MessageBox.Show("Please Enter a valid First Name");
                firstnameTextbox.Clear();
                return false;
            }
            else
            {
                return true;
            }

        }

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            con.Open(); 
            string sql = @"DELETE FROM Student;"; //Deleting all from Student table
            SqlCommand purge = new SqlCommand(sql, con);
            MessageBox.Show("Are you sure you want to purge the entire contents of the database?"); //Prompting user to make sure they want to delete
            purge.ExecuteNonQuery(); //Execute purge query


        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            {

                string query = "select * from student";
                SqlCommand cmd = new SqlCommand(query, con);
                con.Open();

                // create data adapter
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                // this will query your database and return the result to your datatable
                da.Fill(DataGridView);
                con.Close();
                da.Dispose();
            }









        }





    }
}

任何帮助将不胜感激,谢谢

尝试这个....

    private void Button_Click_2(object sender, EventArgs e)
    {
        string query = "select * from student";
        SqlCommand cmd = new SqlCommand(query, con);
        con.Open();

        DataTable dt = new DataTable();

        // create data adapter
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        // this will query your database and return the result to your datatable
        da.Fill(dt);
        con.Close();
        da.Dispose();


        dataGridView1.DataSource = dt;
    }
        MySqlCommand command = conn.CreateCommand();
        command.CommandText = "Select * from student";
        try
        {
            con.Open();

            MySqlDataAdapter sda = new MySqlDataAdapter();
            sda.SelectCommand = command;
            DataTable dbdataset = new DataTable();
            sda.Fill(dbdataset);
            BindingSource bSource = new BindingSource();

            bSource.DataSource = dbdataset;
            dataGridView1.DataSource = bSource;
            sda.Update(dbdataset);

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        con.Close();

尝试这个

只需用表填充DataTable并将其绑定到GridView.DataContext

像这样:

首先在XAML编辑器中添加DataGrid <DataGrid Name="customDataGrid" ItemsSource="{Binding}">

然后代码后面:

namespace WpfApplication4
{
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            string connectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True";

            public MainWindow()
            {
                InitializeComponent();
            }

            private void button1_Click(object sender, EventArgs e)
            {
                DataTable table = null;
                string query = "select * from student";
                try
                {
                    using (SqlConnection connection = new SqlConnection(this.connectionString))
                    {
                        connection.Open();
                        using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))
                        {
                            table = new DataTable();
                            adapter.Fill(table);
                        }
                    }
                }
                catch (Exception ex)
                {
                    //handle caught exception
                }

                if (table != null)
                {
                    customDataGrid.DataContext = table.DefaultView;
                }
            }
        }
}

绑定部分: customDataGrid.DataContext = table.DefaultView;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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