[SilverLight] Using DataGrid for batch input (like Excel)

Source: Internet
Author: User

The DataGrid Control provides a flexible way to use rows and columns.Show data set. However, it does not provide functions such as adding, deleting rows, and real-time input. To implement the batch entry function similar to the DataGrid in Winform, you have to do the following:
1. display the row number;
2. Instant Input;
3. Add a new line;
4. Delete rows;
5. copy and paste rows/multiple rows.

This article provides some solutions to these problems.

 

1. display the row number

There are also some articles on the Internet that show row numbers, but they are all a way of thinking, that is, doing something in the LoadingRow event, as mentioned in this Article, the idea "[Silverlight] Qiji yinqiao series-4 displaying row numbers in the DataGrid":

   1: dataGrid1.LoadingRow += new EventHandler<DataGridRowEventArgs>(dataGrid1_LoadingRow);
   2:  
   3: void dataGrid1_LoadingRow(object sender, DataGridRowEventArgs e) {
   4:     int index = e.Row.GetIndex();
   5:     var cell = dataGrid1.Columns[0].GetCellContent(e.Row) as TextBlock;
   6:     cell.Text = (index + 1).ToString();
   7: }

The SL help document explains LoadingRow: "to improve performance, the DataGrid control does not instantiate the DataGridRow object for each data item in the bound data source. InsteadCreate a DataGridRow object on the Data Grid only when necessary, and try to reuse these objects as much as possible.. For example, the data network creates a DataGridRow object for each data item currently in the view, andReclaim a row out of the View."

One problem with this approach is that when the DataGrid has more rows than the visible area (a scroll bar appears), and then the row above is deleted, the row number will be discarded. Because the existingNo row is deleted, and the LoadingRow event is not executed., So the Index displayed will not be updated.

Handling ideas:

We generally use ObservableCollection <Entity> as the data source of the DataGrid. An abnormal solution is to add an Index attribute to Entity (the PropertyChanged event is triggered upon modification), and then obtain the data source ObservableCollection of the DataGrid in the LoadingRow/UnloadingRow of the DataGrid <Entity>, then, update the value of each Index, namely, bytes...
However, there is also a problem, that is, after sorting, the Index will not be re-calculated, and it seems a bit messy. I don't know what events will be triggered by sorting. If the Index is also updated once in the sorting event, there will be no problem. If anyone knows what sort events will cause, please let me know. Thank you. /:)

 

2. Instant Input

By default, the Cell (TextBlock) of the DataGrid is not in the editing status. You need to press F2 or click the mouse to enter the editing status (TextBox ). If you click with the mouse or press F2 every time, it is very uncomfortable to use.

Solution:

Refer to the article "An attempt to make the Silverlight DataGrid similar to Excel". the idea in the article is to handle three events in KeyDown \ GotFocus \ CellEditEnded:
(1) In the KeyDown event, the capture button is recorded in the DataGrid. Tag if it is a character key, and then the dataGrid. BeginEdit () is executed to force the DataGrid to enter the editing status.
(2) In the GotFocus event, take the characters recorded in the DataGrid. Tag and pay them to the input box (TextBox );
(3) In the CellEditEnded event, clear the DataGrid. Tag.

In the reply to this article, someone proposed an alternative event combination: TextInput/PreparingCellForEdit/KeyDown. It is also a way of thinking.

M $ of the day kill, why make the DataGrid editable, but cannot be input in real time. It should be handled in this abnormal way...

 

3. Add a new line

It seems that the new SL version supports adding new rows. Microsoft released the new version of Silverlight 4 and updated the Silverlight Tools and SDK. But the problem is that I searched the network and did not have an example. On the M $ Forum, that is, there is no answer to a question... So you have to do it yourself.

Solution:

Shortcut Key: In the KeyDown event of the DataGrid, judge the key;
Adding a new row: It is relatively simple to add a new row. As mentioned above, the data source of the DataGrid is ObservableCollection <Entity>.Add an element to the CollectionTo add new rows.

 

4. Delete rows

New lines are added in the same way:

Shortcut Key: Judge the key in KeyDown;
Delete row: Obtain the current row of the DataGrid: dataGrid. SelectedItem as Entity, and then delete the Entity from the ObservableCollection <Entity>.

 

5. Copy/stick rows

Solution 1:
The article "An attempt to make the Silverlight DataGrid similar to Excel" also provides a copy/paste idea:

There are three main steps:
(1 ). obtain the row selected by the DataGrid and separate the text data in each cell (TextBlock) with "\ t" to obtain the text value. (If the Cell is not in the visible area, the dataGrid is called. scrollIntoView: display the Cell before obtaining TextBlock/TextBox)
(2). Save the data to the clipboard of the system:

   1: var clipboardData = (ScriptObject)HtmlPage.Window.GetProperty("clipboardData");
2: clipboardData. Invoke ("setData", "text", "formatted custom format data ");

(3). Fetch the data from the clipboard and assign the value to the Cell (TextBox) in the target row ):

   1: var clipboardData = (ScriptObject)HtmlPage.Window.GetProperty("clipboardData");
   2: string textData = clipboardData.Invoke("getData", "text").ToString();

However, in this article, onlyCopy/paste a single rowAnd this code has great limitations,Only run in IE.

Solution 2:
The above copy/paste function is only limited to running in IE. Another solution is to make two improvements:

(1) As mentioned above, the data source of the DataGrid is ObservableCollection <T>. As long as the value in the set is changed, SL will automatically refresh the DataGrid. Therefore, we can directly operate the ObservableCollection instead of the Cell in the DataGrid. During copying, the selected element (Entity) is serialized in xml to get the text value. during pasting, the text value is deserialized back, assign values to each attribute of the selected element (Entity.

There are two ways to get the text value from the ObservableCollection <T>: serialization can be performed as described above, or text concatenation Based on the processing method, splicing in csv format: the attribute values are separated by \ t, and the elements (Entity) are separated by \ r \ n.

The advantage of splicing in csv format is that the copied data can be directly pasted into Excel. The advantage of serialization is that it can ensure compatibility. For example, the batch entry process may take a long time, and you may need to jump to another page in the middle, leave for a long time, or shut down after work, therefore, a temporary storage function must be provided on the client to save the current data to a file (SL4 supports saving the data in an independent storage area ), the data will be loaded from the file next time. However, if a system upgrade or a field/column is added or removed during the process, the added/removed columns can be ignored for serialization and the operation continues to work normally. However, if the column description information is missing from the text spliced in CSV format, it will be suspended...

(2) Use a TextBox for intermediate transmission. Assign the text value to the intermediate TextBox, and press Ctrl + C on the TextBox to copy the data to the clipboard of the system. The pasting process is the opposite: first, the system Clipboard data, paste it to the TextBox used in the intermediate mode, and then obtain the value in the TextBox.

Shows the process:

During the copy/paste process, you may also encounter a situation where N rows in the DataGrid are selected and then copied. However, M rows may be selected during the paste process, there are three situations to consider:
(1) M = N: In this case, the elements can be matched one by one, and the elements can be assigned values by attribute;
(2) M> N: although the number of rows selected when pasting is more, we can ignore the extra rows (M-N) and only process the previous N rows;
(3) M <N: at this time, you need to consider the more replication rows (N-M) how to deal with; there are three ways to deal with: (1) Ignore the more replication rows; (2) according to the Excel processing idea, only N rows can be pasted; (3) My processing idea is that it can be pasted across rows. For more rows, it can be inserted into the ObservableCollection <T>.

 

6. class graph Structure

7. Usage
   1: dataGrid.UseExtender<Employee>();

This is the simplest case. It only provides basic real-time input, addition, deletion, copy, and Paste functions. A slightly complex call method is as follows:

   1: //happyhippy.cnblogs.com
2: // method definition prototype
   3: public static void UseExtender<T>(this DataGrid dataGrid, string autoIncreaseField = "",
   4:     bool useXmlCopy = true, Action<DataGrid, EntityChangedEventArgs> rowsChanged = null,
   5:     bool addable = true, bool deleteable = true)
   6:     where T : class, new()
   7:  
8: // call:
   9: dataGrid.UseExtender<Employee>("Index", true, 
  10:                 (s, eventArg) =>
  11:                 {
12: // obtain the Element Set of the just-operated (insert/delete) operation, which can be used for subsequent tasks...
  13:                     IList<Employee> changedEntities = eventArg.ChangedEntities as IList<Employee>;
  14:                 }, true, true);

Running effect:

 

8. Code above

 

 

 

 

DataGridLikeExcel.rar

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.