I have created an DataGridViewImage column for my DataGridView.
DataGridViewImageColumn guardar = new DataGridViewImageColumn();
{
guardar.HeaderText = "";
guardar.Name = "guardar";
guardar.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
guardar.CellTemplate = new DataGridViewImageCell();
guardar.Image = Properties.Resources.empty_grilla;
guardar.ToolTipText = "Guardar";
}
dgv_Bancos.Columns.Add(guardar);
The problem is that when I want to change the Image of an specific cell, it just does not changes.
This is my code, please help, I donĀ“t know what is wrong
DataGridViewImageCell cell = (DataGridViewImageCell)dgv_Bancos.Rows[e.RowIndex].Cells["guardar"];
cell.Value = Properties.Resources.guardar_grilla;
RESOLVED!
You can use like this instead of using the DataGridViewImageCell cell
dataGridView1["guardar", e.RowIndex].Value = Properties.Resources.guardar_grilla;
Related
Using the below link, I am able to loop through the rows and able to get exact cell, but unable to set its color. Please see the code below.
How do I dynamically set the forecolour of my column data based on the value when exporting excel using EPPLUS?
var costStructureReport = new
{
CurrentQuotation = rptCostStructure.GetCostStructureReport()
};
var reportEngine = new ReportEngine();
string fileName = reportEngine.ProcessReport(ReportNames.ProjectDownload_Template, reportname + ".xlsx", costStructureReport);
var ep = new ExcelPackage(new FileInfo(fileName));
var sheet1 = ep.Workbook.Worksheets["SPR_ProjectDownload"];
var row = sheet1.Dimension.End.Row;
for(int i=0;i< costStructureReport.CurrentQuotation.Count;i++)
{
if (costStructureReport.CurrentQuotation[i].MaterialCost_ByUser)
{
sheet1.Cells[i+2, 2].Style.Font.Color.SetColor(System.Drawing.Color.Red);
sheet1.Cells[i + 2, 12].Style.Font.Color.SetColor(System.Drawing.Color.Red);
sheet1.Cells[i + 2, 12].Style.Font.Bold = true;
}
}
You can Change the Text Color using
[RangeObject].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
And Font Colour using
[RangeObject].Interior.Color =System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
I have a listview in my form.
In my text file I have this:
24-7-2017:13:44:40;x;0.0078;y;-0.0147;z;0.9879;
24-7-2017:13:44:41;x;0.0069;y;-0.0069;z;1.0104;
24-7-2017:13:44:40; represents the time where I want to put in the first column of the listview
x;0.0078;y;-0.0147;z;0.9879; is where I want to create three columns to put the X,Y,Z in the each column and the data in the respective column
the next line will then be in row 2 in their respective column
they are separated by ";"
How I go about displaying it in the listview?
Try this
System.Windows.Forms.ListView listView = new System.Windows.Forms.ListView();
DateTime = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
X = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
Y = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
Z = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
SuspendLayout();
listView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
DateTime,
X,
Y,
Z});
listView.GridLines = true;
listView.View = System.Windows.Forms.View.Details;
DateTime.Text = "DateTime";
X.Text = "X";
Y.Text = "Y";
Z.Text = "Z";
this.Controls.Add(this.listView);
StreamReader file = new StreamReader("filepath");
string sLine;
while ((sLine = file.ReadLine()) != null)
{
string[] sarr= sLine.Split(';');
StringBuilder sb = new StringBuilder(sarr[0]);
sb[sarr[0].IndexOf(':')] = ' ';
sarr[0] = sb.ToString().Replace(':', '.');
string[] sData = { sarr[0], sarr[2], sarr[4], sarr[6] };
ListViewItem item = new ListViewItem(sData);
listView.Items.Add(item);
}
after this you can add your first data into listView and then do for remain the same. And make sure your listView view property set to Details.
output:
Here is the new tested answer with the solution.
public Form1()
{
InitializeComponent();
//read the file
System.IO.StreamReader file =
new System.IO.StreamReader("yourFileName.txt");
//set list view in details mode
listView1.View = View.Details;
//Set columns in listview
listView1.Columns.Add("Date Time");
listView1.Columns.Add("X");
listView1.Columns.Add("Y");
listView1.Columns.Add("Z");
string line = "";
//read text file line by line.
while (( line = file.ReadLine()) != null)
{
var itemMC = new ListViewItem(new[] { line.ToString().Split(';')[0].ToString(), line.ToString().Split(';')[2].ToString(),
line.ToString().Split(';')[4].ToString(), line.ToString().Split(';')[6].ToString() });
listView1.Items.Add(itemMC);
}
file.Close();
}
Here is the output(from the given data in question) :
I am creating a DataGrid by importing an excel file. I want users manually to be able to change column names from the application.
Edit: Workaround at the bottom
My desktop app will have below logic:
Load excel file and display table in DataGrid
Manually change Column names to match fixed text. (e.x. Column "PricesZZZ" renamed to "Prices", "LeadTimeXXX to "LeadTime")
Export DataGrid to new excel template with only relevant columns that are matched by fixed text (thus the need to have correct
names).
Excel file can have multiple columns and only several of those columns have relevant information and the only way to identify them is to match header name or some other way have user "tell" program which column holds which information.
I need to find a way to change Column name based on user input as I think it's most straightforward. I'm new to c# so sorry if my thinking is a little backwards.
Below is the code snippet I have so far. Might not be relevant for this specific problem, but may help visualize. I use EPPlus library
Import excel
private void btnOpenXL_Click(object sender, RoutedEventArgs e)
{
// Create OpenFileDialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
// Set filter for file extension and default file extension
dlg.DefaultExt = ".xls";
dlg.Filter = "Excel Files|*.xlsx;*.xls;*.xlsm;*.csv";
// Display OpenFileDialog by calling ShowDialog method
Nullable<bool> result = dlg.ShowDialog();
// Get the selected file name
if (result == true)
{
// Open document
string filename = dlg.FileName;
//call another class to draw the table
dataGrid.ItemsSource = GetDataTableFromExcel(filename).DefaultView;
MessageBox.Show("import done");
}
}
public static DataTable GetDataTableFromExcel(string path, bool hasHeader = true)
{
using (var pck = new OfficeOpenXml.ExcelPackage())
{
using (var stream = File.OpenRead(path))
{
pck.Load(stream);
}
var ws = pck.Workbook.Worksheets.First();
DataTable tbl = new DataTable();
foreach (var firstRowCell in ws.Cells[1, 1, 1, ws.Dimension.End.Column])
{
tbl.Columns.Add(hasHeader ? firstRowCell.Text : string.Format("Column {0}", firstRowCell.Start.Column));
}
var startRow = hasHeader ? 2 : 1;
for (int rowNum = startRow; rowNum <= ws.Dimension.End.Row; rowNum++)
{
var wsRow = ws.Cells[rowNum, 1, rowNum, ws.Dimension.End.Column];
DataRow row = tbl.Rows.Add();
foreach (var cell in wsRow)
{
row[cell.Start.Column - 1] = cell.Text;
}
}
return tbl;
}
}
Export excel
private void btnExportToXL_Click(object sender, RoutedEventArgs e)
{
DataTable dataTable = new DataTable();
dataTable = ((DataView)dataGrid.ItemsSource).ToTable();
ExportDataTableToExcel(dataTable);
MessageBox.Show("export done");
}
public void ExportDataTableToExcel(DataTable dataTable)
{
string path = "C:\\test";
var newFile = new FileInfo(path + "\\" +
DateTime.Now.Ticks + ".xlsx");
using (ExcelPackage pck = new ExcelPackage(newFile))
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Sheet1");
ws.Cells["A1"].LoadFromDataTable(dataTable, true);
pck.Save();
System.Diagnostics.Process.Start(newFile.ToString());
}
}
EDIT:
Workaround by double clicking on any cell in datagrid:
private void dataGrid_MouseDoubleClick(object sender, RoutedEventArgs e)
{
if (dataGrid.SelectedIndex == -1) //if column selected, cant use .CurrentColumn property
{
MessageBox.Show("Please double click on a row");
}
else
{
DataGridColumn columnHeader = dataGrid.CurrentColumn;
if (columnHeader != null)
{
string input = Interaction.InputBox("Title", "Prompt", "Default", 0, 0);
columnHeader.Header = input;
}
}
}
You can change the column names of the datagridview. But note, that this change is limited only to the grid and not it's data source. So in a nutshell, for simple representational purposes, you can use the following code:
dataGrid.Columns[i].HeaderText = "New Column Name"; //i is the index of the column
You can call this code form a Button click event of a Text change event of the input where the user provides the header name. Additionally, if you have the column names beforehand, you can replace then column headers with new values right after the data source has been bound to the grid. Change the headers after this line:
dataGrid.ItemsSource = GetDataTableFromExcel(filename).DefaultView;
//Set new column names here
I need to show some texts on the DataGridViewButtonColumn. I've read lots of similar question about these on SO. Many of them answers recommend setting UseColumnTextForButtonValueto True which doesn't for me. It seems in an odd way that Microsoft makes it to have at least a row so that the button will display the text.
The following is my code:
DataGridViewButtonColumn EditColumn = new DataGridViewButtonColumn();
EditColumn.HeaderText = "Complete";
EditColumn.Name = "Complete";
EditColumn.UseColumnTextForButtonValue = True;
dataGridView.Columns.Add(EditColumn);
This code doesn not show the text on the DataGridViewButtonColumn:
The code that works here:
dataGridView1.ColumnCount = 2;
dataGridView1.Columns[0].Name = "a";
dataGridView1.Columns[1].Name = "b";
ArrayList row = new ArrayList();
row.Add("1");
row.Add("2");
dataGridView1.Rows.Add(row.ToArray());
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
btn.Name = "text";
btn.UseColumnTextForButtonValue = true;
dataGridView1.Columns.Add(btn);
This code works but however I am getting my data from a database and thus I won't be using dataGridView.Rows.Add(row.ToArray()) here. So how do I get the text to show on the DataGridViewButtonColumn ?
You have two problems to solve:
How bind a Button column to a DataSource
How to make the DataSource create not only default column types but also one (or more) button column
The first issue is basically solved by setting the DataPropertyName of the column.
But I do not know how or even if it is possible to influence the ColumnTypes created automatically.
Therefore I suggest a workaround: Instead of relying on the AutoGenerateColumns we can do it ourselves in a little helper function:
This clears the columns and creates a new one for each column in a DataTable, using the properties of the columns in the table. To tell it which column(s) we want to be buttons we pass a string with the column names, surrounded by spaces:
void CreateSpecialColumns(DataTable dt, DataGridView dgv, string buttons)
{
dgv.Columns.Clear();
for (int i = 0; i < dt.Columns.Count; i++ )
{
DataColumn dc = dt.Columns[i];
if (buttons.Contains(" " + dc.ColumnName + " "))
{
DataGridViewButtonColumn buttonColumn = new DataGridViewButtonColumn();
buttonColumn.HeaderText = dc.Caption;
buttonColumn.Name = dc.ColumnName;
buttonColumn.ValueType = dc.DataType;
buttonColumn.DataPropertyName = dc.ColumnName;
dgv.Columns.Add(buttonColumn);
}
else
{ // normal columns
int c = dgv.Columns.Add(dc.ColumnName, dc.Caption);
dgv.Columns[c].ValueType = dc.DataType;
dgv.Columns[c].DataPropertyName = dc.ColumnName;
}
}
}
Here is how I called it using a DataTable DT:
dataGridView1.AutoGenerateColumns = false;
CreateSpecialColumns(DT, dataGridView1, " Cook Waiter ", "");
dataGridView1.DataSource = DT;
Note that this only works if the UseColumnTextForButtonValue property is not set to true!
You need to set the Text property,
DataGridViewButtonColumn EditColumn = new DataGridViewButtonColumn();
EditColumn.HeaderText = "Complete";
EditColumn.Name = "Complete";
EditColumn.UseColumnTextForButtonValue = True;
EditColumn.Text = "Complete"; // --Text property added
dataGridView.Columns.Add(EditColumn);
I am working on WinForms, .NET2 project.
I am using a DataGridView control to display some data.
How can I dynamically add an image to display in a DataGridViewImageColumn ?
Have you tried setting the Image property?
Gets or sets the image displayed in the cells of this column when the
cell's Value property is not set and the cell's ValueIsIcon property
is set to false.
You can try following...
for (int i = 0; i < gridView.Columns.Count; i++)
{
TableCell tableCell = gridViewRow.Cells[i];
System.Web.UI.WebControls.Image img;
sortDirectionImageControl = new System.Web.UI.WebControls.Image();
string imageUrl = "~/Images/Myimage.jpg";
img.ImageUrl = imageUrl;
img.Style.Add(HtmlTextWriterStyle.MarginLeft, "10px");
tableCell.Wrap = false;
tableCell.Controls.Add(img);
}
Hope I get your question correctly.