从存储过程加载DataGridView

时间:2016-04-06 19:05:27

标签: c# stored-procedures datagridview

我在将存储过程加载到DataGridView时遇到问题。我已经找到了答案,但我的代码看起来与我找到的每个答案相似。存储过程在另一个DataGridView中运行,我添加了它作为固定数据源。我是C#的新手。谁能看到我错在哪里?

    private void Form1_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        SqlConnection myConn = new SqlConnection("Data Source=SERVER-SQL1;Initial Catalog=OPSystem;Integrated Security=True");
        myConn.Open();
        SqlCommand myCmd = new SqlCommand("spCustomers", myConn);
        myCmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter da = new SqlDataAdapter(myCmd);
        da.Fill(dt);
        dataGridView1.DataSource = da;

    }

2 个答案:

答案 0 :(得分:2)

您无法绑定到SqlDataAdapter。您需要绑定到DataTable。

        DataTable dt = new DataTable();
        SqlConnection myConn = new SqlConnection("Data Source=SERVER-SQL1;Initial Catalog=OPSystem;Integrated Security=True");
        myConn.Open();
        SqlCommand myCmd = new SqlCommand("spCustomers", myConn);
        myCmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter da = new SqlDataAdapter(myCmd);
        da.Fill(dt);
        dataGridView1.DataSource = dt;
        dataGridView1.DataBind();

对于上下文, SqlDataAdapter

  

表示一组数据命令和数据库连接   用于填充DataSet并更新SQL Server数据库。这个班   不能继承。

https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter(v=vs.110).aspx

答案 1 :(得分:0)

private BindingSource bindingSource1 = new BindingSource();

DataTable dt = new DataTable();

SqlConnection myConn = new SqlConnection(" Data Source = SERVER-SQL1; Initial Catalog = OPSystem; Integrated Security = True");

    myConn.Open();
    SqlCommand myCmd = new SqlCommand("spCustomers", myConn);
    myCmd.CommandType = CommandType.StoredProcedure;
    SqlDataAdapter da = new SqlDataAdapter(myCmd);
    da.Fill(dt);

bindingSource1.DataSource = dt; dataGridView1.DataSource = bindingSource1;

尝试使用BindingSource