调用本机数据库的存储过程放到dataGridView和listview中
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//调用本机teach数据库的存储过程chaxu(无参数)
using (SqlConnection conn = new SqlConnection("Data source=.;Initial catalog=teach;Integrated Security=True "))
{
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter("chaxun", conn);
//sda.SelectCommand.CommandType = CommandType.StoredProcedure;
//DataSet ds = new DataSet();//建数据集
//sda.Fill(ds);
//BindingSource bs = new BindingSource();
//bs.DataSource = ds.Tables[0];
//dataGridView1.DataSource = bs;
DataTable dt = new DataTable();//或直接建表
sda.Fill(dt);
BindingSource bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
}
//调用本机teach数据库的存储过程chaxu2(有参数)返回年龄大于30的记录
/*using (SqlConnection conn = new SqlConnection("Data source=.;Initial catalog=teach;Integrated Security=True "))
{
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter("chaxun2", conn);
sda.SelectCommand.CommandType = CommandType.StoredProcedure;
SqlParameter sp =new SqlParameter("@age",30);
sda.SelectCommand.Parameters.Add(sp);
DataSet ds = new DataSet();
sda.Fill(ds);
BindingSource bs = new BindingSource();
bs.DataSource = ds.Tables[0];
dataGridView1.DataSource = bs;
}*/
/*****************************************************************************************************/
//填充到listview的方法
using (SqlConnection conn = new SqlConnection("Data source=.;Initial catalog=teach;Integrated Security=True "))
{
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter("chaxun", conn);
sda.SelectCommand.CommandType = CommandType.StoredProcedure;
DataTable dt = new DataTable();
sda.Fill(dt);
listView1.View = View.Details;
listView1.GridLines = true;
listView1.Columns.Add("姓名");
listView1.Columns.Add("年龄");
foreach (DataRow row in dt.Rows)//读取数据集中的行
{
ListViewItem listViewItem = new ListViewItem(row[0].ToString());
listViewItem.SubItems.Add(row[1].ToString());
listView1.Items.Add(listViewItem);
}
}
}
}
}