C#应用程序中连接SQL并读出表 在datagridview 中显示出来 麻烦大家了 急用 本人小白 最好写的详细点

要求在windows应用程序中读取SQL的你个表 表明叫jk_data_temp 数据库名是wn 要求在datagridview中显示出来 麻烦大家讲详细的步骤和代码给我 谢谢了

步骤1:
导入 System.Data.SqlClient;命名空间

步骤2:
new 一个dataSet数据集为成员变量

步骤3:

定义连接字符串
格式:

string conStr=@"Data Source=计算机名/sql2005;Initial Catalog=你的素具库;Integrated Security=True"

步骤4:
在点击链接的按钮事件中写上
try
{
using(SqlConnection con =new SqlConnection("连接数据库德字符串"))
{

SqlDataAdapter dr = new SqlDataAdapter("select * from jk_data_temp ", con);

dr.Fill("new出来的那个数据集");

//表示数据源为填充的数据集的第一个表
this.dataGridView1.DataSource = 上面填充的那个数据集.Table[0];
}

}
catch (Exception ex)
{
//报错机制 一旦错误 将会有提示
MessageBox.Show(ex.Message);
}

写完收工
温馨提示:答案为网友推荐,仅供参考
第1个回答  2009-07-31
在datagridview 的属性里面可以直接绑定数据源和表.
第2个回答  2009-07-31
手动链接比较麻烦,你在DataGridView里面直接绑定还比较方便。

点击DataGridView右上角的三角,选择数据源->添加项目数据源->数据库->新建连接->数据源Microsoft SQL Server (SqlClient)[默认的],选择服务器...
之后的看着选择就是了,很简单的。
再次点击DataGridView右上角的三角,编辑列,可以编辑HeadText。
第3个回答  2009-07-31
using System.Data.SqlClient;
……

SqlConnection conn;
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
conn = new SqlConnection("Server=(local);database=wn;Integrated Security=True;"); //连接数据库的字符串
conn.Open();
if (!IsPostBack)
{
SetDataBind();
}
}
protected void SetDataBind() //自定义函数
{
string sql = "select * from jk_data_temp ";
cmd = new SqlCommand(sql,conn );
SqlDataReader dr = cmd.ExecuteReader();
datagridview.DataSource = dr;
datagridview.DataBind();
}
相似回答
大家正在搜