Quantcast
Channel: Spread Help » Spread
Viewing all 105 articles
Browse latest View live

SpreadJS Cell Binding Template

$
0
0

You can use the SpreadJS designer to create a binding relation to the data with a template. This saves time by reducing the amount of coding.

The Template option in the designer is used to design the cell binding template.

The Template option is located under the Data tab. Use the template to create field nodes that match the actual data fields. You can also set cell types for the data (Home tab and CellType option). Use the AutoGenerateLabel option to automatically create the binding path label.

Select the green plus symbol to add a field node. Then type the field name (for example, name). You can specify a field option such as CheckBox using the drop-down arrow.

Field List for adding nodes

Field List for adding nodes

The following image illustrates the Template option in the SpreadJS designer.

SpreadJSbindingtemplate

SpreadJS Designer

Drag the nodes to the cell area to generate the layout. You can also use the CellType option to change the cell settings (such as removing a caption from the check box cell).

SpreadJSbindingtemplate2

SpreadJS Designer with Layout

SpreadJSbindingtemplate1

SpreadJS Completed Layout

Save to a SpreadJS designer file (ssjson) if you wish to redesign the template later. Save to a js file to use in an HTML page. The JSON object is saved as a variable field. The field name is the same as the file name. Use the Export option under the File tab to save to a SSJSON or Javascript file.

SpreadJSbindingtemplate4

Save Options

Add code to the page that references the js file. Add code similar to the following:

JavaScript

<!DOCTYPE html>
<html>
<head>
<title>SpreadJS Binding</title>
<link type="text/css" href="./css/gcspread.sheets.8.40.20151.0.css" rel="stylesheet" /> 
<script src="http://code.jquery.com/jquery-2.0.2.js" type="text/javascript"></script>
<script type="text/javascript" src="./scripts/gcspread.sheets.all.8.40.20151.0.min.js"></script>

<script type="text/javascript" src="binding.js"></script>

<script type="text/javascript">  

        $(document).ready(function () {       
var spread = new GcSpread.Sheets.Spread($("#ss")[0],{sheetCount:3});
var data = { name: "bob", age: 20, gender: "Male", email: "bob@test.com", married: true }; // customer's data source.
spread.fromJSON(binding); //Use fromJSON method to load the template, here template variable field is defined in binding.js.
var sheet = spread.getActiveSheet();
sheet.setDataSource(new GcSpread.Sheets.CellBindingSource(data)); //setDataSource with CellBindingSource.
       });
    </script>
</head>
<body>
<div id="ss" style="width: 600px; height: 250px; border: 1px solid gray">
</div>
</body>
</html>

The completed sample appears as follows:

SpreadJSbindingcomplete

Completed Sample in Browser


Creating Charts in a Windows Form Application

$
0
0

Spreadsheets have a lot of different features that make manipulating data very intuitive and easy. One of the main features that helps with visualization of that data is charts. Having the ability to give the power of data visualizations to users and customers can be an invaluable resource for developers. In this blog, I will show you how to create a simple spreadsheet with the ability to add different types of charts based on the data in the spreadsheet.
In this project, there are only two forms: the MainForm and the GenerateChart form. The MainForm contains the Spread component and is the main point of action for the program. The GenerateChart form has logic for handling the interface between user input and chart creation. I started off by creating the MainForm and adding the Spread component to it:

The main form.

The main form.

The “Create Chart” button is what opens up the GenerateChart form, using the following code:

 private void fpSpread1_ButtonClicked(object sender, FarPoint.Win.Spread.EditorNotifyEventArgs e)
        {
            if (fpSpread1.ActiveSheet.ActiveCell.Column.Index == 0 && fpSpread1.ActiveSheet.ActiveCell.Row.Index == 11)
            {
                GenerateChart newChart = new GenerateChart(this);
                newChart.ShowDialog();
            }
            else if (fpSpread1.ActiveSheet.ActiveCell.Column.Index == 0 && fpSpread1.ActiveSheet.ActiveCell.Row.Index == 19)
            {
                if (ChartModel != null)
                    updateChart();
            }
        }

The MainForm is passed to the GenerateChart form as the parent form. Whenever the user chooses to create a new chart, a form like the following opens up:

The GenerateChart form.

The GenerateChart form.

This form allows the user to choose a chart type from a set list using the drop down menu under “Chart Type”. The user can then add a name to the chart and select the series to use for the chart. Once the information is filled in and “Create Chart” is clicked, a chart with the specified properties is created within the MainForm:

The MainForm with a chart loaded into it.

The MainForm with a chart loaded into it.

In my implementation, I wanted to have the chart displayed neatly within the bounds of the rows and columns that comprised the sheet, so I wrote code to calculate the location and size of the chart plot area:

 public void placeChart(string chartName, ChartModel model, CellRange[] cellRanges, int seriesType, int rowStart, int rowCount, int colStart, int colCount)
        {
            SeriesType = seriesType;
            ChartModel = model;
            ChartSizeX = 0;
            ChartSizeY = 0;
            RowHeight = 0;
            if (fpSpread1.Sheets[0].Charts.Count != 0)
                fpSpread1.Sheets[0].Charts.Clear();

            for (int i = colStart; i < colStart + colCount; i++)
            {
                ChartSizeX += (int)fpSpread1.Sheets[0].Columns.Width;
            }
            for (int i = rowStart; i < rowStart + rowCount; i++)
            {
                ChartSizeY += (int)fpSpread1.Sheets[0].Rows.Height;
            }
            for (int i = 0; i < rowStart; i++)
            {
                RowHeight += (int)fpSpread1.Sheets[0].Rows.Height;
            }
            int size = 0;
            for (int i = 0; i < cellRanges.Length; i++)
            {
                if (cellRanges != null)
                    size++;
            }
            tempRange = new CellRange;
            int tempIndex = 0;
            for (int i = 0; i < cellRanges.Length; i++)
            {
                if (cellRanges != null)
                {
                    tempRange[tempIndex] = cellRanges;
                    tempIndex++;
                }       
            }

            if (SeriesType == ClusteredBar)
                fpSpread1.Sheets[0].AddChart(tempRange, typeof(ClusteredBarSeries), ChartSizeX, ChartSizeY, (int)fpSpread1.Sheets[0].Columns[0].Width, RowHeight);
            else if (SeriesType == StackedBar)
                fpSpread1.Sheets[0].AddChart(tempRange, typeof(StackedBarSeries), ChartSizeX, ChartSizeY, (int)fpSpread1.Sheets[0].Columns[0].Width, RowHeight);
            else if (SeriesType == Pie)
                fpSpread1.Sheets[0].AddChart(tempRange, typeof(PieSeries), ChartSizeX, ChartSizeY, (int)fpSpread1.Sheets[0].Columns[0].Width, RowHeight);
            else if (SeriesType == Line)
                fpSpread1.Sheets[0].AddChart(tempRange, typeof(LineSeries), ChartSizeX, ChartSizeY, (int)fpSpread1.Sheets[0].Columns[0].Width, RowHeight);
            else if (SeriesType == Radar)
                fpSpread1.Sheets[0].AddChart(tempRange, typeof(RadarPointSeries), ChartSizeX, ChartSizeY, (int)fpSpread1.Sheets[0].Columns[0].Width, RowHeight);
            updateChart();
        }

In order to provide support for different types of charts, I wrote a function for each type of series. The series methods all pretty much have the same format as the one below:

 public BarSeries createBarSeries(string seriesName, int col, int rowStart, int rowEnd)
        {
            BarSeries series = new BarSeries();
            series.SeriesName = seriesName;
            for (int i = rowStart; i <= rowEnd; i++)
            {
                series.Values.Add(Convert.ToDouble(fpSpread1.Sheets[0].Cells.Value));
                series.CategoryNames.Add(fpSpread1.Sheets[0].Cells.Text);
            }
            return series;
        }

A series of a specific type is created out of the range provided by the parameters. The names are added in order to have labels in the charts. Once a series has been created, a chart can be made using this function:

 public ChartModel createChart(string name)
        {
            LabelArea label = new LabelArea();
            label.Text = name;
            label.Location = new PointF(0.5f, 0.02f);
            label.AlignmentX = 0.5f;
            label.AlignmentY = 0.0f;

            LegendArea legend = new LegendArea();
            legend.Location = new PointF(0.98f, 0.5f);
            legend.AlignmentX = 1.0f;
            legend.AlignmentY = 0.5f;

            ChartModel model = new ChartModel();
            model.LabelAreas.Add(label);
            model.LegendAreas.Add(legend);

            return model;
        }

This function is used to create an initial chart with properties that are changed once cell ranges are created. This can be seen with the button click function in the GenerateChart form:

 private void button1_Click(object sender, EventArgs e)
        {
                MainForm mainForm = (MainForm)this.parentForm;
                string chartType = this.comboBox1.Text;
                string chartName = this.textBox1.Text;
                CellRange[] cellRanges = new CellRange[4];
                if (checkBox1.Checked)
                    cellRanges[0] = new CellRange(3, MainForm.Price, 8, 1);
                if (checkBox2.Checked)
                    cellRanges[1] = new CellRange(3, MainForm.Sold, 8, 1);
                if (checkBox3.Checked)
                    cellRanges[2] = new CellRange(3, MainForm.Produced, 8, 1);
                if (checkBox4.Checked)
                    cellRanges[3] = new CellRange(3, MainForm.Profit, 8, 1);

           if (!this.comboBox1.Text.Equals(null))
           {
                ChartModel chart = mainForm.createChart(chartName);
                if (chartType.Equals("Clustered Bar"))
                {
                    mainForm.placeChart(chartName, chart, cellRanges, MainForm.ClusteredBar, MainForm.ChartAreaRowStart, MainForm.ChartAreaRowCount, MainForm.ChartAreaColStart, MainForm.ChartAreaColCount);
                    this.Close();
                }
                else if (chartType.Equals("Stacked Bar"))
                {
                    mainForm.placeChart(chartName, chart, cellRanges, MainForm.StackedBar, MainForm.ChartAreaRowStart, MainForm.ChartAreaRowCount, MainForm.ChartAreaColStart, MainForm.ChartAreaColCount);
                    this.Close();
                }
                else if (chartType.Equals("Pie"))
                {
                    mainForm.placeChart(chartName, chart, cellRanges, MainForm.Pie, MainForm.ChartAreaRowStart, MainForm.ChartAreaRowCount, MainForm.ChartAreaColStart, MainForm.ChartAreaColCount);
                    this.Close();
                }
                else if (chartType.Equals("Line"))
                {
                    mainForm.placeChart(chartName, chart, cellRanges, MainForm.Line, MainForm.ChartAreaRowStart, MainForm.ChartAreaRowCount, MainForm.ChartAreaColStart, MainForm.ChartAreaColCount);
                    this.Close();
                }
                else if (chartType.Equals("Radar Point"))
                {
                    mainForm.placeChart(chartName, chart, cellRanges, MainForm.Radar, MainForm.ChartAreaRowStart, MainForm.ChartAreaRowCount, MainForm.ChartAreaColStart, MainForm.ChartAreaColCount);
                    this.Close();
                }
            }
        }

These particular charts can handle at most 4 series (the 4 categories in the spreadsheet). Every chart created can have less than 4 series, and the other series could be passed in as null values. Both creating a chart and updating a chart utilized the updateChart function, which gives the chart all of its labels and legend and ensure that the data is displayed correctly:

 public void updateChart()
        {
            if (SeriesType == ClusteredBar)
            {
                ClusteredBarSeries bars = new ClusteredBarSeries();
                for (int i = 0; i < tempRange.Length; i++)
                    bars.Series.Add(createBarSeries(SeriesNames[tempRange.Column - 1], tempRange.Column, 3, 11));
                fpSpread1.Sheets[0].Charts[0].Model.PlotAreas[0].Series[0] = bars;
                YPlotArea barChart = (YPlotArea)fpSpread1.Sheets[0].Charts[0].Model.PlotAreas[0];
                barChart.Vertical = false;
            }
            else if (SeriesType == StackedBar)
            {
                StackedBarSeries bars = new StackedBarSeries();
                for (int i = 0; i < tempRange.Length; i++)
                    bars.Series.Add(createBarSeries(SeriesNames[tempRange.Column - 1], tempRange.Column, 3, 11));
                fpSpread1.Sheets[0].Charts[0].Model.PlotAreas[0].Series[0] = bars;
                YPlotArea barChart = (YPlotArea)fpSpread1.Sheets[0].Charts[0].Model.PlotAreas[0];
                barChart.Vertical = false;
            }
            else if (SeriesType == Pie)
            {
                for (int i = 0; i < tempRange.Length; i++)
                    fpSpread1.Sheets[0].Charts[0].Model.PlotAreas[0].Series = createPieSeries(SeriesNames[tempRange.Column - 1], tempRange.Column, 3, 11);
            }
            else if (SeriesType == Line)
            {
                for (int i = 0; i < tempRange.Length; i++)
                    fpSpread1.Sheets[0].Charts[0].Model.PlotAreas[0].Series = createLineSeries(SeriesNames[tempRange.Column - 1], tempRange.Column, 3, 11);
            }
            else if (SeriesType == Radar)
            {
                for (int i = 0; i < tempRange.Length; i++)
                    fpSpread1.Sheets[0].Charts[0].Model.PlotAreas[0].Series = createRadarPointSeries(SeriesNames[tempRange.Column - 1], tempRange.Column, 3, 11);
            }

            fpSpread1.Sheets[0].Charts[0].Model.LabelAreas.Add(ChartModel.LabelAreas[0]);
            fpSpread1.Sheets[0].Charts[0].CanMove = FarPoint.Win.Spread.DrawingSpace.Moving.None;
            fpSpread1.Sheets[0].Charts[0].CanSize = FarPoint.Win.Spread.DrawingSpace.Sizing.None;
        }

Now whenever a chart is created, a user can edit the values that the chart is based on and click the “Update Chart” button to have the changes reflected in the chart.

In this blog, I have shown how to create a Windows Form application that utilizes Spread’s charting capabilities. The creation of charts is a simple and intuitive process that makes it easy for developers to add charts to their spreadsheet applications. Different kinds of charts can be created with very simple code that is generalized across most of the chart types. With this functionality, Spread can be a powerful tool for data visualization.

The download link below contains the project files for this sample.
WinForms Charting

Spread ASP.NET and Sheet Skins

$
0
0

Spread ASP.NET allows you to customize the appearance of a sheet by applying a “skin” to it. Built-in (default) skins are provided with Spread to create common formats. You can also create your own custom skin and save it to use again or share it, similar to a template. A skin, whether built-in or custom, can be applied to any number of sheets in a Spread component. Because a skin can be saved to a file, you can use it across projects and share it with other developers. Skins allow you to apply a consistent look across sheets or the control.

A skin includes the following appearance settings:

  • cell colors
  • header colors
  • whether headers are displayed
  • bold header text
  • row colors
  • selection colors
  • Spread background color
  • grid lines
  • cell spacing

You can save several appearance properties of a sheet as a custom skin. Any custom skins that you create can be saved to a file in the Spread Designer using the SheetSkin editor.

Use the following steps to create a custom skin with the SheetSkin editor.

  1. Select Sheet Skins… from the FpSpread Tasks dialog to display the SheetSkin editor. You can also access the SheetSkin editor from the Settings menu in the Spread Designer.

    SpreadASPDesigner

    Select SheetSkins Editor

  2. Use the Custom tab to create your own skin. Create a custom skin by changing the properties in the Property window. Click Save when you are done making changes. The Skin Repository dialog is displayed and you can enter a name for your skin.
SpreadASPdesignercustom

Custom Tab

SpreadASPdesignersave

Skin Repository

After you select OK, the file name is displayed in the list of saved custom skins in the Saved tab. You can use the custom skin again later by selecting the Saved tab and then applying the appropriate custom skin.

The skn file is saved to GrapeCity\Spread Studio 8\ASP.NET\v8.40.xxxxx\Skins or ComponentOne\Spread Studio 8\ASP.NET\v8.40.xxxxx\Skins depending on the version of Spread you are using.

You can use the Apply button in the SheetSkin editor to review the changes as shown in the following image.

SpreadASPdesignerapply

Review Changes

You can also access the SheetSkin editor from a menu in the Spread Designer.

SpreadASPdesignermenu

SheetSkin Editor

Use the following steps to access the SheetSkin editor from a menu in the Spread Designer.

  1. Select the Settings tab.
  2. Select the SheetSkin icon under the Appearance Settings section.
  3. Select the Custom tab to create a custom skin.
  4. Set the properties.
  5. Click Save and type in a name for the custom skin.
  6. Click OK.

Click Apply and Exit to close the Spread Designer.

This example code sets the sheet to use a custom skin. Use the SheetSkin object constructor, and set its parameters to specify the settings for the skin.

SpreadASPsheetcode

Custom Skin

C#

FarPoint.Web.Spread.SheetSkin myskin = new FarPoint.Web.Spread.SheetSkin("MySkin", System.Drawing.Color.BlanchedAlmond, System.Drawing.Color.Bisque, System.Drawing.Color.Navy, 2, 
System.Drawing.Color.Blue, GridLines.Both, System.Drawing.Color.Beige, System.Drawing.Color.BurlyWood, 
System.Drawing.Color.AntiqueWhite, System.Drawing.Color.Brown, System.Drawing.Color.Bisque, System.Drawing.Color.Bisque, true, true, true, true, false);
myskin.Apply(FpSpread1.Sheets[0]);

VB

Dim myskin As New FarPoint.Web.Spread.SheetSkin("MySkin", System.Drawing.Color.BlanchedAlmond, System.Drawing.Color.Bisque, System.Drawing.Color.Navy, 2, System.Drawing.Color.Blue, GridLines.Both, System.Drawing.Color.Beige, System.Drawing.Color.BurlyWood, System.Drawing.Color.AntiqueWhite, System.Drawing.Color.Brown, 
System.Drawing.Color.Bisque, System.Drawing.Color.Bisque, True, True, True, True, False)
myskin.Apply(FpSpread1.Sheets(0))

The following example sets the first sheet to use the Colorful2 predefined skin (built-in skin).

Use the GetAt method of the DefaultSkins object to specify the index of the default skin to return, then the default skin Apply method to assign it to a specific FpSpread component, collection of sheets, or sheet.

C#

FarPoint.Web.Spread.DefaultSkins.Colorful2. Apply(FpSpread1.Sheets[0]);

VB

FarPoint.Web.Spread.DefaultSkins.Colorful2. Apply(FpSpread1.Sheets(0))

This example applies the built-in skin to the control.

C#

FarPoint.Web.Spread.DefaultSkins.Colorful2.Apply(FpSpread1);

VB

FarPoint.Web.Spread.DefaultSkins.Colorful2.Apply(FpSpread1)

You can use the Save method to save a skin to a file or the Load method to load a sheet skin with code.

Winforms Subeditor and Captions

$
0
0

When creating large spreadsheets, information can be hard to convey without enlarging cells or spanning multiple row and columns. It could be useful to hide information from the user until it is necessary, as well as provide a way to easily edit a cell without having to enlarge it if it is too small. Spread provides shape and subeditor functionality that will allow you to accomplish these tasks with little effort. In this blog, I will show you how to use shapes to create captions for cells as well as how to create a subeditor to make editing cells easier, as well as providing rich features or complex UI editors that cannot be displayed inline in a Windows Forms application using Visual Studio 2013.
To start off, I created two forms: a MainForm where the application is run from, and a TextSubEditor form that represents the subeditor. The TextSubEditor forms is very simplistic, containing a text box and two buttons:

The subeditor form.

The subeditor form.

In this example, I named the text box “txt”, and the two buttons “OkButton” and “CancelButton”. To ensure that this was not just a form, I had to implement the ISubEditor interface, and the subsequent methods GetLocation, GetSubEditorControl, GetValue, SetValue, and GetPreferredSize:

 public Point GetLocation(Rectangle rect)
 {
     Point pt = new Point(0);
     Size sz = GetPreferredSize();
     pt.Y = (Screen.PrimaryScreen.WorkingArea.Height / 2) - (sz.Height / 2);
     pt.X = (Screen.PrimaryScreen.WorkingArea.Width / 2) - (sz.Width / 2);
     return pt;
 }
 public Control GetSubEditorControl()
 {
    return this;
 }
 public object GetValue()
 {
     return txt.Text;
 }
 public void SetValue(object value)
 {
     txt.Text = value.ToString();
 }
 public Size GetPreferredSize()
 {
     return new Size(310, 200);
 }

I also had to implement the event handlers for changing the text in the text box as well as clicking the buttons:

 private void txt_TextChanged(object sender, EventArgs e)
 {
     Text = txt.Text;
 }
 private void okButton_Click(object sender, EventArgs e)
 {
     if (ValueChanged != null)
         ValueChanged(this, EventArgs.Empty);
     if (CloseUp != null)
         CloseUp(this, EventArgs.Empty);
 }
 private void cancelButton_Click(object sender, EventArgs e)
 {
     if (CloseUp != null)
         CloseUp(this, EventArgs.Empty);
 }

Once that was done, I wanted to have a text cell that had an ellipsis button in it that would open the subeditor I had just created. To do this, I implemented my version of a text cell type, with code that only overrode the GetEditorControl method of the TextCellType:

  public override System.Windows.Forms.Control GetEditorControl(System.Windows.Forms.Control parent, FarPoint.Win.Spread.Appearance appearance, float zoomFactor)
  {
     System.Windows.Forms.Control myControl = base.GetEditorControl(parent, appearance, zoomFactor);
     ((GeneralEditor)myControl).ButtonStyle = FarPoint.Win.ButtonStyle.PopUp;
     return myControl;
  }

This completed the pieces I needed to actually start putting the program together. On my MainForm, I added the Spread component from the toolbox and docked it to fit the entire form:

The main form.

The main form.

To allow a cell to have the subeditor I created, I have to specify the cell type’s cell editor. In this case, I assign the first cell’s CellType and its subeditor to the celltype and subeditor I created:

 MyTextCellType t = new MyTextCellType();
 t.MaxLength = 100;
 t.SubEditor = new TextSubEditor();
 fpSpread1.ActiveSheet.Cells[0, 0].CellType = t;
 fpSpread1.ActiveSheet.Cells[0, 0].Text = "This is an example cell with a subeditor.";
 fpSpread1.ActiveSheet.SetColumnWidth(0, 100);
 t.SubEditor.SetValue(fpSpread1.ActiveSheet.Cells[0, 0].Text);

Now when I enter edit mode in the first cell, I can click on the ellipsis button (specified as the PopUp button style in the Cell Type’s getEditorControl method that I overrode) and open up the subeditor for the cell. There is one problem with this however: the user might not know that they can open up the subeditor with the ellipsis button. I want a way to show them this information without having it always be visible in the sheet. I can get this functionality by using shapes.
Most of the time, tutorials in programs involve speech bubbles or circling certain areas of the window to direct the user’s attention. Spread allows you to create shapes and move them around, serving as the basis for this functionality. To start off, I created two shapes and set their visible property to false:

 private void CreateShapes()
 {
     FarPoint.Win.Spread.DrawingSpace.CaptionBalloonShape balloon = new FarPoint.Win.Spread.DrawingSpace.CaptionBalloonShape();
     balloon.Parent = fpSpread1;
     balloon.Name = "customTextBubble";
     balloon.Height = 75;
     balloon.Width = 150;
     balloon.FlipVertical = true;
     balloon.Text = "\n\nPress the ... to open subeditor";
     balloon.TextWrap = true;
     balloon.CanRenderText = true;
     fpSpread1.ActiveSheet.AddShape(balloon, 0, 0);
     balloon.Visible = false;

     FarPoint.Win.Spread.DrawingSpace.SquareCaptionBalloonShape squareBalloon = new FarPoint.Win.Spread.DrawingSpace.SquareCaptionBalloonShape();
     squareBalloon.Parent = fpSpread1;
     squareBalloon.Name = "numberBubble";
     squareBalloon.Height = 75;
     squareBalloon.Width = 150;
     squareBalloon.FlipVertical = true;
     squareBalloon.Text = "\n\nThis is a number cell";
     squareBalloon.TextWrap = true;
     squareBalloon.CanRenderText = true;
     fpSpread1.ActiveSheet.AddShape(squareBalloon, 0, 0);
     squareBalloon.Visible = false;
 }

For my custom text cell with its subeditor, I want the tutorial message to only be displayed when focus is set to the cell. For this, I have to use the EnterCell and LeaveCell event handlers:

 private void fpSpread1_EnterCell(object sender, EnterCellEventArgs e)
 {
     if (fpSpread1.ActiveSheet.Cells[e.Row, e.Column].CellType is MyTextCellType)
     {
         fpSpread1.EditMode = true;
         Rectangle cell = fpSpread1.GetCellRectangle(0, 0, e.Row, e.Column);
         fpSpread1.ActiveSheet.GetShape("customTextBubble").Left = cell.X;
         fpSpread1.ActiveSheet.GetShape("customTextBubble").Top = cell.Y;
         fpSpread1.ActiveSheet.GetShape("customTextBubble").Visible = true;
     }
 }

 private void fpSpread1_LeaveCell(object sender, LeaveCellEventArgs e)
 {
     if (fpSpread1.ActiveSheet.Cells[e.Row, e.Column].CellType is MyTextCellType)
     {
         fpSpread1.ActiveSheet.GetShape("customTextBubble").Visible = false;
     }
 }

When the user enters a cell that has the CellType I created, the customTextBubble shape is moved to its location and it is set to be visible. When the user leaves the cell, that shape is made invisible again.
While this functionality is great, it might also be useful to show messages when the user simply hovers over a cell. To do this, I created a number cell to test it on and utilized the TextToolTip functionality of Spread. In order to implement this, I had to set the TextTipPolicy and its delay:

 NumberCellType nt = new NumberCellType();
 fpSpread1.ActiveSheet.Cells[2, 0].CellType = nt;
 fpSpread1.ActiveSheet.Cells[2, 0].Value = 123456;

 fpSpread1.TextTipPolicy = FarPoint.Win.Spread.TextTipPolicy.Floating;
 fpSpread1.TextTipDelay = 500;

Then, I had to use the TextTipFetch event handler to show the shape I created rather than the text tool tip:

 private void fpSpread1_TextTipFetch(object sender, TextTipFetchEventArgs e)
 {
     e.ShowTip = false;
     if (fpSpread1.ActiveSheet.Cells[e.Row, e.Column].CellType is NumberCellType)
     {
         Rectangle cell = fpSpread1.GetCellRectangle(0, 0, e.Row, e.Column);
         fpSpread1.ActiveSheet.GetShape("numberBubble").Left = cell.X;
         fpSpread1.ActiveSheet.GetShape("numberBubble").Top = cell.Y;
         fpSpread1.ActiveSheet.GetShape("numberBubble").Visible = true;
     }
     else
     {
         fpSpread1.ActiveSheet.GetShape("numberBubble").Visible = false;
     }
 }

Now the user can hover over cells with the NumberCellType and a message bubble will be displayed:

The shape that utilizes the text tip fetch event handler.

The shape that utilizes the text tip fetch event handler.

Another bubble will also be displayed when the user sets focus to the custom text cell:

The shape that uses the enter/leave cell event handlers.

The shape that uses the enter/leave cell event handlers.

In this blog, I have shown you how to create a subeditor to utilize functionality that cannot normally be displayed inline. I have also shown a way to create captions that can be used in many different ways. Spread is a powerful data manipulation tool, but it can also help users view and edit that data without having to know exactly how a particular spreadsheet might work.

The following is a download link for the files for this project:
WinformsSubeditor

Spread WinRT and Selection Colors

$
0
0

You can change the selection colors and the selection theme in Spread WinRT. This allows you to draw more attention to selections or change the selection colors to match the application appearance.

You can specify selection colors with the SelectionBorderColor, SelectionBackground, or SelectionBorderThemeColor property. The SelectionBackground property uses a Brush object. The SelectionBorderColor property uses a Color object. The SelectionBorderThemeColor property uses a string object.

This example sets the SelectionBorderColor and SelectionBackground properties.

SpreadWinRTselcolor

Selection Colors

C#

gcSpreadSheet1.Sheets[0].SelectionBackground = new SolidColorBrush(Windows.UI.Colors.Magenta);
gcSpreadSheet1.Sheets[0].SelectionBorderColor = Windows.UI.Color.FromArgb(150, 10, 100, 99);

VB

GcSpreadSheet1.Sheets(0).SelectionBackground = New SolidColorBrush(Windows.UI.Colors.Magenta)
GcSpreadSheet1.Sheets(0).SelectionBorderColor = Windows.UI.Color.FromArgb(150, 10, 100, 99)

You can set a theme color to one of six accent colors, two dark colors, two light colors, a hyperlink color, or a followed hyperlink color. The color property names are Accent 1-6, BackgroundColor1, BackgroundColor2, TextColor1, TextColor2, FollowedHyperlink, and Hyperlink. You can specify an additional shade with the Accent option (100 to -50). The properties are listed in the ThemeColor class.

This example sets the SelectionBorderThemeColor property.

SpreadWinRTselcolor2

Selection Theme

C#

gcSpreadSheet1.Sheets[0].SelectionBorderThemeColor = "Accent 3 40";

VB

GcSpreadSheet1.Sheets(0).SelectionBorderThemeColor = "Accent 3 40"

This example uses the Hyperlink option for the SelectionBorderThemeColor property.

SpreadWinRTselcolor1

Selection Theme

C#

gcSpreadSheet1.Sheets[0].SelectionBorderThemeColor = "Hyperlink";

VB

GcSpreadSheet1.Sheets(0).SelectionBorderThemeColor = "Hyperlink"

MultiRow Template Designer

$
0
0

You can use the MultiRow template designer to design the layout of your data. The template items can be placed in any order. This allows you to display one record in multiple rows and requires less time to create a layout.

A template can have a column header, row, and column footer sections.

You can use a default template or add a new template.

This example creates a new template. Select Project and then Add New Item.

mrowNewItem

Add New Item

Select the MultiRow 7.0 Template.

mrowSelectTemplate

MultiRow 7.0 Template

The following image displays a default template.

mrowCreateLayout

Default Template

You can drag items to the template from the Toolbox.

mrowdesignitems

Toolbox

Select the Task icon on the MultiRow control and then select the new template (Template1) to add the template to the control.

mrowAddTemplate

Select Template

You can use code to add data to cells in the control or you can bind the control to a data source at design time. The following image displays the design time data source option. Use the Add Project Data Source option to connect to a data source. This example uses the nwnd database.

mrowAddDataSource

Add Data Source

Assign a field to the item in the template (for example, ShipName to a text box cell).

mrowAssignField

Assign Field

You can type text in the column header section in the template.

mrowHeaderText

Header Text

You can move items to any location in the template. This allows you to arrange the layout of your data.

mrowPlace

Place Items

The template in the preceding image would appear as follows:

mrowrowsection

Sample Data

Spread 8 COM and Microsoft Visual Studio 2015

$
0
0

You can use the Spread 8 COM control in Microsoft Visual Studio 2015 with Microsoft Windows 10. Spread Windows Forms is a .NET control and is a better option; however, you may have older code or projects where you need to use Spread 8 COM.

Use the following steps to create a new project in Visual Studio 2015 and add the Spread 8 COM control.

    1. Select File, New, and then Project in Visual Studio 2015.

      filenew

      New Project

    2. Select Windows under the Visual C# or Visual Basic sections. Then select Windows Forms Application. Specify a name and location and then select OK.

      windowsforms

      Windows Forms Application

    3. Right click on the Toolbox and select Choose Items…

      chooseitems

      Add Item

    4. Select Farpoint Spread 8.0 from the COM Components tab. Then select OK.

      comtab

      Components

    5. Select Spread and drag it to the form from the Toolbox.
      dragcontrol

      Toolbox

      controlform

      Form with Spread Control

    6. Select MSDATASRC and stdole references in the Solution Explorer and set Embed Interop Types to False.

      Msdatasrc

      Reference

      stdole

      Reference

    7. Select Project and Properties.

      projectprop

      Project Properties

    8. Verify that the Prefer 32-bit option is checked under the Build menu.

      Buildsetting

      Build Options

    9. Add code and run the project. This code creates multiple headers and adds header text.

C#

axfpSpread1.MaxCols = 8;
axfpSpread1.MaxRows = 12;
axfpSpread1.ColHeaderRows = 3;
axfpSpread1.RowHeaderCols = 2;
axfpSpread1.AddCellSpan(1, -1000, 8, 1);
axfpSpread1.SetText(1, -1000, "Fiscal Year 2015");
axfpSpread1.AddCellSpan(1, -999, 2, 1);
axfpSpread1.SetText(1, -999, "1st Quarter");
axfpSpread1.AddCellSpan(3, -999, 2, 1);
axfpSpread1.SetText(3, -999, "2nd Quarter");
axfpSpread1.AddCellSpan(5, -999, 2, 1);
axfpSpread1.SetText(5, -999, "3rd Quarter");
axfpSpread1.AddCellSpan(7, -999, 2, 1);
axfpSpread1.SetText(7, -999, "4th Quarter");
axfpSpread1.SetText(1, -998, "East");
axfpSpread1.SetText(2, -998, "West");
axfpSpread1.SetText(3, -998, "East");
axfpSpread1.SetText(4, -998, "West");
axfpSpread1.SetText(5, -998, "East");
axfpSpread1.SetText(6, -998, "West");
axfpSpread1.SetText(7, -998, "East");
axfpSpread1.SetText(8, -998, "West");
axfpSpread1.AddCellSpan(-1000, 1, 1, 12);
axfpSpread1.SetText(-1000, 1, "Store #");
complete

Completed Project

Using Charts in SpreadJS

$
0
0

SpreadJS is a useful tool for adding the power of Spread to webpages using JavaScript. Being able to easily display data in a spreadsheet without having to create html tables by hand is useful for web developers who simply want to convey information. SpreadJS has the concept of Sparklines, which are small graphs contained within cells. While this is useful, it might also be desirable to create large graphs that don’t depend on being inside of a cell. To do this, we can use a Custom Floating Object to wrap a third-party chart into SpreadJS. In this blog, I will show you how to insert a D3-based chart inside of SpreadJS.

To start off, I needed some sample data to display in the chart, so I created a function that simply generates new data every time the page loads:

var data = (function () {
var chartData = [];
for (var i = 0; i < 3; i++) {
    var columnData = [];
    columnData.push("Data" + i);
        for (var j = 0; j < 10; j++) {
            columnData.push( Math.round(Math.random() * 100));
        }
        chartData.push(columnData);
    }
    return chartData;
})();

Next, I created a spread component on the page and placed the data in it:

var spread = new GcSpread.Sheets.Spread($("#ss").get(0));
activeSheet = spread.getActiveSheet();
activeSheet.isPaintSuspended(true);
activeSheet.setArray(0, 0, data);
activeSheet.isPaintSuspended(false);

To add the chart, we first have to create a floating object that will contain it, and add it to the sheet:

var floatChart = new GcSpread.Sheets.CustomFloatingObject("chart", 10, 100, 600, 200);
floatChart.Content($("
")); activeSheet.addFloatingObject(floatChart);

Now that the container is there, we have to put a chart in it. To do this, we have to bind the CustomFloatingObjectLoaded event to a new handler function:

activeSheet.bind(GcSpread.Sheets.Events.CustomFloatingObjectLoaded, function (sender, args) {
    var chartContainer = $(args.element);
    chartContainer.attr("id", "chart");
    chart = c3.generate({
        data: {
            columns: args.sheet.getArray(0,0,3,10)
        }
    });
});

With the c3 library, the type of chart defaults as a line chart. To change the type of chart, simply specify the “types” property of data for each series. More information on using c3 can be found here: http://c3js.org/gettingstarted.html.

To ensure that the chart changes size with the floating object, we can bind a function to the FloatingObjectChanged event:

activeSheet.bind(GcSpread.Sheets.Events.FloatingObjectChanged, function (sender, args) {
    if (args.propertyName === "width" || args.propertyName === "height") {
        chart.resize({ width: args.floatingObject.width(), height: args.floatingObject.height() });
    }
});

Lastly, if that data changes, we can have those changes reflected in the chart by binding a function to the ValueChanged event:

activeSheet.bind(GcSpread.Sheets.Events.ValueChanged, function (sender, args) {
    chart = c3.generate({
        data: {
            columns: args.sheet.getArray(0, 0, 3, 10)
        }
    });
});

When these lines of code are added as script for a page, we can see that there is a Spread component with a nice graph that can be moved around and resized. It also reflects the data in the sheet, so we won’t have to reload the page with new data every time we want to change the graph.

The download for this sample can be found at the bottom of this blog.

This is the completed webpage with SpreadJS

This is the completed webpage with SpreadJS


SpreadJS Charts

Adding a Ribbon to SpreadJS

$
0
0

It is common to need users controls, such as a toolbar, to allow end-users to manipulate SpreadJS sheets and their data. This tutorial will give step-by-step instructions for adding an open source Ribbon toolbar to an instance of SpreadJS. The toolbar we are using is an open source JQuery ribbon that can be found here: https://www.openhub.net/p/jquery-ui-ribbon. Other ribbons can be used, but this is a simple example to show how we can go about connecting a ribbon to SpreadJS.
Download the source code for this tutorial: SpreadJS Ribbon

Set Up the Project

Set up your project by placing the SpreadJS scripts and the source code for the Ribbon control lined above in the directory where you will create the SpreadJS web page.
Start by creating a web page with a SpreadJS widget. Find instructions here: http://sphelp.grapecity.com/webhelp/SpreadJSWeb/webframe.html#addcontrol.html
Your spreadsheet should look like the one in the screen shot below.

Example HTML page with SpreadJS

Example HTML page with SpreadJS

Add the Ribbon to Your Page

Add the links to the scripts found in the open source Ribbon you downloaded.

    <link type="text/css" href="../../themes/base/ui.all.css" rel="stylesheet" />
    <link type="text/css" href="../../themes/base/ui.tabs.css" rel="stylesheet" />
    <link type="text/css" href="../../style/ui.button.css" rel="stylesheet" />
    <link type="text/css" href="../../style/ui.ribbon.css" rel="stylesheet" />
    <link type="text/css" href="../../style/ui.orbButton.css" rel="stylesheet" />
    <link type="text/css" href="../../style/ui.ribbon.style.msoffice.css" rel="stylesheet" />
    <link type="text/css" href="../../style/msoffice-icons.css" rel="stylesheet" />

    <script language="JavaScript" type="text/javascript" src="../../jquery-1.3.2.js"></script>

    <script language="JavaScript" type="text/javascript" src="../../ui/ui.core.js"></script>
    <script language="JavaScript" type="text/javascript" src="../../ui/ui.tabs.js"></script>
    <script language="JavaScript" type="text/javascript" src="../../ui/ui.ribbon.js"></script>
    <script language="JavaScript" type="text/javascript" src="../../ui/ui.orbButton.js"></script>
    <script language="JavaScript" type="text/javascript" src="../../ui/ui.button.js"></script>
    <script language="JavaScript" type="text/javascript">
        jQuery(function ($) {
            $('#log').dblclick(function () { $('#log').empty(); });

            $('.ui-button').button({ useSlidingDoors: true });
            $('#ribbon-msoffice').wrap('<div class="style-msoffice"></div>');

            $('#ribbon, #ribbon-msoffice').ribbon({
                collapsible: true
            })
        });
    </script>

Now, set the page to display the ribbon by adding this html code to the body above the SpreadJS widget:

<div id="ribbon-msoffice" style="width:700px; border: 1px solid gray">
        <div id="ribbon-msofficeContextData" style="display:none;"><label>Data</label></div>
        <ul>
            <li><a href="#ribbon-msofficeTabHome"><span><label>Home</label></span></a></li>
            <li><a href="#ribbon-msofficeTabInsert"><span><label>Insert</label></span></a></li>
            <li><a href="#ribbon-msofficeTabView"><span><label>View</label></span></a></li>
        </ul>
        <div id="ribbon-msofficeTabHome">
            <ul>
                <li id="groupClipboard_ribbon-msofficeTabHome">
                    <div>
                        <button class="ui-ribbon-element ui-ribbon-control ui-button ui-ribbon-large-button" id="ribbon-msofficeButtonPaste" title="Paste"><span class="ui-icon msoffice-icon-paste-32x32"></span><span class="ui-button-label">Paste</span></button>
                        <ul class="ui-ribbon-element ui-ribbon-list">
                            <li><button class="ui-ribbon-element ui-ribbon-control ui-button ui-ribbon-simple-button" id="ribbon-msofficeButtonCut" title="Cut"><span class="ui-icon msoffice-icon-cut-22x22"></span><span class="ui-button-label">Cut</span></button></li>
                            <li><button class="ui-ribbon-element ui-ribbon-control ui-button ui-ribbon-simple-button" id="ribbon-msofficeButtonCopy" title="Copy"><span class="ui-icon msoffice-icon-copy-22x22"></span><span class="ui-button-label">Copy</span></button></li>
                        </ul>
                    </div>
                    <h3><span>Clipboard</span></h3>
                </li>
                <li id="groupRows_ribbon-msofficeTabHome">
                    <div>
                        <ul class="ui-ribbon-element ui-ribbon-list">
                            <li><button class="ui-ribbon-element ui-ribbon-control ui-button ui-ribbon-simple-button" id="ribbon-msofficeButtonAddRow" title="Add Row"><span class="ui-icon ui-icon-none"></span><span class="ui-button-label">Add Row</span></button></li>
                            <li><button class="ui-ribbon-element ui-ribbon-control ui-button ui-ribbon-simple-button" id="ribbon-msofficeButtonRemoveRow" title="Remove Row"><span class="ui-icon ui-icon-none"></span><span class="ui-button-label">Remove Row</span></button></li>
                        </ul>
                    </div>
                    <h3><span>Rows</span></h3>
                </li>
                <li id="groupColumns_ribbon-msofficeTabHome">
                    <div>
                        <ul class="ui-ribbon-element ui-ribbon-list">
                            <li><button class="ui-ribbon-element ui-ribbon-control ui-button ui-ribbon-simple-button" id="ribbon-msofficeButtonAddColumn" title="Add Column"><span class="ui-icon ui-icon-none"></span><span class="ui-button-label">Add Column</span></button></li>
                            <li><button class="ui-ribbon-element ui-ribbon-control ui-button ui-ribbon-simple-button" id="ribbon-msofficeButtonRemoveColumn" title="Remove Column"><span class="ui-icon ui-icon-none"></span><span class="ui-button-label">Remove Column</span></button></li>
                        </ul>
                    </div>
                    <h3><span>Columns</span></h3>
                </li>
            </ul>
        </div>
        <div id="ribbon-msofficeTabInsert">
            <ul>
                <li id="groupSheet_ribbon-msofficeTabInsert">
                    <div>
                        <button class="ui-ribbon-element ui-ribbon-control ui-button ui-ribbon-large-button" id="ribbon-msofficeButtonNewSheet" title="New Sheet"><span class="ui-icon msoffice-icon-menu-new-32x32"></span><span class="ui-button-label">New Sheet</span></button>
                        <button class="ui-ribbon-element ui-ribbon-control ui-button ui-ribbon-large-button" id="ribbon-msofficeButtonDeleteSheet" title="Delete Sheet"><span class="ui-icon msoffice-icon-delete-24x24""></span><span class="ui-button-label">Delete Sheet</span></button>
                    </div>
                    <h3><span>Sheet</span></h3>
                </li>
            </ul>
        </div>
        <div id="ribbon-msofficeTabView">
            <ul>
                <li id="groupZoom_ribbon-msofficeTabView">
                    <div>
                        <button class="ui-ribbon-element ui-ribbon-control ui-button ui-ribbon-large-button" id="ribbon-msofficeButtonZoomIn" title="Zoom In"><span class="ui-icon msoffice-icon-zoom-32x32"></span><span class="ui-button-label">Zoom In</span></button>
                        <button class="ui-ribbon-element ui-ribbon-control ui-button ui-ribbon-large-button" id="ribbon-msofficeButtonZoomOut" title="Zoom Out"><span class="ui-icon msoffice-icon-zoom-32x32"></span><span class="ui-button-label">Zoom Out</span></button>
                        <button class="ui-ribbon-element ui-ribbon-control ui-button ui-ribbon-large-button" id="ribbon-msofficeButtonZoom100" title="100%"><span class="ui-icon msoffice-icon-zoom100-32x32"></span><span class="ui-button-label">100%</span></button>
                    </div>
                    <h3><span>Scale</span></h3>
                </li>
            </ul>
        </div>
    </div>

The ribbon is now displayed on the page with Spread and it looks similar to a ribbon you would see in a Microsoft Office program:

HTML page with SpreadJS and a ribbon

HTML page with SpreadJS and a ribbon

Make the Buttons Work with SpreadJS

To add the functionality for these buttons in the script for SpreadJS on the page, find the id for each button and use that id to write a function for clicking on that button. This can be done using:

$(“#idOfButton”).click(function() { });

The code that is defined within the function will be called whenever that particular button is clicked. The following is an example that adds functionality to the New Sheet button in the Insert tab:

    $("#ribbon-msofficeButtonNewSheet").click(function () {
        spread.addSheet();
    });

Once the code for each button has been written, the page with the SpreadJS component and ribbon will be displayed correctly, and the user can interact with the SpreadJS component using the buttons in the ribbon.

Spread WPF and Validation

$
0
0

You can use data validation to control the type of data and values that users are allowed to enter in a cell. This can be useful if you only want to allow correct values in a cell based on your data. Spread WPF supports data validation.

Create validators to validate the user data. You can display a list of valid values for the user and display an invalid data image if the user types invalid data.

You can use any of several types of validator methods to create the validation criteria.

  • CreateDateValidator Method
  • CreateFormulaListValidator Method
  • CreateNumberValidator Method
  • CreateTextLengthValidator Method
  • CreateFormulaValidator Method
  • CreateListValidator Method

Set the HighlightInvalidData property to use the red ellipse as an invalid data image. You can also customize the invalid data image with the InvalidDataPresenter control.

The following code uses different types of validators to validate the data in B1, B2, and B3.

SpreadSLvalid

Validators

C#

gcSpreadSheet1.HighlightInvalidData = true;
var valid = GrapeCity.Windows.SpreadSheet.Data.DataValidator.CreateListValidator("5,10,15,20");
gcSpreadSheet1.Sheets[0].Cells[0, 1].DataValidator = valid;
gcSpreadSheet1.Sheets[0].Cells[0, 0].Text = "5, 10, 15, and 20 are valid numbers.";
var valid1 = GrapeCity.Windows.SpreadSheet.Data.DataValidator.CreateNumberValidator(GrapeCity.Windows.SpreadSheet.Data.ComparisonOperator.GreaterThan, "5", "20", true);
gcSpreadSheet1.Sheets[0].Cells[1, 1].DataValidator = valid1;
gcSpreadSheet1.Sheets[0].Cells[1,0].Text = "A number greater than 5 is valid.";
var valid2 = GrapeCity.Windows.SpreadSheet.Data.DataValidator.CreateTextLengthValidator(GrapeCity.Windows.SpreadSheet.Data.ComparisonOperator.GreaterThan, "4", "20");
gcSpreadSheet1.Sheets[0].Cells[2, 1].DataValidator = valid2;
gcSpreadSheet1.Sheets[0].Cells[2, 0].Text = "Type more than four characters.";

VB

GcSpreadSheet1.HighlightInvalidData = True
Dim valid = GrapeCity.Windows.SpreadSheet.Data.DataValidator.CreateListValidator("5,10,15,20")
GcSpreadSheet1.Sheets(0).Cells(0, 1).DataValidator = valid
GcSpreadSheet1.Sheets(0).Cells(0, 0).Text = "5, 10, 15, and 20 are valid numbers."
Dim valid1 = GrapeCity.Windows.SpreadSheet.Data.DataValidator.CreateNumberValidator(GrapeCity.Windows.SpreadSheet.Data.ComparisonOperator.GreaterThan, "5", "20", True)
GcSpreadSheet1.Sheets(0).Cells(1, 1).DataValidator = valid1
GcSpreadSheet1.Sheets(0).Cells(1, 0).Text = "A number greater than 5 is valid."
Dim valid2 = GrapeCity.Windows.SpreadSheet.Data.DataValidator.CreateTextLengthValidator(GrapeCity.Windows.SpreadSheet.Data.ComparisonOperator.GreaterThan, "4", "20")
GcSpreadSheet1.Sheets(0).Cells(2, 1).DataValidator = valid2
GcSpreadSheet1.Sheets(0).Cells(2, 0).Text = "Type more than four characters."

The following code customizes the invalid data image. The following image illustrates a valid value for the cell.

SpreadSLformlist

Valid Value

The following image illustrates an invalid value.

SpreadSLformlist2

Invalid Value

XAML

<Window.Resources>
<Style TargetType=”ss:InvalidDataPresenter”>
<Setter Property=”Template”>
<Setter.Value>
<ControlTemplate TargetType=”ss:InvalidDataPresenter”>
<Grid Background=”{TemplateBinding Background}”>
<Ellipse Stroke=”Orange”
StrokeThickness=”2″
Margin=”-6,-3,-6,-3″
/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>

C#

gcSpreadSheet1.ActiveSheet.Cells["C1"].Value = 1;
gcSpreadSheet1.ActiveSheet.Cells["C2"].Value = 2;
gcSpreadSheet1.ActiveSheet.Cells["C3"].Value = 3;
gcSpreadSheet1.HighlightInvalidData = true;
var valid = GrapeCity.Windows.SpreadSheet.Data.DataValidator.CreateFormulaListValidator("C1:C3");
gcSpreadSheet1.Sheets[0].Cells[1, 1].DataValidator = valid;
gcSpreadSheet1.Sheets[0].Cells[1, 0].Text = "Formulas";

VB

GcSpreadSheet1.ActiveSheet.Cells("C1").Value = 1
GcSpreadSheet1.ActiveSheet.Cells("C2").Value = 2
GcSpreadSheet1.ActiveSheet.Cells("C3").Value = 3
GcSpreadSheet1.HighlightInvalidData = True
Dim valid = GrapeCity.Windows.SpreadSheet.Data.DataValidator.CreateFormulaListValidator("C1:C3")
GcSpreadSheet1.Sheets(0).Cells(1, 1).DataValidator = valid
GcSpreadSheet1.Sheets(0).Cells(1, 0).Text = "Formulas"

This example validates a date with the CreateDateValidator method.

SpreadSLvaliddate

Date Validator

C#

//Type a date in cell (0,1)
gcSpreadSheet1.HighlightInvalidData = true;
var valid = GrapeCity.Windows.SpreadSheet.Data.DataValidator.CreateDateValidator(GrapeCity.Windows.SpreadSheet.Data.ComparisonOperator.Between, new System.DateTime(2012, 12, 31), DateTime.Now, false);
gcSpreadSheet1.Sheets[0].Cells[0, 1].DataValidator = valid;
gcSpreadSheet1.Sheets[0].Cells[0, 0].Text = "Enter a date between 12/31/2012 and now.";
gcSpreadSheet1.Sheets[0].SetColumnWidth(0, GrapeCity.Windows.SpreadSheet.Data.SheetArea.ColumnHeader, 300);
gcSpreadSheet1.Sheets[0].SetColumnWidth(1, GrapeCity.Windows.SpreadSheet.Data.SheetArea.ColumnHeader, 100);

VB

'Type a date in cell (0,1)
GcSpreadSheet1.HighlightInvalidData = True
Dim valid = GrapeCity.Windows.SpreadSheet.Data.DataValidator.CreateDateValidator(GrapeCity.Windows.SpreadSheet.Data.ComparisonOperator.Between, New System.DateTime(2012, 12, 31), DateTime.Now, False)
GcSpreadSheet1.Sheets(0).Cells(0, 1).DataValidator = valid
GcSpreadSheet1.Sheets(0).Cells(0, 0).Text = "Enter a date between 12/31/2012 and now."
GcSpreadSheet1.Sheets(0). SetColumnWidth(0, GrapeCity.Windows.SpreadSheet.Data.SheetArea.ColumnHeader, 300)
GcSpreadSheet1.Sheets(0). SetColumnWidth(1, GrapeCity.Windows.SpreadSheet.Data.SheetArea.ColumnHeader, 100)

This example uses a validator to check that the integer value is greater than 0.

SpreadSLformvalidate

Formula Validator

C#

gcSpreadSheet1.HighlightInvalidData = true;
var valid = GrapeCity.Windows.SpreadSheet.Data.DataValidator.CreateFormulaValidator("B2>0");
valid.InputMessage = "Enter a value greater than 0 in B2";
valid.ShowInputMessage = true;
valid.InputTitle= "Tip";
gcSpreadSheet1.Sheets[0].Cells[1, 1].DataValidator = valid;
gcSpreadSheet1.Sheets[0].Cells[1, 0].Text = "Enter a value greater than 0 in B2.";

VB

GcSpreadSheet1.HighlightInvalidData = True
Dim valid = GrapeCity.Windows.SpreadSheet.Data.DataValidator.CreateFormulaValidator("B2>0")
valid.InputMessage = "Enter a value greater than 0 in B2"
valid.ShowInputMessage = True
valid.InputTitle = "Tip"
GcSpreadSheet1.Sheets(0).Cells(1, 1).DataValidator = valid
GcSpreadSheet1.Sheets(0).Cells(1, 0).Text = "Enter a value greater than 0 in B2."

Adding Undo/Redo to a Ribbon with SpreadJS

$
0
0

Utilizing a Ribbon toolbar with SpreadJS is useful and gives control to end-users without needing to have the knowledge of the code behind it. Users might also need to undo or redo an action, which is possible with keyboard shortcuts, but not with buttons in the Ribbon. This tutorial will show how to add undo/redo functionality for a particular button on the ribbon toolbar.

This tutorial is a continuation of: Adding a Ribbon to SpreadJS

Download the source code for this tutorial: SpreadJS Ribbon Undo/Redo

Choose a Button and Create an Action

A simple button to add undo/redo functionality to is the “Add Row” button, which simply adds a row to the end of the current sheet.

The Add Row button on the ribbon bar created in the previous blog.

The Add Row button on the ribbon bar created in the previous blog.

To start off, create a new undo/redo action for this particular button by writing a function and defining its prototype:

function AddRowUndoRedoAction(sheet, rowCount) {
    this._oldRowCount = rowCount;
    this._rowCount = rowCount;
    this._sheet = sheet;
}

AddRowUndoRedoAction.prototype = new GcSpread.Sheets.UndoRedo.ActionBase();

Adding a row only needs three variables: the original number of rows, the number of rows after adding, and the active sheet. Other actions could require more variables to keep track of, but for the purposes of this example we will use the simplest action.
Next, define the prototype’s “execute” method, which will be called whenever the action is executed. In this case, adding a row simply increases the number of rows in the active sheet by one:

AddRowUndoRedoAction.prototype.execute = function (args) {
    this._sheet.setRowCount(this._rowCount);
}

For the purpose of undoing the action:

1. Define the “saveState” method of the action, which saves the state for undoing the action:

AddRowUndoRedoAction.prototype.saveState = function () {
    this._oldRowCount = this._sheet.getRowCount();
}

2. Define the “undo” method of the action, which is called when the user presses Ctrl+Z. In this case, the number of rows is decreased by one:

AddRowUndoRedoAction.prototype.undo = function (args) {
    this._sheet.setRowCount(this._oldRowCount - 1);
    return true;
}

Connect the Button to the New Action

Connect this action to the add row button by replacing the original code for the button with the new action:

This code:

$("#ribbon-msofficeButtonAddRow").click(function () {
    activeSheet = spread.getActiveSheet();
    activeSheet.setRowCount(activeSheet.getRowCount() + 1);
});

is replaced with this code:

$("#ribbon-msofficeButtonAddRow").click(function () {
    activeSheet = spread.getActiveSheet();
    activeSheet.doCommand(new AddRowUndoRedoAction(activeSheet, activeSheet.getRowCount() + 1));
    spread.focus();
});

When the user clicks the add row button, they can undo it by pressing Ctrl+Z. To add undo/redo functionality for other buttons in the ribbon, create new undo/redo actions for those buttons, similar to this tutorial, and pass them into the doCommand method for the active sheet in each button.click function like the code above.

Spread ASP.NET and Client Events

$
0
0

You can use client events in Spread ASP.NET. Client-side scripting allows the user to interact with the page on the client without the page having to be reloaded from the server. This can be useful if the event relies on run time only information.

There are several ways to map events on the client-side. You can use an attribute, map the event to a function, or map the event to the Spread object in the HTML page.

This example maps the event to the Spread object in the page:

JavaScript

<script type="text/javascript">               
        function show(event) {
            alert("r" + event.row + ",c" + event.col);            
        }
        </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>

    </div>
        <FarPoint:FpSpread onDataChanged="show(event)" ID="FpSpread1" runat="server" BorderColor="#A0A0A0" BorderStyle="Solid" BorderWidth="1px" Height="200" Width="400">
            <commandbar backcolor="#F6F6F6" buttonfacecolor="Control" buttonhighlightcolor="ControlLightLight" buttonshadowcolor="ControlDark">
            </commandbar>
            <sheets>
                <FarPoint:SheetView SheetName="Sheet1">
                </FarPoint:SheetView>
            </sheets>
        </FarPoint:FpSpread>
    </form>
</body>
</html>

This example maps the event to a function.

JavaScript

<script type="text/javascript">
window.onload = function ()
        {           
            var spread1 = document.getElementById("<%=FpSpread1.ClientID %>");
            if (spread1.addEventListener) {
                // IE 9 and above or Chrome or FF
                  spread1.addEventListener("ActiveCellChanged", cellChanged, false);
                } else if (spread1.attachEvent) {
                    spread1.attachEvent("onActiveCellChanged",  cellChanged);
                } else {
                    spread1.onActiveCellChanged =  cellChanged;
} 
         }
         function cellChanged(event) {
            alert("r" + event.row + ",c" + event.col);
        }        
</script>

This example uses an attribute.

C#

protected void Page_Load(object sender, EventArgs e)
        {
            if (this.IsPostBack) return;
            FpSpread1.Attributes.Add("onDataChanged", "Test(event)");            
        }
    }

VB

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
FpSpread1.Attributes.Add("onDataChanged", "Test(event)")
End Sub

JavaScript

<script type="text/javascript">
function Test(event) {
            alert("r" + event.row + ",c" + event.col);
        }</script>

The following sample code for the ASPX page uses the built-in GetValue method to total the values in the cells (all except the last cell) of the first column and uses the SetValue method to put the result in the last cell of that column. Type a value in a cell and change cells to see the result.

SpASPClientSample

Total Result

C#

protected void Page_Load(object sender, EventArgs e)
        {
            if (this.IsPostBack) return;
            FpSpread1.Sheets[0].Cells[0, 0].Value = 4;
            FpSpread1.Sheets[0].Cells[1, 0].Value = 3;
            FpSpread1.Attributes.Add("onDataChanged", "doCalc(event)");
        }

VB

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If (IsPostBack) Then
            Return
        End If
        FpSpread1.Sheets(0).Cells(0, 0).Value = 4
        FpSpread1.Sheets(0).Cells(1, 0).Value = 3
        FpSpread1.Attributes.Add("onDataChanged", "doCalc(event)")
    End Sub

JavaScript

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SpreadASP.aspx.cs" Inherits="SpWeb8CSharp.SpreadASP" %>
<%@ Register assembly="FarPoint.Web.Spread, Version=8.40.20151.0, Culture=neutral, PublicKeyToken=327c3516b1b18457" namespace="FarPoint.Web.Spread" tagprefix="FarPoint" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Spread ASP.NET</title>

    <script type="text/javascript">
        function doCalc() {
            var rc = FpSpread1.GetRowCount();
            var total = 0;

            for (var i = 0; i < rc - 1; i++) {
                var value = parseFloat(FpSpread1.GetValue( i, 0 ));
                total += value;
            }
            if (!isNaN(total))
                FpSpread1.SetValue(rc-1, 0, total, true);
        }
        </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
    </div>
        <FarPoint:FpSpread ID="FpSpread1" runat="server" BorderColor="#A0A0A0" BorderStyle="Solid" BorderWidth="1px" Height="200" Width="400">
            <commandbar backcolor="#F6F6F6" buttonfacecolor="Control" buttonhighlightcolor="ControlLightLight" buttonshadowcolor="ControlDark">
            </commandbar>
            <sheets>
                <FarPoint:SheetView SheetName="Sheet1">
                </FarPoint:SheetView>
            </sheets>
        </FarPoint:FpSpread>
    </form>
</body>
</html>

Adding a Ribbon to SpreadASP

$
0
0

Toolbars are a useful addition that allow end-users to manipulate components on a webpage. This tutorial provides step-by-step instructions for adding an open source Ribbon toolbar to an instance of SpreadASP. The toolbar we are using is an open source JQuery ribbon that can be found here: https://www.openhub.net/p/jquery-ui-ribbon. Other ribbons can be used, but this is a simple example to show how we can go about connecting a ribbon to SpreadASP.

For a tutorial on adding a ribbon to another Spread project, such as SpreadJS, see here: http://sphelp.grapecity.com/2015/09/16/adding-a-ribbon-to-spreadjs/.

Download the source code for this tutorial: SpreadASP Ribbon

Set Up the Project

Start by creating an ASP.NET web application that you will add Spread to. Find instructions here: http://sphelp.grapecity.com/WebHelp/SpreadNet8/ASP2/webframe.html#spweb-startvs2013.html.

Set up your project by placing the source code for the Ribbon control linked above in the directory where you created the project. Include these files and folders in your project.
Your spreadsheet should look like the one in the screen shot below.

An ASP page with the Spread Component on it.

An ASP page with the Spread Component on it.

Add the Ribbon to Your Page

Add the links to the scripts found in the open source Ribbon you downloaded.

<link type="text/css" href="../../themes/base/ui.all.css" rel="stylesheet" />
<link type="text/css" href="../../themes/base/ui.tabs.css" rel="stylesheet" />
<link type="text/css" href="../../style/ui.button.css" rel="stylesheet" />
<link type="text/css" href="../../style/ui.ribbon.css" rel="stylesheet" />
<link type="text/css" href="../../style/ui.orbButton.css" rel="stylesheet" />
<link type="text/css" href="../../style/ui.ribbon.style.msoffice.css" rel="stylesheet" />
<link type="text/css" href="../../style/msoffice-icons.css" rel="stylesheet" />

<script type="text/javascript" src="../../jquery-1.3.2.js"></script>

<script type="text/javascript" src="../../ui/ui.core.js"></script>
<script type="text/javascript" src="../../ui/ui.tabs.js"></script>
<script type="text/javascript" src="../../ui/ui.ribbon.js"></script>
<script type="text/javascript" src="../../ui/ui.orbButton.js"></script>
<script type="text/javascript" src="../../ui/ui.button.js"></script>
<script type="text/javascript">
    jQuery(function ($) {
        $('#log').dblclick(function () { $('#log').empty(); });
        $('.ui-button').button({ useSlidingDoors: true });
        $('#ribbon-msoffice').wrap('<div class="style-msoffice"></div>');

        $('#ribbon, #ribbon-msoffice').ribbon({
            collapsible: true
        })
    });
</script>

Next, set the page to display the ribbon by adding this html code to the body above the SpreadASP component:

<div id="ribbon-msoffice" style="width:700px; border: 1px solid gray">
    <div id="ribbon-msofficeContextData" style="display:none;"><label>Data</label></div>
    <ul>
        <li><a href="#ribbon-msofficeTabHome"><span><label>Home</label></span></a></li>
        <li><a href="#ribbon-msofficeTabInsert"><span><label>Insert</label></span></a></li>
        <li><a href="#ribbon-msofficeTabView"><span><label>View</label></span></a></li>
    </ul>
</div>

You can then add code for each particular button by adding div elements for each tab in the ribbon. When a tab is added, unordered lists within those div elements can be added to represent the sections with buttons:

<div id="ribbon-msofficeTabInsert">
    <ul>
        <li id="groupSheet_ribbon-msofficeTabInsert">
            <div>
                <button class="ui-ribbon-element ui-ribbon-control ui-button ui-ribbon-large-button" id="AddSheetButton" runat="server" onserverclick="AddSheetButton_Click"><span class="ui-icon msoffice-icon-menu-new-32x32"></span><span class="ui-button-label">New Sheet</span></button>
                <button class="ui-ribbon-element ui-ribbon-control ui-button ui-ribbon-large-button" id="DeleteSheetButton" runat="server" onserverclick="DeleteSheetButton_Click"><span class="ui-icon msoffice-icon-delete-24x24""></span><span class="ui-button-label">Delete Sheet</span></button>
            </div>
            <h3><span>Sheet</span></h3>
        </li>
    </ul>
</div>

The ribbon should now be displayed on the page right above the Spread component, and it should look similar to a ribbon you would see in a Microsoft Office program:

The finished ASP page with Spread and a Ribbon on it.

The finished ASP page with Spread and a Ribbon on it.

Make the Buttons Work with SpreadASP

To add the functionality to these buttons, it must be decided whether the functions can be run in a client-side script or in server-side code. For information about what client-side functions are supported in SpreadASP, see here: http://sphelp.grapecity.com/WebHelp/SpreadNet8/ASP2/webframe.html#clientscript-members.html.

If a button can be controlled in a client-side script, you can define the “onclick” attribute of a button like so:

<button class="ui-ribbon-element ui-ribbon-control ui-button ui-ribbon-large-button" id="PasteButton" onclick="PasteButton_Click();"><span class="ui-icon msoffice-icon-paste-32x32"></span><span class="ui-button-label">Paste</span></button>

The “PasteButton_Click()” function referenced in this button can be defined in the script with Spread:

window.onload = function () {
    spread = document.getElementById("<%= FpSpread1.ClientID %>");
}

function PasteButton_Click() {
    spread.PasteLikeExcel();
}

Whenever that paste button is clicked, that function in the script will fire on the client-side.
To link a button to server-side code, define the “runat” and “onserverclick” attributes of the button like so:

<button class="ui-ribbon-element ui-ribbon-control ui-button ui-ribbon-large-button" id="AddSheetButton" runat="server" onserverclick="AddSheetButton_Click"><span class="ui-icon msoffice-icon-menu-new-32x32"></span><span class="ui-button-label">New Sheet</span></button>

In the code-behind file for the sheet, define the “AddSheetButton_Click” function:

protected void AddSheetButton_Click(object sender, EventArgs e)
{
    FpSpread1.Sheets.Add(new FarPoint.Web.Spread.SheetView());
}

Once the code for each button has been written, the ribbon should be connected to the Spread component on an ASP page, and the user can interact with both.

SpreadJS and Visual Studio

$
0
0

You can use SpreadJS in a Visual Studio project. This provides access to automatic complete and code checking in Visual Studio.

Use the following steps to create a project that uses SpreadJS.

    1. Create an ASP.NET project (File, New Project or New Project in Visual Studio).  Select ASP.NET Web Application. Specify the Name, Location, and Solution name.

      SpreadJSWebProject

      New Project

    2. Select a template such as Empty and select OK.

      SpreadJSEmpty

      Empty Template

    3. Select Project, Add New Item.

      SpreadJSAddNewItem

      New Item

    4. Select HTML page. Specify a name. Select Add. You can also right-click on the HTML file in the Solution Explorer and change the name (Rename menu option).

      SpreadJSHtml

      HTML Page

    5. Save the file (File, Save SpreadJSHtml.html).
    6. Add the file to the project (Project, Add Existing Item).

      SpreadJSAddExisting

      Existing Item

    7. Select the file in the project folder (SpreadJSHtml.html) and select Add. You can also use the Add Existing Item option to add the gcspread.sheets.all.8.40.20151.5.min.js and gcspread.sheets.all.8.40.20151.5.css files to the project so that you can use relative paths.
      SpreadJSlocation

      Add File

    8. Use code similar to the following to add the widget to the page.
      <!DOCTYPE html>
      <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
      <head>
          <meta charset="utf-8" />
          <title>SpreadJS</title>
          <script src="http://code.jquery.com/jquery-2.0.2.js" type="text/javascript"></script>
          <script type="text/javascript" src="gcspread.sheets.all.8.40.20151.5.min.js"></script>
          <script type="text/javascript" src="gcspread.sheets.all.8.40.20151.5.css"></script>
      
          <script type="text/javascript">
          $(function () {
              var spread = new GcSpread.Sheets.Spread($("#ss")[0]);
              var sheet = spread.getActiveSheet();
              sheet.setValue(0, 0, "This is a test");
              sheet.getCell(0, 0).backColor("yellow");
              sheet.getColumn(0).width(100);
               })
          </script>
      </head>
      <body>
          <div id="ss" style="width:600px;height:450px"></div>
      </body>
      </html>

      SpreadJSCode

      Sample Code

    9. You can use the View in Browser option to test the page or use the Run option.

      SpreadJSViewBrowser

      View in Browser

    10. The completed example is illustrated in the following image.

      SpreadJSComplete

      Completed Sample

SpreadASP Excel Copy/Paste

$
0
0

Spread for ASP.NET is a useful component for providing Spreadsheet functionality on a web server. While Spread has many great features, it might be beneficial for a user to paste cell ranges into the Spread component, without having to worry about reformatting the cells or writing any code. In this tutorial, we will create an ASP Web Application that allows the users to paste cell ranges from Excel into Spread while keeping the formatting.

Download this project: ExcelSpreadCopyPaste

To start off, we must create an ASP Web Application and add a Spread component to a web page. For more information about adding a Spread component, see the tutorial here: http://sphelp.grapecity.com/WebHelp/SpreadNet8/ASP2/webframe.html#spweb-startvs2013.html

Set Up the Page

Once the default page has been set and a Spread component has been added to it, specify a “ContentEditable” div above the Spread component like the code below:

<h1>Excel-Spread Copy-Paste</h1>
<p>You can copy cells from an Excel file and put them into the Spreadsheet below!</p>
<div class="toggle" id="contentEditor" contenteditable style="background: #ffffff">
    <p>Paste cells here!</p>
</div>
<FarPoint:FpSpread ID="FpSpread1" runat="server" BorderColor="#A0A0A0" BorderStyle="Solid" BorderWidth="1px" Height="400px" Width="1000px">
    <commandbar backcolor="#F6F6F6" buttonfacecolor="Control" buttonhighlightcolor="ControlLightLight" buttonshadowcolor="ControlDark">
    </commandbar>
    <sheets>
        <FarPoint:SheetView SheetName="Sheet1">
        </FarPoint:SheetView>
    </sheets>
</FarPoint:FpSpread>

The web page should now look like the following screen shot:

The default page with content editable div and Spread on it.

The default page with content editable div and Spread on it.

Add Spread Code

Add a script to the web page for the client-side code, and define the “window.onload” function:

<script lang=”javascript” type=”text/javascript”>

window.onload = function () {

}

</script>

The rest of the code for this tutorial will be inside of this function. Define the Spread component in the script by getting the element on the page:

var spread = document.getElementById("<%=FpSpread1.ClientID %>");

The “ContentEditable” div is where the Excel cell ranges are going to be pasted, so define the function for the “onPaste” event:

$('[contenteditable]').on('paste', function (e) {}):

The rest of the code for this tutorial will be defined within the function specified above. To get the clipboard data to paste into Spread, define a “text” variable:

var text = (e.originalEvent || e).clipboardData.getData('text/html');

A new div element will be created on the page to help with merging the data into spread:

var newDiv = document.createElement("div");
newDiv.innerHTML = text;
newDiv.id = "spreadTable";
document.getElementById("contentEditor").appendChild(newDiv);

Define a function called “addToSpread” that will handle adding the content from that new div to the Spread component with the correct formatting. For simplicity, define a variable called “table” in this function to refer to the table containing the data and formatting from Excel:

var table = document.getElementById('spreadTable').getElementsByTagName('table')[0];

Go through the table to get the values and properties to set in Spread using For loops:

for (var i = 0, row; row = table.rows; i++) {
    for (var j = 0, cell; cell = row.cells[j]; j++) {}
}

Within the inner For loop, set the value of the cells in Spread to the table values:

spread.SetValue(I, j, cell.textContent);

Set the column width to match the table:

if (cell.width > 0) {
    spread.setColWidth(j, cell.width);
}

Get the rules of the css in order to get the background and foreground colors of cells in the table and apply them to the Spread component:

var rules = document.styleSheets.item(4);
rules = rules.cssRules || rules.rules;
for (var k = 0; k < rules.length; k++) {
    if (rules.item(k).selectorText == "." + cell.className) {
        var currentCell = spread.Cells(i, j);
        currentCell.SetBackColor(rules.item(k).style.backgroundColor);
        currentCell.SetForeColor(rules.item(k).style.color);
        break;
    }
}

Set the height of the rows for both the rows and row headers:

if (cell.height > 0) {
    var spreadRowHeader = document.getElementById('MainContent_FpSpread1_rh');
    if (spreadRowHeader.rows.style.height != null) {
        spreadRowHeader.rows.style.height = cell.height + 'px';
    }
    var spreadTable = document.getElementById('MainContent_FpSpread1_viewport');
    if (spreadTable.rows.style.height != null) {
        spreadTable.rows.style.height = cell.height + 'px';
    }
}

Outside of the For loops, set the range selected in the Spread component to the cells just pasted in:

spread.SetSelectedRange(0, 0, i, j);

Then call the function just defined and hide the div element used to paste cells:

addToSpread();
var removeDiv = document.getElementById('contentEditor');
if (removeDiv) {
    removeDiv.hidden = true;
}

A user should be able to copy cells from an Excel file and paste them into the “ContentEditable” div on the page. Once they do so, the cells will be copied into the Spread component with some formatting applied to them. This is just one example of how Spread can provide an easy way for users to interact with Spread with no coding knowledge required.

The Excel file that was copied from.

The Excel file that was copied from.

The Spread page with the copied Excel cell range pasted into it.

The Spread page with the copied Excel cell range pasted into it.

 


Adding a Ribbon to Spread for Winforms

$
0
0

The Windows Forms Spread control brings powerful grid tools and features to desktop applications that users can run on their computer. In the Spread Designer, it is easy to create and format spreadsheets, but it might also be useful for the user to perform these actions at runtime. This tutorial provides step-by-step instructions for adding an open-source Ribbon toolbar to a Windows Forms application with Spread. The toolbar being used in this tutorial is an open-source ribbon for Windows Forms applications called the “Office Ribbon Project” and can be found here: http://officeribbon.codeplex.com/releases/view/113126.
Other ribbons can be used, but this is a simple example to show how to connect a ribbon to a Spread control in a Windows Forms application.
For a tutorial on adding a ribbon to another Spread project, such as SpreadASP, see here: http://sphelp.grapecity.com/2015/09/24/adding-a-ribbon-to-spreadasp/.
Download the source code for this tutorial: SpreadWin Ribbon Code

Set Up the Project

Start by creating a Windows Forms application and add a Spread component to it. Find instructions here: http://sphelp.grapecity.com/WebHelp/SpreadNet8/WF/webframe.html#spwin-VS2013add.html.
Set up the project by adding the ribbon control to your application. For steps on how to add the control to the toolbox in Visual Studio, follow the instructions in Part 2 of this tutorial: http://www.codeproject.com/Articles/364272/Easily-Add-a-Ribbon-Into-a-WinForms-Application-Cs.
Once the ribbon has been added to the application, it should show as an empty ribbon in the design window like the screen shot below:

The Windows Forms application with Spread and an empty ribbon on it.

The Windows Forms application with Spread and an empty ribbon on it.

You can follow the steps in the code project tutorial linked above for adding tabs, panels, and buttons in the ribbon. Once the buttons have been added, the application will look something like the screen shot below:

The finished design of the Windows Forms application.

The finished design of the Windows Forms application.

In this tutorial, the “Orb Style” property of the Ribbon control was set to “Office_2013”, but it can be changed depending on the preference.

Connecting the Buttons to the Spread Control

The event handlers for clicking on each button can be created by Visual Studio via the Code Project tutorial in Step 11 of Part 2. Simply click on the “events” property of each button and add a function for the “click” event. There should be a “Click” function for each button that you have added a handler for. The code for connecting the Ribbon Control to the Spread control will go into these functions.
As a simple example, this is the code for the “Insert Row” button:

private void insertRowButton_Click(object sender, EventArgs e)
{
    fpSpread1.ActiveSheet.AddRows(fpSpread1.ActiveSheet.ActiveRowIndex, 1);
}

When the user clicks on this button, a row will be inserted at the position of the active row in the spreadsheet.

Change Styling of Ribbon

The color scheme of this particular ribbon can be customized, and instructions on how to do so can be found in the code project tutorial: http://www.codeproject.com/Articles/364272/Easily-Add-a-Ribbon-Into-a-WinForms-Application-Cs.
In this tutorial, a pre-made skin was used. To change the skin, create a new function in the Main form’s source code called “ChangeTheme”:

private void ChangeTheme()
{
    Theme.ColorTable = new RibbonProfesionalRendererColorTablePurple();
    ribbon1.Refresh();
    this.Refresh();
}

Then, call that function from the form’s main function:

public SpreadRibbonForm()
{
    InitializeComponent();
    ChangeTheme();
}

The changes aren’t reflected at design time, but can be seen at runtime:

Completed design of Windows Forms application with styling.

Completed design of Windows Forms application with styling.

Once the code for each button has been written, the ribbon will be connected to the Spread control and the user can interact with both.

Spread Windows Forms and Printing

$
0
0

Spread Windows Forms supports printing to a PDF file or previewing the output before printing. This allows you to check the data and layout before printing, which can save paper.

This example saves the sheets to a PDF file.

C#

private void SpreadWin1_Load(object sender, EventArgs e)
        {
            fpSpread1.Sheets.Count = 3;
            fpSpread1.Sheets[0].RowCount = 10;
            fpSpread1.Sheets[0].ColumnCount = 10;
            fpSpread1.Sheets[1].RowCount = 10;
            fpSpread1.Sheets[1].ColumnCount = 10;
            fpSpread1.Sheets[2].RowCount = 10;
            fpSpread1.Sheets[2].ColumnCount = 10;
            fpSpread1.Sheets[0].SetClip(0, 0, 3, 3, "Sunday\tMonday\tTuesday\r\nWednesday\tThursday\tFriday\r\nSaturday\tSunday\tMonday");
            fpSpread1.Sheets[1].SetClip(0, 0, 3, 3, "January\tFebruary\tMarch\r\nApril\tMay\tJune\r\nJuly\tAugust\tSeptember");
            fpSpread1.Sheets[2].SetClip(0, 0, 3, 3, "2012\t2013\t2014\r\n2015\t2016\t2017\r\n2018\t2019\t2020");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Define the printer settings
            FarPoint.Win.Spread.PrintInfo printset = new FarPoint.Win.Spread.PrintInfo();
            printset.Header = "Print Job for GrapeCity Inc.";            
            printset.PdfWriteTo = FarPoint.Win.Spread.PdfWriteTo.File;
            printset.PdfWriteMode = FarPoint.Win.Spread.PdfWriteMode.Append;            
            printset.PrintToPdf = true;
            printset.PdfFileName = "C:\\results.pdf";
            // Assign the printer settings to the sheet and print to PDF
            fpSpread1.Sheets[0].PrintInfo = printset;
            fpSpread1.Sheets[1].PrintInfo = printset;
            fpSpread1.Sheets[2].PrintInfo = printset;
            fpSpread1.PrintSheet(-1);
        }

VB

Private Sub SpreadWin1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        FpSpread1.Sheets.Count = 3
        FpSpread1.Sheets(0).RowCount = 10
        FpSpread1.Sheets(0).ColumnCount = 10
        FpSpread1.Sheets(1).RowCount = 10
        FpSpread1.Sheets(1).ColumnCount = 10
        FpSpread1.Sheets(2).RowCount = 10
        FpSpread1.Sheets(2).ColumnCount = 10
        FpSpread1.Sheets(0).SetClip(0, 0, 3, 3, "Sunday" + vbTab + "Monday" + vbTab + "Tuesday" + vbCrLf + "Wednesday" + vbTab + "Thursday" + vbTab + "Friday" + vbCrLf + "Saturday" + vbTab + "Sunday" + vbTab + "Monday")
        FpSpread1.Sheets(1).SetClip(0, 0, 3, 3, "January" + vbTab + "February" + vbTab + "March" + vbCrLf + "April" + vbTab + "May" + vbTab + "June" + vbCrLf + "July" + vbTab + "August" + vbTab + "September")
        FpSpread1.Sheets(2).SetClip(0, 0, 3, 3, "2012" + vbTab + "2013" + vbTab + "2014" + vbCrLf + "2015" + vbTab + "2016" + vbTab + "2017" + vbCrLf + "2018" + vbTab + "2019" + vbTab + "2020")
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ' Define the printer settings
        Dim printset As New FarPoint.Win.Spread.PrintInfo()
        printset.Header = "Print Job for GrapeCity Inc."
        printset.PdfWriteTo = FarPoint.Win.Spread.PdfWriteTo.File
        printset.PdfWriteMode = FarPoint.Win.Spread.PdfWriteMode.Append
        printset.PrintToPdf = True
        printset.PdfFileName = "C:\results.pdf"
        ' Assign the printer settings to the sheet And print to PDF
        FpSpread1.Sheets(0).PrintInfo = printset
        FpSpread1.Sheets(1).PrintInfo = printset
        FpSpread1.Sheets(2).PrintInfo = printset
        FpSpread1.PrintSheet(-1)
    End Sub

This example uses the Preview property in the PrintInfo class to preview a sheet before printing.

SpreadWinPreview

Preview Notes and Shapes

C#

private void SpreadWin1_Load(object sender, EventArgs e)
        {
            fpSpread1.TextTipPolicy = FarPoint.Win.Spread.TextTipPolicy.Fixed;
            fpSpread1.Sheets[0].Cells[1, 1].NoteStyle = FarPoint.Win.Spread.NoteStyle.StickyNote;
            fpSpread1.Sheets[0].Cells[1, 1].Note = "Printing";
            fpSpread1.Sheets[0].Cells[5, 1].Text = "Print Shape and Note";
            fpSpread1.AllowCellOverflow = true;

            FarPoint.Win.Spread.DrawingSpace.ArrowShape arrow = new FarPoint.Win.Spread.DrawingSpace.ArrowShape();
            arrow.BackColor = Color.Red;
            arrow.ForeColor = Color.DarkRed;
            arrow.SetBounds(0, 20, 100, 50);
            fpSpread1.Sheets[0].AddShape(arrow);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            FarPoint.Win.Spread.PrintInfo printset = new FarPoint.Win.Spread.PrintInfo();            
            printset.PrintNotes = FarPoint.Win.Spread.PrintNotes.AsDisplayed;
            printset.PrintShapes = true;
            printset.Preview = true;
            fpSpread1.Sheets[0].PrintInfo = printset;
            fpSpread1.PrintSheet(0);
        }

VB

Private Sub SpreadWin1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        FpSpread1.TextTipPolicy = FarPoint.Win.Spread.TextTipPolicy.Fixed
        FpSpread1.Sheets(0).Cells(1, 1).NoteStyle = FarPoint.Win.Spread.NoteStyle.StickyNote
        FpSpread1.Sheets(0).Cells(1, 1).Note = "Printing"
        FpSpread1.Sheets(0).Cells(5, 1).Text = "Print Shape and Note"
        FpSpread1.AllowCellOverflow = True

        Dim arrow = New FarPoint.Win.Spread.DrawingSpace.ArrowShape()
        arrow.BackColor = Color.Red
        arrow.ForeColor = Color.DarkRed
        arrow.SetBounds(0, 20, 100, 50)
        FpSpread1.Sheets(0).AddShape(arrow)
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim printset As New FarPoint.Win.Spread.PrintInfo()
        printset.PrintNotes = FarPoint.Win.Spread.PrintNotes.AsDisplayed
        printset.PrintShapes = True
        printset.Preview = True
        FpSpread1.Sheets(0).PrintInfo = printset
        FpSpread1.PrintSheet(0)
    End Sub

This example creates headers and footers for the printed sheet.

SpreadWinpp

Preview with Header

C#

private void SpreadWin1_Load(object sender, EventArgs e)
{
//Add sample data
string conStr = "Provider=Microsoft.JET.OLEDB.4.0;data source= C:\\Program Files (x86)\\GrapeCity\\Spread Studio 8\\Common\\nwind.mdb";
string sqlStr = "Select CompanyName, ContactName, ContactTitle, Country from Customers";
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(conStr);
DataSet ds = new DataSet();
System.Data.OleDb.OleDbDataAdapter da = new System.Data.OleDb.OleDbDataAdapter(sqlStr, conn);
da.Fill(ds);
fpSpread1.ActiveSheet.DataAutoSizeColumns = true;
fpSpread1.ActiveSheet.DataMember = "Patients";
fpSpread1.ActiveSheet.DataSource = ds;
}

private void button1_Click(object sender, EventArgs e)
{
// Create PrintInfo object and set properties.
FarPoint.Win.Spread.PrintInfo printset = new FarPoint.Win.Spread.PrintInfo();
printset.Colors = new Color[] { Color.Green, Color.Yellow, Color.Gold, Color.Indigo, Color.Brown };
printset.Header = "/fn\"Book Antiqua\" /fz\"14\" Print job for GrapeCity./n ";
printset.Footer = "/r/cl\"4\"This is page /p of /pc";
printset.Preview = true;
// Set the PrintInfo property for the first sheet.
fpSpread1.Sheets[0].PrintInfo = printset;
// Print the sheet.
fpSpread1.PrintSheet(0);
}

VB

Private Sub SpreadWin1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim conStr As String = "Provider=Microsoft.JET.OLEDB.4.0;data source= C:\Program Files (x86)\GrapeCity\Spread Studio 8\Common\nwind.mdb"
Dim sqlStr As String = "Select CompanyName, ContactName, ContactTitle, Country from Customers"
Dim conn As New System.Data.OleDb.OleDbConnection(conStr)
Dim ds As DataSet = New DataSet()
Dim da As New System.Data.OleDb.OleDbDataAdapter(sqlStr, conn)
da.Fill(ds)
FpSpread1.ActiveSheet.DataAutoSizeColumns = True
FpSpread1.ActiveSheet.DataMember = "Patients"
FpSpread1.ActiveSheet.DataSource = ds
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Create PrintInfo object and set properties.
Dim printset As New FarPoint.Win.Spread.PrintInfo()
printset.Colors = New Color() {Color.Green, Color.Yellow, Color.Gold, Color.Indigo, Color.Brown}
printset.Header = "/fn""Book Antiqua"" /fz""14"" Print job for GrapeCity./n "
printset.Footer = "/g""1""/r/cl""4""This is page /p of /pc"
' Set the PrintInfo property for the first sheet.
printset.Preview = True
FpSpread1.Sheets(0).PrintInfo = printset
' Print the sheet.
FpSpread1.PrintSheet(0)
End Sub

You can also use a print dialog control to preview the printing. You can use a print preview control in the PrintPreviewShowing event or with the SetPrintPreview method.

This example uses a print preview control in the Spread PrintPreviewShowing event to preview the data.

C#

private void button1_Click(object sender, EventArgs e)
        {
            FarPoint.Win.Spread.PrintInfo printset = new FarPoint.Win.Spread.PrintInfo();
            printset.Preview = true;
            printset.ShowPrintDialog = true;
            fpSpread1.Sheets[0].PrintInfo = printset;
            fpSpread1.PrintSheet(0);            
        }

        private void fpSpread1_PrintPreviewShowing(object sender, FarPoint.Win.Spread.PrintPreviewShowingEventArgs e)
        {
            e.Cancel = true;
            PrintPreviewDialog printPreviewDialog1  = new PrintPreviewDialog();          
            printPreviewDialog1.Document = e.PreviewDialog.Document;            
            printPreviewDialog1.ShowDialog();
        }

VB

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim printset As New FarPoint.Win.Spread.PrintInfo()
        printset.Preview = True
        printset.ShowPrintDialog = True
        FpSpread1.Sheets(0).PrintInfo = printset
        FpSpread1.PrintSheet(0)
    End Sub

    Private Sub FpSpread1_PrintPreviewShowing(sender As Object, e As FarPoint.Win.Spread.PrintPreviewShowingEventArgs) Handles FpSpread1.PrintPreviewShowing
        e.Cancel = True
        Dim printPreviewDialog1 As New PrintPreviewDialog()
        printPreviewDialog1.Document = e.PreviewDialog.Document
        printPreviewDialog1.ShowDialog()
    End Sub

This example uses the SetPrintPreview method and sets properties for the print preview control.

spreadwinsetpreview

Custom Preview Settings

C#

private void Form1_Load(object sender, EventArgs e)
        {
            fpSpread1.Sheets.Count = 3;
            fpSpread1.Sheets[0].RowCount = 10;
            fpSpread1.Sheets[0].ColumnCount = 10;
            fpSpread1.Sheets[1].RowCount = 10;
            fpSpread1.Sheets[1].ColumnCount = 10;
            fpSpread1.Sheets[2].RowCount = 10;
            fpSpread1.Sheets[2].ColumnCount = 10;
            fpSpread1.Sheets[0].SetClip(0, 0, 3, 3, "Sunday\tMonday\tTuesday\r\nWednesday\tThursday\tFriday\r\nSaturday\tSunday\tMonday");
            fpSpread1.Sheets[1].SetClip(0, 0, 3, 3, "January\tFebruary\tMarch\r\nApril\tMay\tJune\r\nJuly\tAugust\tSeptember");
            fpSpread1.Sheets[2].SetClip(0, 0, 3, 3, "2012\t2013\t2014\r\n2015\t2016\t2017\r\n2018\t2019\t2020");
         }

        private void button1_Click(object sender, EventArgs e)
        {            
            PrintPreviewDialog pi = new PrintPreviewDialog();
            pi.BackColor = Color.Cyan;
            pi.ForeColor = Color.Red;
            pi.Text = "My preview dialog";  
            fpSpread1.SetPrintPreview(pi);
            fpSpread1.ActiveSheet.PrintInfo.Preview = true;
            fpSpread1.ActiveSheet.PrintInfo.ZoomFactor = 0.75f;
            fpSpread1.PrintSheet(fpSpread1.ActiveSheet);
        }

VB

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        FpSpread1.Sheets.Count = 3
        FpSpread1.Sheets(0).RowCount = 10
        FpSpread1.Sheets(0).ColumnCount = 10
        FpSpread1.Sheets(1).RowCount = 10
        FpSpread1.Sheets(1).ColumnCount = 10
        FpSpread1.Sheets(2).RowCount = 10
        FpSpread1.Sheets(2).ColumnCount = 10
        FpSpread1.Sheets(0).SetClip(0, 0, 3, 3, "Sunday" + vbTab + "Monday" + vbTab + "Tuesday" + vbCrLf + "Wednesday" + vbTab + "Thursday" + vbTab + "Friday" + vbCrLf + "Saturday" + vbTab + "Sunday" + vbTab + "Monday")
        FpSpread1.Sheets(1).SetClip(0, 0, 3, 3, "January" + vbTab + "February" + vbTab + "March" + vbCrLf + "April" + vbTab + "May" + vbTab + "June" + vbCrLf + "July" + vbTab + "August" + vbTab + "September")
        FpSpread1.Sheets(2).SetClip(0, 0, 3, 3, "2012" + vbTab + "2013" + vbTab + "2014" + vbCrLf + "2015" + vbTab + "2016" + vbTab + "2017" + vbCrLf + "2018" + vbTab + "2019" + vbTab + "2020")
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim pi As New PrintPreviewDialog()
        pi.BackColor = Color.Cyan
        pi.ForeColor = Color.Red
        pi.Text = "My preview dialog"
        FpSpread1.SetPrintPreview(pi)
        FpSpread1.ActiveSheet.PrintInfo.Preview = True
        FpSpread1.ActiveSheet.PrintInfo.ZoomFactor = 0.75F
        FpSpread1.PrintSheet(FpSpread1.ActiveSheet)
    End Sub

SpreadJS Validation

$
0
0

You can use data validation to control the type of data and values that users are allowed to enter in a cell. This can be useful if you only want to allow correct values in a cell based on your data. SpreadJS supports data validation.

Create validators to validate the user data. You can display a list of valid values for the user and display an invalid data image if the user types invalid data. Use the highlightInvalidData method to specify a red ellipse as an invalid data image.

You can use any of several types of validator methods to create the validation criteria.

  • createDateValidator
  • createFormulaValidator
  • createFormulaListValidator
  • createListValidator
  • createNumberValidator
  • createTextLengthValidator

The ValidationError event occurs when the applied cell value is invalid. You can also use the isValid method to check that a cell value is valid based on the validation.

This example creates a list of valid values for the Category column.

SpreadJSvalid

List Data

JavaScript

var datasource = [
                   { Name: "Apple", Category: "Fruit" },
                   { Name: "Orange", Category: "Fruit" },
                   { Name: "Broccoli", Category: "Vegetable" },
                   { Name: "Kiwi", Category: "Fruit" },
                   { Name: "Strawberry", Category: "Fruit" },
                   { Name: "Yogurt", Category: "Dairy" },
                   { Name: "Plum", Category: "Fruit" },
                   { Name: "Pear", Category: "Cereal" },
	           { Name: "Carrot", Category: "Vegetable" },
	           { Name: "Cheese", Category: "Dairy" },
               ];

activeSheet.setDataSource(datasource);
activeSheet.getColumn(0).width(75);
activeSheet.getColumn(1).width(75);

spread.highlightInvalidData(true);
var dv = GcSpread.Sheets.DefaultDataValidator.createListValidator("Fruit,Vegetable,Dairy");
dv.showInputMessage = true;
dv.inputMessage = "Value must be Fruit, Vegetable, or Dairy.";
dv.inputTitle = "tip";
activeSheet.setDataValidator(-1, 1, dv);

This example uses a text validator, displays an input tip, and displays an invalid data image if the incorrect value is entered.

SpreadJSvalidtext

Text Validator

JavaScript

spread.highlightInvalidData(true);
var dv = GcSpread.Sheets.DefaultDataValidator.createTextLengthValidator(GcSpread.Sheets.ComparisonOperator.GreaterThan, "4", "20");
dv.showInputMessage = true;
dv.inputMessage = "Number of characters must be greater than 4.";
dv.inputTitle = "tip";
activeSheet.setDataValidator(1, 1, dv);

This example uses a number validator, displays an input tip, and displays an invalid data image if the incorrect value is entered.

SpreadJSvalidnum

Number Validator

JavaScript

spread.highlightInvalidData(true);
var dv = GcSpread.Sheets.DefaultDataValidator.createNumberValidator(GcSpread.Sheets.ComparisonOperator.Between, "5", "20", true);
dv.showInputMessage = true;
dv.inputMessage = "Value must be between 5 and 20.";
dv.inputTitle = "tip";
activeSheet.setDataValidator(1, 1, dv);

This example creates a date validator.

SpreadJSvaliddate

Date Validator

JavaScript

spread.highlightInvalidData(true);
var dv = GcSpread.Sheets.DefaultDataValidator.createDateValidator(GcSpread.Sheets.ComparisonOperator.Between, new Date(2012, 11, 31), new Date(2013, 11, 31));
dv.showInputMessage = true;
dv.inputMessage = "Enter a date between 12/31/2012 and 12/31/2013.";
dv.inputTitle = "Tip";
activeSheet.setDataValidator(1, 1, dv);

This example creates a formula validator.

SpreadJSvalidform

Formula Validator

JavaScript

spread.highlightInvalidData(true);
//The formula validator is valid if the formula condition returns true.
var dv = GcSpread.Sheets.DefaultDataValidator.createFormulaValidator("A1>0");
dv.showInputMessage = true;
dv.inputMessage = "Enter a value greater than 0 in A1.";
dv.inputTitle = "Tip";
activeSheet.setDataValidator(0, 0, dv);

This example uses the isValid method.

JavaScript

var nCondition = new GcSpread.Sheets.CellValueCondition();
nCondition.compareType = GcSpread.Sheets.GeneralCompareType.EqualsTo;
nCondition.expected = 0;
//When the option is false, the validation fails and the red alert is displayed.
//When the option is true, the blank cell is treated as zero and the validation is successful.
nCondition.treatNullValueAsZero = false;
var validator = new GcSpread.Sheets.DefaultDataValidator(nCondition)
validator.IgnoreBlank(false);
activeSheet.getCell(0, 0, GcSpread.Sheets.SheetArea.viewport).dataValidator(validator);
spread.highlightInvalidData(true);
activeSheet.setValue(0, 0, null);
alert(activeSheet.isValid(0, 0, 0));

This example uses the ValidationError event.

JavaScript

var nCondition = new GcSpread.Sheets.CellValueCondition();
nCondition.compareType = GcSpread.Sheets.GeneralCompareType.EqualsTo;
nCondition.expected = 0;
//When the option is false, the validation fails and the red alert is displayed.
//When the option is true, the blank cell is treated as zero and the validation is successful.
nCondition.treatNullValueAsZero = false;
var validator = new GcSpread.Sheets.DefaultDataValidator(nCondition)
validator.IgnoreBlank(false);
activeSheet.getCell(0, 0, GcSpread.Sheets.SheetArea.viewport).dataValidator(validator);
spread.highlightInvalidData(true);
activeSheet.setValue(0, 0, null);

//Type different values in cell (0,0). This event fires if the user types an invalid value.
activeSheet.bind("ValidationError", vError);
 function vError(sender, args) {
alert("error");
            }

Spread ASP.NET and Visual Studio 2015

$
0
0

You can use Spread ASP.NET in Visual Studio 2015.

Use the following steps to add a Spread component to a Web Form in Visual Studio 2015. You can either open an existing Web Site or create a new one.

  1. Start Visual Studio 2015.
  2. Create a new Web site.
  3. Select New Project or from the File menu, choose New, Web Site.
  4. Under Templates, select Web under Visual Basic or Visual C#.

    spreadwebvs2015

    Create Project

  5. Select ASP.NET Web Application. Specify a location and name for the project. Select OK.
  6. Select a template such as Empty.

    spwebtemplate

    Select Template

  7. Select OK.
    If your project does not display the Solution Explorer, from the View menu, choose Solution Explorer. If you used an empty site, you may wish to add a web form to the project (choose Add, Web Form after right-clicking on the project name in the Solution Explorer).
    Specify the Item name. Select OK.

    spwebform

    Form Name

  8. Add the FpSpread component to the Web site.

With an open project, in the Toolbox under Web Forms, select the FpSpread component. Select FpChart if you wish to add the chart at design time. On your Web Forms page, draw an FpSpread component by dragging a rectangle the size that you would like the initial component or simply double-click on the page. The FpSpread component appears (as shown in this Visual Studio 2015 project).

spwebselect

Component in Project

Spread Windows Forms and Visual Studio 2015

$
0
0

You can use Spread Windows Forms in Visual Studio 2015.

Use the following steps to add a Spread control to a project in Visual Studio 2015.

  1. Start Visual Studio .NET.
  2. From the File menu, choose New, Project.
  3. In the New Project dialog, in the Installed area, select a project type depending on the language environment in which you are developing. For example, choose Windows under Visual Basic.

    vs2015newp

    New Project

  4. Choose the type of project such as Windows Forms Application.
  5. In the Name box, type the name of the new project. The default is WindowsApplication1 for the first Windows Forms application.
  6. In the Location box, leave the location path as the designated path, or click Browse to change the path to a new directory.
  7. Select OK.
    If your project does not display the Solution Explorer, from the View menu, choose Solution Explorer. In the Solution Explorer, right-click on the form name, Form1. Choose Rename from the pop-up menu, then type the new form name you prefer for the new form name.
  8. With an open project, in the Toolbox under GrapeCity Spread (or whatever category to which you added it), select the FpSpread component.
  9. On your Windows Forms page, draw a Spread component by dragging a rectangle the size that you would like the initial component or simply double-click on the page. The Spread component appears. The Spread Designer also appears by default. Close the designer.

Your project should look similar to the following image.

vs2015toolspread

Component in Project

Viewing all 105 articles
Browse latest View live