Reputation: 89
I m working on an application where 5 images saved on a single id in the database. Now I want to retrieve these images in a datagrigview whenever they are called. My following code is working good with picturebox but I want multiple images containing the same pincode in datagridview from SQl server database.
try
{
string sql = "Select IMAGE from UserInput where PINCODE = '" + txt_LPin.Text + "'";
if (conn.State != ConnectionState.Open)
conn.Open();
cmd = new SqlCommand(sql, conn);
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
//txt_LName.Text = reader[0].ToString();
byte[] img = (byte[])(reader[1]);
if (img == null)
pb_get1.Image = null;
else
{
MemoryStream ms = new MemoryStream(img);
pb_get1.Image = Image.FromStream(ms);
}
}
else
{
txt_LPin.Text = "";
txt_LName.Text = "";
pb_get1.Image = null;
MessageBox.Show("This ID does not exist.");
}
conn.Close();
}
catch (Exception ex)
{
conn.Close();
MessageBox.Show(ex.Message);
}
I have tried following code for dataGridView but it shows cross mark intead of image on place of image.
SqlDataAdapter adpat = new SqlDataAdapter();
adpat.SelectCommand = new SqlCommand("select IMAGE from UserInput", conn);
DataTable table = new DataTable("UserInput");
adpat.Fill(table);
//create image column:
DataGridViewImageColumn photoColumn = new DataGridViewImageColumn();
photoColumn.DataPropertyName = "Picture";
photoColumn.Width = 200;
photoColumn.HeaderText = "Picture column";
photoColumn.ReadOnly = true;
photoColumn.ImageLayout = DataGridViewImageCellLayout.Normal;
dataGridView1.Columns.Add(photoColumn);
//bind data to dgv:
dataGridView1.DataSource = new BindingSource(table, null);
Upvotes: 1
Views: 4449
Reputation: 89
Problem is Solved by the following line of codes;
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter("Select Image,Name from UserInput where PINCODE = '" + txt_LPin.Text + "'",conn);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
conn.Close();
Upvotes: 0
Reputation: 110
To insert images in gridview ,you can use:
1) We need datasource:
dataGridView1.DataSource = datasouce;
2) create an image column by writing;
DataGridViewImageColumn img = new DataGridViewImageColumn();
img.Name = "img";
img.HeaderText = "Image Column";
img.ValuesAreIcons = true;
dataGridView1.Columns.Add(img);
3) and Finally
int number_of_rows = dataGridView1.RowCount;
for (int i = 0; i < number_of_rows; i++)
{
if (dataGridView1.Rows[i].Cells[6].Value.ToString() == "true")
{
Icon image = Properties.Resources.succcess_icon;
dataGridView1.Rows[i].Cells["img"].Value = image;
}
else
{
Icon image =Properties.Resources.cancel_icon;
dataGridView1.Rows[i].Cells["img"].Value = image;
}
}
Upvotes: 1