skip to Main Content

I can’t display photo from heidiSQL in my datagridview. There is an error and I don’t know how to cope with it because my source code is exactly the same as a person that I’m study with. Only difference is that he is using phpmyadmin.

Student student = new Student();
private void StudentsList_Load(object sender, EventArgs e)
{
    // populate the datagridview with students data

    MySqlCommand command = new MySqlCommand("SELECT * FROM `students`");
    dataGridView1.ReadOnly = true;
    DataGridViewImageColumn picCol = new DataGridViewImageColumn();
    dataGridView1.RowTemplate.Height = 80;
    dataGridView1.DataSource = student.getStudents(command);
    picCol = (DataGridViewImageColumn)dataGridView1.Columns[7];
    picCol.ImageLayout = DataGridViewImageCellLayout.Stretch;
    dataGridView1.AllowUserToAddRows = false;
}

https://i.stack.imgur.com/Kilx0.png
Error I get

2

Answers


  1. Chosen as BEST ANSWER

    I already fixed the problem. I needed to add .ToArray() to my picture variable when I was converting it into parameter.

    MySqlCommand command = new MySqlCommand();
    String editQuery = "sql query";
    command.CommandText = editQuery;
    command.Connection = conn.getConnection();
    
    command.Parameters.Add("@pic", MySqlDbType.Blob).Value = picture.ToArray();
    

  2. For a start, I would use a column Name instead of an Index; it’s where it can get mixed easily. I believe it should be:

    picCol = (DataGridViewImageColumn)dataGridView1.Columns["ImageDBColumnName"];
    

    This applies also to your DataSource, SELECT * is a bad practice. You should list your data columns and also refer by their names.

    Then, what is the file type of your images? You didn’t mention that.

    But I would focus also on the order of definitions. You set the properties quite randomly, I would suggest fist to define DataGridView properties such as Columns (most importantly ensure that intended image column is of type DataGridViewImageColumn) and only at the last moment, set the DataGridView.DataSource. Specifically here I see a potential problem:

    dataGridView1.DataSource = student.getStudents(command);
    picCol = (DataGridViewImageColumn)dataGridView1.Columns[7];
    

    I personally prefer to use GUI to set up DataGridView columns, as it offloads a lot of code from the solution and you can be sure, they are set before your code is executed. However, if your datasource happens to be empty, you will loose those definitions. An easy solution is to use DataTable as data mediator.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search