Freeze excel column with c# - c#

I generate an excel spread-cheat with c# and I want to freeze the first column.
This is the code that I use :
public static void SaveToExcel(object[,] data)
{
Excel = Microsoft.VisualBasic.Interaction.CreateObject("Excel.Application", String.Empty);
Excel.ScreenUpdating = false;
dynamic workbook = Excel.workbooks;
workbook.Add();
dynamic worksheet = Excel.ActiveSheet;
const int left = 1;
const int top = 1;
int height = data.GetLength(0);
int width = data.GetLength(1);
int bottom = top + height - 1;
int right = left + width - 1;
if (height == 0 || width == 0)
return;
dynamic rg = worksheet.Range[worksheet.Cells[top, left], worksheet.Cells[bottom, right]];
rg.Value = data;
// Set borders
for (var i = 1; i <= 4; i++)
rg.Borders[i].LineStyle = 1;
// Set header view
dynamic rgHeader = worksheet.Range[worksheet.Cells[top, left], worksheet.Cells[top, right]];
rgHeader.Font.Bold = true;
rgHeader.Interior.Color = 189 * (int)Math.Pow(16, 4) + 129 * (int)Math.Pow(16, 2) + 78;
rg.EntireColumn.AutoFit();
// Show excel app
Excel.ScreenUpdating = true;
Excel.Visible = true;
}
Could You Please Help me???

The right solution is to add the following code :
worksheet.Activate();
worksheet.Application.ActiveWindow.SplitColumn = 1;
worksheet.Application.ActiveWindow.FreezePanes = true;

You need to set
yuorRange.Application.ActiveWindow.FreezePanes = true;
Have a look at
Window.FreezePanes Property
Window.SplitColumn Property
Window.SplitRow Property

Related

C# I create a new Picturebox and now my Textboxes won't give me any values back

I'm creating a new Picturebox via code, but now my TextBoxes don't give me any values. I think they went out of focus, or their controls aren't working anymore, here's the code so far:
private void button1_Click(object sender, EventArgs e)
{
int ErrorCode = 0;
string NewName = NewPointName.Text;
int X, Y;
Application.DoEvents();
if (NewPointName.Text == "")
ErrorCode = 1;
else
for (int i = 0; i < Names + 1; i++)
{
if (PointName[i] == NewName)
ErrorCode = 2;
}
if (ErrorCode > 0)
MessageBox.Show("Error " + ErrorCode);
else
{
if (Convert.ToInt32(NewPointXBox.Text) > 60)
X = 60;
else if (Convert.ToInt32(NewPointXBox.Text) < -60)
X = -60;
else if (NewPointXBox.Text == "")
X = 0;
else
X = Convert.ToInt32(NewPointXBox.Text);
if (Convert.ToInt32(NewPointYBox.Text) > 60)
Y = 60;
else if (Convert.ToInt32(NewPointYBox.Text) < -60)
Y = -60;
else if (NewPointYBox.Text == "")
Y = 0;
else
Y = Convert.ToInt32(NewPointYBox.Text);
Punkt.GiveName(NewName, Names);
Punkt.GiveCoordinates(X, Y, Names);
PointName[Names] = NewName;
NewPointName.Text = "";
NewPointXBox.Text = "";
NewPointYBox.Text = "";
Application.DoEvents();
UpdatePoint();
CreatePoint(X, Y, NewName, Names);
Names++;
ErrorCode = 0;
NewName = "";
}
}
public void CreatePoint(int X, int Y, string name, int i)
{
int StartPointX = 450, StartPointY = 450, Factor = 7;
if (RadioG6060.Checked)
{
StartPointX = 454;
StartPointY = 449;
Factor = 7;
}
Dot[i] = new PictureBox();
this.Controls.Add(Dot[i]);
Dot[i].Name = "PB_" + name;
Dot[i].Size = new Size(10, 10);
Dot[i].Image = Image.FromFile("../Dot.png");
Dot[i].Anchor = AnchorStyles.Left;
Dot[i].Location = new Point(StartPointX, StartPointY);
Dot[i].Visible = true;
InitializeComponent();
Dot[i].BringToFront();
Dot[i].Location = new Point(Dot[i].Location.X + (X * Factor), Dot[i].Location.Y - (Y * Factor));
Application.DoEvents();
}
I think it's the this.controls.Add(Dot[i]) that throws it off, because now I can't access the text in my NewPointName textbox.
How can I focus the program back on the form or do generally anything that could activate the boxes again?
I just solved the problem, I just had to leave out the InitializeComponent(), then it worked. Turns out that if you do that, the already existing components get blocked and can't be changed in any options of themselves anymore.

Graph with uneven intervals on y axis

I've tried without luck do make such graph in WinForms with Chart control.Graph with uneven intervals on y axis My first idea was to use pointed Chart with images for empty and not empty marker. The lines are displayed, but unfortunatelly there is a big space between values 4 - 19 and 20 - 33. Is there a way to avoid the space when using standard WinForms chart Control?
My second idea was to use a DatagridView. I could add not more that something aboit 700 columns. I would need almost 2000 columns. Thus the DataGridView isn't best choice for me.
Thank for any hint how to achieve it.
Edit 1:
As sugested by TnTinMn I've tried ScaleBreakStyle. This seems to remove some spaces from the graph. At the moment my graph looks like this:
This was achieved by the Code:
var chartArea = chart1.ChartAreas[series.ChartArea];
chartArea.AxisX.LabelStyle.IsStaggered = false;
chartArea.AxisX.Minimum = 0;
chartArea.AxisX.Maximum = (int)numericUpDown1.Value;
chartArea.AxisX.IsReversed = true;
chartArea.AxisX.Interval = 1;
chartArea.AxisX.ScaleView.SizeType = DateTimeIntervalType.Number;
chartArea.AxisY.ScaleBreakStyle.Enabled = true;
chartArea.AxisY.ScaleBreakStyle.BreakLineStyle = BreakLineStyle.None;
chartArea.AxisY.ScaleBreakStyle.Spacing = 0;
chartArea.AxisY.ScaleBreakStyle.CollapsibleSpaceThreshold = 50;
chartArea.AxisY.Interval = 1;
If I try to put the y labels on the left side, it doesn't work
chartArea.AxisY.Enabled = AxisEnabled.False;
chartArea.AxisY2.Enabled = AxisEnabled.True;
Adding folowing code doesn't solve the problem:
chartArea.AxisY2.ScaleBreakStyle.Enabled = true;
chartArea.AxisY2.ScaleBreakStyle.BreakLineStyle = BreakLineStyle.None;
chartArea.AxisY2.ScaleBreakStyle.Spacing = 0;
chartArea.AxisY2.ScaleBreakStyle.CollapsibleSpaceThreshold = 50;
chartArea.AxisY2.Interval = 1;
How can I remove 26 and 28, and leave only 1 and 27 on the chart? How can I put 1 and 27 on the bottom and leave a "big" space above them?
Edit 2:
After some tryies I've achieved what I wanted(I still have to adjust the marker images, but it looks very promising).
This is what I have at the moment:
As TnTiMn said, it is a little bit tricky. I had to map 1, 2, 3... to my real values and then to assign custom labels. I didn't used ScaleBreakStyle. Thanks anyway for your help.
My code:
chart1.ChartAreas[0].AxisX.IsReversed = true;
chart1.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
chart1.ChartAreas[0].AxisY.MajorGrid.Enabled = false;
chart1.ChartAreas[0].AxisY2.MajorGrid.Enabled = false;
chart1.ChartAreas[0].AxisY.Enabled = AxisEnabled.False;
chart1.ChartAreas[0].AxisY2.Enabled = AxisEnabled.True;
chart1.ChartAreas[0].AxisY2.ScaleView.SizeType = DateTimeIntervalType.Number;
chart1.ChartAreas[0].AxisY2.MajorTickMark.Enabled = false;
chart1.Series[0].MarkerImage ="NotEmptyPoint.png";
chart1.Series[0].EmptyPointStyle.MarkerImage = "EmptyPoint.png";
chart1.Series[1].MarkerImage = "NotEmptyPoint.png";
chart1.Series[1].EmptyPointStyle.MarkerImage = "EmptyPoint.png";
chart1.Series[2].MarkerImage = "NotEmptyPoint.png";
chart1.Series[2].EmptyPointStyle.MarkerImage = "EmptyPoint.png";
chart1.ChartAreas[0].AxisY.Interval = 1;
chart1.ChartAreas[0].AxisY2.Interval = 1;
chart1.ChartAreas[0].AxisY2.Minimum = 0;
chart1.ChartAreas[0].AxisY2.Maximum = 10;
chart1.ChartAreas[0].AxisY.Minimum = 0;
chart1.ChartAreas[0].AxisY.Maximum = 10;
int number = 0;
string mappedNumber;
for (int i = 1; i < 15; i++)
{
number = 1;
mappedNumber = "1";
chart1.Series["Series1"].Points.AddXY(i, number);
chart1.ChartAreas[0].AxisY2.CustomLabels.Add(number - 0.5, number + 0.5, mappedNumber);
if(i % 3 == 0)
{
chart1.Series["Series1"].Points[chart1.Series["Series1"].Points.Count - 1].IsEmpty = true;
}
}
for (int i = 1; i < 15; i++)
{
number = 2;
mappedNumber = "7";
chart1.Series["Series2"].Points.AddXY(i, number);
chart1.ChartAreas[0].AxisY2.CustomLabels.Add(number - 0.5, number + 0.5, mappedNumber);
if (i % 4 == 0)
{
chart1.Series["Series2"].Points[chart1.Series["Series2"].Points.Count - 1].IsEmpty = true;
}
}
for (int i = 1; i < 15; i++)
{
number = 3;
mappedNumber = "20";
chart1.Series["Series3"].Points.AddXY(i, number);
chart1.ChartAreas[0].AxisY2.CustomLabels.Add(number - 0.5, number + 0.5, mappedNumber);
if (i % 5 == 0)
{
chart1.Series["Series3"].Points[chart1.Series["Series3"].Points.Count - 1].IsEmpty = true;
}
}

Display pictures with their name from database in winforms?

dataGridView1.DataSource = null;
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection.Open();
using (SqlCommand mySqlCommand = new SqlCommand("Select Name, Picture from Employee ", myDatabaseConnection))
{
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(mySqlCommand);
adapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
}
Instead of using datagridview, How I can display the picture with their Name in the panel or other control from the database something like this format http://static.neatorama.com/images/2008-04/yearbook-project-robot-johnny.gif in win form?
For example I have 7 records in the database, the form will display 7 panels with picture and label. And when I click or select a panel it will dipslay more information such as Address, Contacts, Etc in a textBox. If the records in the database is too many to fit in the form there will be a vertical or horizontal scroll bar.
I suggest you to create the objects you need dynamically. You can use "Location" to position your object.
Example :
int cptx = 0;
int cpty = 0;
for(int i=0; i<ds.Tables[0].Rows.Count;i++)
{
PictureBox currentpic = new PictureBox();
Label currentlabel = new Label();
currentpic.Size = new Size(20,20);
currentlabel.Size = new Size(20,20);
currentpic.BorderStyle = BorderStyle.FixedSingle;
currentlabel.Text = "te";
if(cptx >= 4)
{
cptx = 0;
cpty ++;
}
currentpic.Location= new Point((cptx*25),(cpty*50));
currentlabel.Location = new Point((cptx*25),(cpty*50)+25);
This.Controls.Add(currentpic);
cptx ++;
}
This code should do this :
EDIT : I suggest you to take a look at the "User control", the user control allow you to create you own control. So, the picture and the label will be inside a single control. The advantage to use the user control is the control you will create will be totally reusable for your other windows and/or programs.
Form has only one panel (pnlGrid) and panel's AutoScroll property setted as true;
DataTable dtImage = new DataTable();
dtImage.Columns.Add("Path");
dtImage.Columns.Add("Name");
dtImage.Rows.Add(new object[] { "ImagePath", "ImageText" });
dtImage.Rows.Add(new object[] { "ImagePath", "ImageText" });
dtImage.Rows.Add(new object[] { "ImagePath", "ImageText" });
CreateImageGrid(dtImage);
and method;
private void CreateImageGrid(DataTable dtDataSource)
{
int colCount = 5;
int rowCount = 0;
int imgWidth = 100;
int imgHeight = 100;
int imgPadding = 10;
int lblPadding = 5;
int ind = -1;
PictureBox pic = null;
Label lbl = null;
if (dtDataSource.Rows.Count > colCount)
{
rowCount = Convert.ToInt32(dtDataSource.Rows.Count / colCount);
if (Convert.ToInt32(dtDataSource.Rows.Count % colCount) > 0)
{
rowCount++;
}
}
else
{
rowCount = 1;
}
for (int j = 0; j < rowCount; j++)
{
for (int i = 0; i < colCount && dtDataSource.Rows.Count > ((j * colCount) + i); i++)
{
ind = (j * colCount) + i;
pic = new PictureBox();
pic.Image = Image.FromFile(dtDataSource.Rows[ind]["Path"].ToString());
pnlGrid.Controls.Add(pic);
pic.Width = imgWidth;
pic.Height = imgHeight;
pic.Top = (j * (imgHeight + imgPadding)) + imgPadding;
pic.Left = (i * (imgWidth + imgPadding)) + imgPadding;
lbl = new Label();
lbl.Text = dtDataSource.Rows[ind]["Name"].ToString();
pnlGrid.Controls.Add(lbl);
lbl.Left = pic.Left;
lbl.Top = pic.Top + pic.Height + lblPadding;
}
}
}
Note: Text lengths may cause problems, you should define some rules.

WPF - Set Images to Grid

I am trying to set images to a grid I gave created, I am a noob, so please don't get mad at my coding :). I was wondering if there is a way to say set image to grid row 1, grid row 2, etc. I am trying to make a whack a mole game.
private void PopulateGrid()
{
double NumofImages = TUtils.GetIniInt(Moleini, "NumPictures", "pictures", 8);
int ImageSize = TUtils.GetIniInt(Moleini, "ImageSize", "imageSize", 50);
int ImageBorderSize = TUtils.GetIniInt(Moleini, "ImageBorder", "imageBorder", 2);
double NumberOfColumns = TUtils.GetIniInt(Moleini, "NumRowsColumns", "columnNum", 4);
// More Columns than Rows \\
if (NumberOfColumns > NumofImages)
{
MessageBox.Show("There is something wrong with the .ini file.");
Window1.Close();
}
// Math - Get Necessary Variables \\
int ColumnSize = (ImageSize + (4 * ImageBorderSize));
int RowSize = (ImageSize + (4 * ImageBorderSize));
int NumberofRows = (int)Math.Ceiling(NumofImages / NumberOfColumns);
int MainWindowWidth = (TUtils.ToInt(NumberOfColumns.ToString(), 4) * ColumnSize) + 15;
int MainWindowHeight = (NumberofRows * RowSize) + 35;
// Set Window Size \\
Window1.Width = MainWindowWidth;
Window1.Height = MainWindowHeight;
// Create Grid \\
Window1.Content = grid_Main;
grid_Main.Height = MainWindowHeight;
grid_Main.Width = MainWindowWidth;
// Grid Properties \\
for (int i = 0; i < NumberofRows; i++)
{
ColumnDefinition newColumn = new ColumnDefinition();
newColumn.Width = new GridLength(ColumnSize, GridUnitType.Pixel);
grid_Main.ColumnDefinitions.Add(newColumn);
}
for (int i = 0; i < NumberofRows; i++)
{
RowDefinition Row = new RowDefinition();
Row.Height = new GridLength(RowSize, GridUnitType.Pixel);
grid_Main.RowDefinitions.Add(Row);
}
// Fill Grid \\
int RowCount = 0;
int ColumnCount = 0;
for (int i = 0; i < NumofImages; i++)
{
grid_Main.Children.Add(grid_Main);
if (RowCount < NumberofRows)
{
if (ColumnCount < NumberOfColumns)
{
Console.WriteLine("ColumnCount: " + ColumnCount.ToString());
Grid.SetRow(grid_Main, ColumnCount);
Grid.SetColumn(grid_Main, ColumnCount);
ColumnCount++;
}
else
{
RowCount++;
ColumnCount = 0;
Grid.SetRow(grid_Main, ColumnCount);
Grid.SetColumn(grid_Main, ColumnCount);
ColumnCount++;
Console.WriteLine("RowCount: " + RowCount.ToString());
}
}
else
{
break;
}
}
}
...
private Image CreateImage(int ImageNum)
{
// Gets/Sets Necessary Variables \\
double ImageHeight = ImageSize * 0.7;
// Initialize Image \\
System.Windows.Controls.Image newImage = new Image();
// Image Properties \\
newImage.Width = ImageSize;
newImage.Height = ImageHeight;
// Define Name and Content \\
newImage.Name = "Image_" + ImageNum;
String ImageFunction = TUtils.GetIniString(Moleini, "Image" + ImageNum, "PictureFile", Root + "mole2.png");
if (File.Exists(ImageFunction))
{
newImage.Source = new BitmapImage(new Uri(ImageFunction));
}
else
{
MessageBox.Show("Cannot find " + ImageFunction + ".", "Please fix the ini file");
}
return newImage;
}

Merge cells using EPPlus?

I'm using the EPPlus library to read/write Excel files: http://epplus.codeplex.com/
I'm trying to simply merge some cells when writing a document:
using (ExcelPackage pck = new ExcelPackage())
{
//Create the worksheet
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");
//Format the header for column 1-3
using (ExcelRange rng = ws.Cells["A1:C1"])
{
bool merge = rng.Merge;
}
}
There's a property named Merge that simply returns true or false. I thought maybe that would Merge the cells, but it doesn't.
Anyone know how to do this?
You have to use it like this:
ws.Cells["A1:C1"].Merge = true;
instead of:
using (ExcelRange rng = ws.Cells["A1:C1"])
{
bool merge = rng.Merge;
}
If you want to merge cells dynamically, you can also use:
worksheet.Cells[FromRow, FromColumn, ToRow, ToColumn].Merge = true;
All these variables are integers.
You can create a extension method:
public static void Merge(this ExcelRangeBase range)
{
ExcelCellAddress start = range.Start;
ExcelCellAddress end = range.End;
range.Worksheet.Cells[start.Row, start.Column, end.Row, end.Column].Merge = true;
}
You can use this as you would via interop:
range.Merge();
int inicio = CELDA_CUERPO;
bool values = true;
int COLUMNA_A = 0;
int finx_a = 0;
int finy_a = 0;
int COLUMNA_B = 1;
int finx_b = 0;
int finy_b = 0;
//Pintar cabecera:
for (int i = 0; i < ListaCabecera.Length; i++)
{
celda = $"{letras[i]}{CELDA_CABECERA}";
if (i == 0)
{
inicioRango = celda;
}
Sheet.Cells[celda].Value = ListaCabecera[i];
//System.Drawing.Color colFromHex = System.Drawing.ColorTranslator.FromHtml("#B7DEE8");
Sheet.Cells[celda].Style.Font.Color.SetColor(Color.FromArgb(0, 124, 183));
Sheet.Cells[celda].Style.Fill.PatternType = ExcelFillStyle.Solid;
Sheet.Cells[celda].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(232, 235, 249));
Sheet.Cells[celda].Style.Font.Bold = true;
Sheet.Cells[celda].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
}
//Pintar detalle:
for (int i = 0; i < Datos.GetLength(0); i++)
{
for (int j = 0; j < Datos.GetLength(1); j++)
{
celda = $"{letras[j]}{CELDA_CUERPO + i}";
finalizaRango = celda;
if (j < 3) if (Datos[i, j].valor != null && Datos[i, j + 1].valor == null)
{
Sheet.Cells[celda].Style.Font.Color.SetColor(Color.FromArgb(156, 0, 6));
Sheet.Cells[celda].Style.Fill.PatternType = ExcelFillStyle.Solid;
Sheet.Cells[celda].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(255, 199,206));
}
Sheet.Cells[celda].Value = Datos[i, j].valor;
}
//::::::::::::::::::: MERGE A ::::::::::::::::::::
if (i < Datos.GetLength(0) - 1)
{
// :::::::::::::::::::::: x :::::::::::::::::::::::::::::::::
if (values)
{
if (Datos[i, COLUMNA_A].valor == Datos[i, COLUMNA_A].valor)
{
values = false;
finx_a = inicio + i;
finx_b = inicio + i;
//list_x.Add(finx_b);
}
}
else
{
if (Datos[i - 1, COLUMNA_A].valor != Datos[i, COLUMNA_A].valor)
{
finx_a = inicio + i;
}
if (Datos[i - 1, COLUMNA_B].valor != Datos[i, COLUMNA_B].valor)
{
finx_b = inicio + i;
//list_x.Add(finx_b);
}
}
// :::::::::::::::::::::: y (A) :::::::::::::::::::::::::::::::::
if (Datos[i, COLUMNA_A].valor != Datos[i + 1, COLUMNA_A].valor)
{
finy_a = inicio + i;
//list_y.Add(finy);
Sheet.Cells[$"A{finx_a}:A{finy_a}"].Value = Datos[i, COLUMNA_A].valor;
Sheet.Cells[$"A{finx_a}:A{finy_a}"].Merge = true;
Sheet.Cells[$"A{finx_a}:A{finy_a}"].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
}
// :::::::::::::::::::::: y (B) :::::::::::::::::::::::::::::::::
if (Datos[i, COLUMNA_B].valor != Datos[i + 1, COLUMNA_B].valor)
{
finy_b = inicio + i;
//list_y.Add(finy_b);
Sheet.Cells[$"B{finx_b}:B{finy_b}"].Value = Datos[i, COLUMNA_B].valor;
Sheet.Cells[$"B{finx_b}:B{finy_b}"].Merge = true;
Sheet.Cells[$"B{finx_b}:B{finy_b}"].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
}
}
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
}

Categories