当前位置:编程学习 > C#/ASP.NET >>

C#调用SQL Server数据库

本人有段C#调用SQL Server数据库的代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace ConnectSQLServer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
try
            { 
            string ConStr=@"server=.\SQLEXPRESS;user id=sa;pwd=;database=school";
                SqlConnection con =new SqlConnection (ConStr);
               con.Open();
                string SqlStr="select * from student";
                SqlDataAdapter ada =new SqlDataAdapter(SqlStr ,con);
                DataSet ds=new DataSet();
                ada.Fill(ds);
                this.dataGridView1.DataSource = ds.Tables[0].DefaultView;
                
            }
            catch
            {
            return ;
            }
        }

       
    }
}
数据库为school,数据库中的表为student.现在用这段代码不能将数据库中的数据调出来,请路过的高手帮忙指点指点,不甚感激! --------------------编程问答--------------------  DataSet ds=new DataSet(); 
                ada.Fill(ds.Tables[0]); 
                this.dataGridView1.DataSource = ds.Tables[0].DefaultView; 
不然直接用DataTable --------------------编程问答-------------------- DataTable dt=new DataTable(); 
                ada.Fill(dt); 
                this.dataGridView1.DataSource = dt.DefaultView;
确认下你的数据库连接有问题吗? --------------------编程问答-------------------- 好熟悉的代码啊 现在在复习中~~~ --------------------编程问答--------------------
  SqlDataAdapter ada =new SqlDataAdapter(SqlStr ,con); 
  ada.Fill(ds, "student");
  this.dataGridView1.DataSource = ds.Tables["student"];

这样就可以了 --------------------编程问答-------------------- 怎么个不能掉出来?抛出了异常还是返回0行的数据?具体点 --------------------编程问答-------------------- 没有过报错?那可能是DATAGRIDVIEW1设了固定的格式了~~ --------------------编程问答-------------------- 少了个绑定的方法
this.dataGridView1.databind(); --------------------编程问答-------------------- 数据最终没有绑定到控件上 --------------------编程问答-------------------- 设个断点跟一下,看看你的ds返回内容了没?
建议使用using的写法 --------------------编程问答--------------------
引用 7 楼 petroe 的回复:
少了个绑定的方法
this.dataGridView1.databind();

绑定啊. --------------------编程问答-------------------- 添加个SqlCommand cmd=new SqlCommand(SqlStr,con)
cmd.ExecuteReader();

在绑定。databind(); --------------------编程问答-------------------- 肯定不需要绑定
你加个断点,跟踪一下,看连上数据库没有
,这样的问题一般都这样解决 --------------------编程问答-------------------- this.dataGridView1.DataSource = ds.Tables[0].DefaultView; 
后面需要绑定
dataGridView1.DataBind();
--------------------编程问答-------------------- 这明显是winform的datagridview,
DataSource属性就可以了
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,