我想在颜色列的单元格背景上显示一个简单的颜色吗?
如何显示颜色而不是颜色代码至少是单元格本身的背景颜色?顺便说一句,我正在使用全速选择..
我的加载数据库的代码
SuspendLayout();
using (MySqlConnection conn = new MySqlConnection(myConnection))
{
//string cell = dataGridView3.CurrentCell.Value.ToString();
conn.Open();
string query = "SELECT productid,description,color,quantity,unitprice FROM deqor.tblproducts where category=?cat;";
using (MySqlCommand cmd = new MySqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("?cat", comboBox1.SelectedItem.ToString());
try
{
sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
datset = new DataTable();
sda.Fill(datset);
bsource = new BindingSource();
bsource.DataSource = datset;
dataGridView1.DataSource = bsource;
DataGridViewColumn column = dataGridView1.Columns[0];
column.HeaderText = "Code";
column.Width = 160;
DataGridViewColumn column1 = dataGridView1.Columns[1];
column1.HeaderText = "Brand";
column1.Width = 220;
DataGridViewColumn column2 = dataGridView1.Columns[2];
column2.HeaderText = "Color";
column2.Width = 100;
DataGridViewColumn column3 = dataGridView1.Columns[3];
column3.HeaderText = "Quantity";
column3.Width = 50;
DataGridViewColumn column4 = dataGridView1.Columns[4];
column4.HeaderText = "Price";
column4.Width = 50;
sda.Update(datset);
if (dataGridView1.RowCount < 1)
{
datset.Clear();
string row = "NO items found";
datset.Rows.Add(row);
}
}
catch (Exception ex)
{
MessageBox.Show("" + ex);
}
}
conn.Close();
}
ResumeLayout();
答案 0 :(得分:1)
您可以在CellFormatting
活动期间设置颜色,有关说明,请参阅here
示例强>
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
//Check if we're formatting the color column
if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Color")
{
//Make sure there's a value set
if (e.Value != null)
{
string colorCode = (string)e.Value;
ColorConverter cc = new ColorConverter();
e.CellStyle.BackColor = (Color)cc.ConvertFromString("#" + colorCode);
//If you don't want the code to show
e.Value = "";
e.FormattingApplied = true;
}
}
}
答案 1 :(得分:1)
你可以对列[2]中的每个单元格使用foreach
并填充它:
dataGridView1.Rows[count].DefaultCellStyle.BackColor = (Color)ColorConverter.ConvertFromString("#FFDFD991");