简体   繁体   中英

C# LoadData , Convert column to image in dataGridView

I need when load dataGridView status[status] column convert to image and show image , The column status = 1 or 0 and i need if 1 show ok.png and if 0 show no.png

private void LoadData()
        {
            SetConnection();
            sql_con.Open();
            sql_cmd = sql_con.CreateCommand();
            string CommandText = "select id[code] ,status[status], url[url] from  db";
            DB = new SQLiteDataAdapter(CommandText, sql_con);
            DS.Reset();
            DB.Fill(DS);
            DT = DS.Tables[0];
            dataGridView.DataSource = DT;
            dataGridView.Columns["code"].Visible = false;
            sql_con.Close();
        }

anyone can help me ?

Thanks

Use CellFormatting event of DataGridView as follow:

    private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        if (e.ColumnIndex == 0)
        {
            var dt = dataGridView1.DataSource as DataTable;
            if (dt != null && dt.Rows.Count > e.RowIndex && dt.Columns.Count > e.ColumnIndex)
            {
                var value = Convert.ToInt32(dt.Rows[e.RowIndex][e.ColumnIndex]);
                if (value == 0)
                    e.Value = Image.FromFile(@"C:\No.png"); // Here you can provide your own path of No.png image
                if (value == 1)
                    e.Value = Image.FromFile(@"C:\OK.png"); // Here you can provide your own path of Ok.png image

            }
        }
    }

Edit: Instead of Auto-Generating columns, create columns in DataGridView as shown in image:

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