In this article, we will Add new font for all the cells in a DataGridView.
Introduction
In this article, we will Add new font for all the cells in a DataGridView.
Straight to Experiment
Let us create a "Windows Forms Application" and add a "DataGridView" as under
Next in the code behind create a class as under
public class FileInformation
{
public string FileName { get; set; }
public string Download { get { return "Download File"; } }
}
This class holds the information about "FileName" and the "Download" link.
Next let us write the code that will give a good look and fell to our grid
private void PrepareGrid()
{
var fileNameColumn = new DataGridViewTextBoxColumn
{
Name = @"FileName",
HeaderText = "File Name",
DataPropertyName = @"FileName",
AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill,
ReadOnly = false,
Frozen = false
};
dataGridView1.Columns.Add(fileNameColumn);
var downloadColumn = new DataGridViewLinkColumn
{
Name = @"Download",
HeaderText = @"Download",
DataPropertyName = @"Download",
AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill,
ReadOnly = true
};
dataGridView1.Columns.Add(downloadColumn);
this.dataGridView1.AllowUserToAddRows = false;
this.dataGridView1.AllowUserToDeleteRows = false;
this.dataGridView1.AllowUserToResizeRows = false;
this.dataGridView1.RowHeadersVisible = false;
this.dataGridView1.MultiSelect = false;
this.dataGridView1.SelectionMode = DataGridViewSelectionMode.RowHeaderSelect;
this.dataGridView1.AutoGenerateColumns = false;
}
In the "PrepareGrid()" method, we are giving mainly a Name, HeaderText and DataPropertyName to the columns that should participate in the DataGridViewControl.
Once done, the next task is to populate the grid content
private void DisplayResult()
{
FileInformationList = LoadItems();
dataGridView1.DataSource = FileInformationList;
}
private List<FileInformation> LoadItems()
{
var lstScriptInfo = new List<FileInformation>();
for (int i = 1; i <= 5; i++)
{
lstScriptInfo.Add(new FileInformation { FileName = "File" + i.ToString() + ".txt" });
}
return lstScriptInfo;
}
The code is preety straight forward.We are preparing a list of 5 items and binding the same to the grid
Next write the code in the Cell Painting event of the DataGridViewControl
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
string familyName = "Courier New";
float emSize = 8.5f;
dataGridView1.Columns["FileName"].DefaultCellStyle.Font = new System.Drawing.Font(familyName, emSize);
dataGridView1.Columns["Download"].DefaultCellStyle.Font = new System.Drawing.Font(familyName, emSize);
}
We are adding the needed font family name and size to the cells.
Conclusion
In this article we have seen how to Add new font for all the cells in a DataGridView.Hope this will be helpful.Thanks for reading.Zipped file is attached