【问题标题】:C# WinForm passing a name chosen in a combobox to a stored procedureC# WinForm 将组合框中选择的名称传递给存储过程
【发布时间】:2016-12-23 00:59:38
【问题描述】:

我有一个主页表,其中两个作为根/主/父网站(localDB,数据集)。我想实现一个存储过程。它列出了网站的所有父级并在 DataGridView 中显示结果 [id, parentID, name]。

我得到了以下存储过程

CREATE PROCEDURE GetIDbyID (@childname varchar(50)) AS

;With CTE  (ID
        ,   name
        ,   parentID
        ,   Level) AS
(SELECT e.ID
        , e.name
        , e.parentID
        , 0 AS Level

    FROM page AS e
    WHERE e.name LIKE @childname

UNION ALL

SELECT    e.ID
        , e.name
        , e.parentID
        , Level+1

    FROM page AS e
    INNER JOIN CTE AS h
    ON h.parentID = e.ID
    )
SELECT DISTINCT ID
              , name
              , parentID
FROM CTE
ORDER BY ID

执行我得到这个查询,我可以在其中插入一个网站

USE [C:\...DATABASE1.MDF]
GO

DECLARE @return_value Int

EXEC    @return_value = [dbo].[GetIDbyID]
        @childname = N'**Page..**'  //How to insert the page here that is selected in the combobox???

SELECT  'Return Value' = @return_value

GO

我管理它来建立与数据库的连接并在组合框中列出整个表。具有列和与 SP 的连接的 DataGridView 也已经存在。现在我的愿望是,当我在组合框中选择一个站点时,DataGridView 会立即用 SP 的值填充。这个 CTE 甚至可能吗?

任何想法如何实现这一目标?

【问题讨论】:

  • 标记使用的 dbms 产品。 (那个 SP 看起来不像 ANSI SQL。)
  • 听起来你想使用 ComboBox.SelectedIndexChanged 来刷新/绑定你的数据网格。您正在发布您的 SQL 代码,但据我所知,这实际上更像是一个 c# 问题,因此您也应该发布该代码
  • @Matt 谢谢!我想这样做,但由于我的代码没有问题,我只是想确保这个 SQL 是兼容的。下面的答案是我需要的:-)
  • @jarlh 我知道 ANSI 是什么,但只是出于我的兴趣,该 SP 应该如何看起来正确?我拿了教程的一部分,并按照它对我的数据库的工作方式进行了更改。而对于未来,我想做适当的事
  • 如果您使用的是 MS SQL Server,ANSI SQL 版本的procecure 将无法运行。 MS SQL Server(和大多数其他 dbms 产品)有自己的存储过程实现。这就是为什么您应该指定您正在使用的 dbms 产品!

标签: c# sql-server winforms stored-procedures combobox


【解决方案1】:

我通常喜欢创建一个单独的过程来填充 datagridview,然后从我想要更改数据的任何事件中调用它。这是一个可以帮助您入门的示例:

public void fillDataGridView()
{
    using (SqlConnection connection = new SqlConnection(yourConnectionString))
        {
            using (SqlCommand scmd = new SqlCommand("[dbo].[GetIDbyID]", connection))
            {
                connection.Open();
                scmd.CommandType = CommandType.StoredProcedure;
                scmd.Parameters.AddWithValue("@childname", comboBox.SelectedValue); //add as many parameters as you need
                SqlDataAdapter sda = new SqlDataAdapter(scmd);
                DataTable dt = new DataTable();
                sda.Fill(dt);
                connection.Close();
                dataGridView.DataSource = dt;
                dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells); //this just autosizes the columns to their contents and is optional
            }
        }
}

您可以从 SelectedIndexChanged 事件中调用它和/或创建一个将在单击时执行它的按钮。

【讨论】:

  • 谢谢!只是用按钮这样做,它工作正常。感谢您的快速回复!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-27
  • 1970-01-01
  • 2014-03-21
  • 2011-09-15
  • 1970-01-01
相关资源
最近更新 更多