简体   繁体   中英

Bind datasource to a datagridview

I use .net 4.0 c# in winform. 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. In asp.net it is very simple but in winform it seems like we must use BindingSource object???

Which means in winform we have to use a different way. The following code is that I used to use in asp.net to insert new record and binding. How to rewrite it to bind the datasource to a 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. 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).

you are using ExecuteNonQuery, that means you are not querying anything from the database. 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.

I Hope that will resolve your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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