Home > Software design >  DatagridView by SQL
DatagridView by SQL

Time:12-16

I have a datagridview with 4 columns

[](https://i.stack.imgur.com/wvD94.png)

and I want to make a query in my database, so that it appears in my datagridview.

 public DataTable pesquisar(string produto)
        {
            DataTable _dt = new DataTable();

            string sqlQuerry = "Select cd_produto, "  
                                  "ds_produto, "  
                                  "referencia, "  
                                  "ds_marca "  
                                  "FROM produto";

            command.CommandText = sqlQuerry;

            
            try
            {
                command.Connection = conn.Conectar();

                using (SqlDataAdapter da = new SqlDataAdapter(sqlQuerry, command.Connection))
                {
                    command.ExecuteNonQuery();

                    using (DataTable _DT = new DataTable())
                    {
                        da.Fill(_DT);

                        return _DT;
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

I did it like this, but this way it adds new columns to my datagrid

CodePudding user response:

When you set the DataSource of a DataGridView and AutoGenerateColumns is set to true, any columns/properties in the data source that do not match existing columns will have a new column generated for them. The way you match a column that you create to a column/property in the data source is to set the grid column's DataPropertyName property. For example, if you have a column in your data source named "cd_produto" then you need to set the DataPropertyName property of the corresponding grid column to "cd_produto" and then that source column will bind to that grid column.

  • Related