【问题标题】:Loading DataGridView from Stored Procedure从存储过程加载 DataGridView
【发布时间】:2016-04-06 19:05:27
【问题描述】:

我在将存储过程加载到 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;

    }

【问题讨论】:

  • this.iTManagementSystemDataSet 是什么?这里好像没有在Form的Load事件中初始化。
  • 抱歉从我的代码中删除,我已经编辑了我的帖子。

标签: c# stored-procedures datagridview


【解决方案1】:

您不能绑定到 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

【讨论】:

  • 非常感谢 :) 我没有添加行 dataGridView1.DataBind();因为我认为这仅适用于网络表单。
  • 太棒了。我不确定它是 Windows 应用还是网络应用。
  • 完美运行。如何管理在 gridview 中显示列和标题?
【解决方案2】:
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

【讨论】:

    猜你喜欢
    • 2010-12-28
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多