如何将按钮中的文本设置为粗体,具体取决于它是否在 datagridview 中有信息。
下面是一个示例项目 - 创建一个 Windows 应用程序并将此代码放入。
我想要做的是,如果一个字段中有信息,我只想将那个单元格按钮字体加粗。
例如基于下面代码中的数据表
Row 1 David Notes this row bold text in button
Row 2 Sam Notes this row not
Row 3 Christoff Notes this row not
Row 4 Janet Notes this row bold text in button
Row 5 Melanie Notes this row not
代码:
private void Form1_Load(object sender, EventArgs e) {
DataTable table = GetTable();
DataGridViewColumn col = new DataGridViewTextBoxColumn();
col.HeaderText = "Dosage";
col.Width = 80;
int colIndex = dataGridView1.Columns.Add(col);
DataGridViewColumn col2 = new DataGridViewTextBoxColumn();
col2.HeaderText = "Drug";
col2.Width = 75;
colIndex = dataGridView1.Columns.Add(col2);
DataGridViewColumn col3 = new DataGridViewTextBoxColumn();
col3.HeaderText = "Patient";
col3.Width = 75;
colIndex = dataGridView1.Columns.Add(col3);
DataGridViewColumn col4 = new DataGridViewTextBoxColumn();
col4.HeaderText = "Date";
col4.Width = 40;
colIndex = dataGridView1.Columns.Add(col4);
DataGridViewButtonColumn buttonCol = new DataGridViewButtonColumn();
buttonCol.Name = "btnNotes";
buttonCol.HeaderText = "Notes";
buttonCol.Text = "Notes";
buttonCol.Width = 80;
buttonCol.UseColumnTextForButtonValue = true;
buttonCol.DefaultCellStyle.Font = new Font("Arial", 12, FontStyle.Bold);
dataGridView1.Columns.Add(buttonCol);
// Add items to the grid
int i = 0;
foreach(DataRow rows in table.Rows) {
dataGridView1.Rows.Add();
dataGridView1[1, i].Value = rows[0].ToString();
dataGridView1[1, i].Value = rows[1].ToString();
dataGridView1[2, i].Value = rows[2].ToString();
dataGridView1[3, i].Value = rows[3].ToString();
if (rows[3].ToString().Trim().Length != 0) {
//Because there are notes in this field, I would like to set this button text only to bold
}
i++;
}
}
static DataTable GetTable() {
DataTable table = new DataTable();
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("BlaBlaBla", typeof(string));
table.Rows.Add(25, "Indocin", "David", "Notes in here");
table.Rows.Add(50, "Enebrel", "Sam", "");
table.Rows.Add(10, "Hydralazine", "Christoff", "");
table.Rows.Add(21, "Combivent", "Janet", "Notes in here");
table.Rows.Add(100, "Dilantin", "Melanie", "");
return table;
}