C# Visual Studio - 将 SQL 表数据输出到 Datagridview
Posted
技术标签:
【中文标题】C# Visual Studio - 将 SQL 表数据输出到 Datagridview【英文标题】:C# Visual Studio - Outputting SQL table data to Datagridview 【发布时间】:2016-03-10 13:25:25 【问题描述】:抱歉,如果这已涵盖。我似乎找到的例子比我需要的更复杂
当单击“显示所有记录”按钮时,我试图将 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();
任何帮助将不胜感激,谢谢
【问题讨论】:
【参考方案1】:只需用您的表格填写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;
【讨论】:
您好 SeM,感谢您的快速回复。它给了我一个错误错误 1 找不到类型或命名空间名称“DataTable”(您是否缺少 using 指令或程序集引用?) h:\visual studio 2013\Projects\WpfApplication4\WpfApplication4\MainWindow.xaml.cs 138 13 WpfApplication4 另外,错误 3“System.Windows.Controls.DataGrid”不包含“DataSource”的定义,并且没有接受“System.Windows.Controls”类型的第一个参数的扩展方法“DataSource”。可以找到 DataGrid'(您是否缺少 using 指令或程序集引用?) h:\visual studio 2013\Projects\WpfApplication4\WpfApplication4\MainWindow.xaml.cs 159 31 WpfApplication4 第一个错误:添加引用using System.Data;
第二个:你把你的dataGridView1投成DataGrid
,但是你需要投成DataGridView
您好,第一个效果很好,当我尝试从工具箱中获取 DataGridView 时,它只是被一个被阻止的符号遮住了?不会让我拖放。再次感谢您的所有帮助【参考方案2】:
试试这个....
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;
【讨论】:
【参考方案3】: 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();
试试这个
【讨论】:
以上是关于C# Visual Studio - 将 SQL 表数据输出到 Datagridview的主要内容,如果未能解决你的问题,请参考以下文章
ASP.NET 本地 SQL Server 数据库 C# gridview 数据绑定 Visual Studio 2013
visual studio2017使用c#删除SQL数据库里的一行
如何使用 Microsoft Visual Studio 将查询插入到 C# 中的另一个查询中?
从 Visual Studio C# 和 SQL Compact(连接、选择、插入)开始?