因为在使用datagridview的时候,vs的服务器资源管理器显示已经连接到sql,但是代码还是不能把数据库中的表显示在datagridview控件上,而且报错是 sa登录失败,但是我确实已经成功连接了sql。所以,新建了一个 【控制台应用程序】,通过try和catch来找到到底是哪个环节出了问题
- 新建 一个 【控制台应用程序】

- 代码是否成功连接上了数据库
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//用代码连接数据库
// 第一种连接,sql server的Windows身份验证
//string ConStr = "server=.;database=StudentStatusDB;Trusted_Connection=SSPI";
//第二种连接,sql server身份验证
try
{
string ConStr = "server=.;database=test;uid=sa;pwd=123456";
SqlConnection conn = new SqlConnection(ConStr);
conn.Open();
Console.WriteLine("Connected Sql");
}
catch (Exception ex)
{
Console.WriteLine("Error is "+ex+ "Error" );
}
Console.ReadLine();
}
}
}
如果try里连接上了就在控制台上显示Connected Sql, 如果try里失败了,那就进入catch输出错误类型Error。(最开始接触c#的时候不是很懂为什么有些例程要用try catch语句,觉得没必要,现在才发现try catch语句还挺有用的)
运行之后显示如下,说明连接成功

到这里就能说明,连接部分没问题,那么问题应该是对数据库表的查询和调用,接下来排除查询和调用。
2. 是否可以查询到数据库的表
功能:查询表Table_1 的Name列的第一行的数据,返回,显示在控制台,如果没有查询到,就报错
代码:
try
{
//
string ConStr = "server=.;database=test;uid=sa;pwd=123456";
SqlConnection conn = new SqlConnection(ConStr);
conn.Open();
Console.WriteLine("Connected Sql");
////返回Age列的第一个值 12
//SqlCommand cmd = new SqlCommand("select Age from Table_1", conn);
//int count = (int)cmd.ExecuteScalar();
//string t = Convert.ToString(count);
//Console.WriteLine("return" + t);
//返回Name列第一个值 Abb
SqlCommand cmd = new SqlCommand("select Name from Table_1", conn);
string str = (string)cmd.ExecuteScalar();
Console.WriteLine("return" + str);
}
catch (Exception ex)
{
Console.WriteLine("error"+ex+ "error");
}
Console.ReadLine();
运行结果:

打开SSMS ,查看表Name列的第一个数是不是Abb


所以,查询没问题,
3. 新建一个窗体应用程序

添加datagridview控件
在Form.cs里写入连接查询数据的代码(在此之前同样得先用工具栏里的连接数据库连接sql,服务器资源管理器如之前那样显示),并将表Table_1显示在控件Datagridview上
需要自己添加引用的命名空间namespace
![]()
![]()
代码:
namespace ApplicationSql
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
try
{
string ConStr = "server=.;database=test;uid=sa;pwd=123456";
SqlConnection conn = new SqlConnection(ConStr);
conn.Open();
Console.WriteLine("Connected Sql");
// //整个表显示在控件上
SqlDataAdapter cmd = new SqlDataAdapter("select * from Table_1",conn);
//创建dataset对象
DataSet d = new DataSet();
cmd.Fill(d);
dataGridView1.DataSource = d.Tables[0].DefaultView;
}
catch
{
}
}
}
}
运行结果:

结束。
这篇博客记录了作者在使用C#的WinForms应用中遇到的问题,即无法将SQL数据库的表显示在DataGridView控件上。作者首先通过创建控制台应用程序测试数据库连接,发现连接没有问题。接着,验证了查询数据库表的能力,确认查询操作正确。最后,在窗体应用程序中尝试加载数据到DataGridView,但仍然失败。问题可能在于数据绑定或控件设置。博客强调了try-catch语句在调试中的重要性。
2438

被折叠的 条评论
为什么被折叠?



