简体   繁体   English

将数据源绑定到datagridview

[英]Bind datasource to a datagridview

I use .net 4.0 c# in winform. 我在Winform中使用.net 4.0 c#。 Now I use a stored procedure to insert a new row to the database. 现在,我使用存储过程将新行插入数据库。 Obviously I am confused by binding steps between asp.net and windows form. 显然,我对asp.net和Windows窗体之间的绑定步骤感到困惑。 In asp.net it is very simple but in winform it seems like we must use BindingSource object??? 在asp.net中,它非常简单,但在winform中,似乎必须使用BindingSource对象???

Which means in winform we have to use a different way. 这意味着在Winform中,我们必须使用其他方式。 The following code is that I used to use in asp.net to insert new record and binding. 下面的代码是我以前在asp.net中用来插入新记录和绑定的代码。 How to rewrite it to bind the datasource to a datagridview. 如何重写它以将数据源绑定到datagridview。

public void ExecuteNonQuery(string storedProcedure, Dictionary<string, object> parameters)
    {
        using (SqlConnection conn = new SqlConnection(_connectionString))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand(storedProcedure, conn))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                if (parameters != null)
                {
                    foreach (string parameter in parameters.Keys)
                    {
                        cmd.Parameters.AddWithValue(parameter, parameters[parameter] ?? DBNull.Value);
                    }
                }
                cmd.ExecuteNonQuery();
            }
            conn.Close();
        }
    }

After setting parameters, then call it like: 设置参数后,按如下方式调用它:

        DBAccess dbaccess = new DBAccess(connString);
        dbaccess.ExecuteNonQuery("InsertStoredProcedure", parameters);

I don't know how to bind database to the datagridview. 我不知道如何将数据库绑定到datagridview。 Thanks. 谢谢。

If you inserted a Row to database, then you need to fetch the rows from the database again. 如果将行插入数据库,则需要再次从数据库中获取行。 using the another Stored Procedeure (with SELECT Query). 使用另一个存储过程(带有SELECT查询)。

you are using ExecuteNonQuery, that means you are not querying anything from the database. 您正在使用ExecuteNonQuery,这意味着您没有从数据库查询任何内容。 So It willn't give you result in the form of grid. 因此,它不会以网格的形式提供结果。 But it will just return an integer with number of row affected. 但是它只会返回一个整数,其中包含受影响的行数。

So my suggestion is after inserting the row, write another query to fetch the rows with cmd.ExecuteReader() and bind the SqlReader object to Grid. 所以我的建议是在插入行之后,编写另一个查询以使用cmd.ExecuteReader()获取行并将SqlReader对象绑定到Grid。

I Hope that will resolve your problem. 希望能解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM