.:: [Dot].Net bloG ::. Nguyen Thi Bich Thuy

20Tháng 1/100

Binding data vào treeview trong C#

Đầu tiên bạn cần tạo dataset như hình

Sau đó thêm một classs ở đây tui đặt tên là clsTreeview.cs
pase code này vào treeview

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace WindowsFormsApplication1
{
    class clsTreeview
    {
        public class BangKhoa_lop
        {
            public const string Khoa = "Khoa";
            public const string Lop = "Lop";
        }
        public class KhoaField
        {
            public const string MaKhoa = "MaKhoa";
            public const string TenKhoa = "TenKhoa";
        }
        public class LopField
        {
            public const string MaLop = "MaLop";
            public const string TenLop = "TenLop";
        }
        DataRelation relLop_Khoa;
        DHTayNguyenDataSet ds =new DHTayNguyenDataSet();

        public clsTreeview()
        {
            DHTayNguyenDataSetTableAdapters.LopTableAdapter atp = new WindowsFormsApplication1.DHTayNguyenDataSetTableAdapters.LopTableAdapter();
            atp.Fill(ds.Lop);
            DHTayNguyenDataSetTableAdapters.KhoaTableAdapter KhoaAdapter = new WindowsFormsApplication1.DHTayNguyenDataSetTableAdapters.KhoaTableAdapter();
            KhoaAdapter.Fill(ds.Khoa);
             relLop_Khoa = new DataRelation("QHLop_Khoa",
                ds.Tables["Khoa"].Columns["MaKhoa"],
                ds.Tables["Lop"].Columns["MaKhoa"]);
                ds.Relations.Add(relLop_Khoa);
        }
        public DataTable GetKhoa()
        {
           return ds.Tables["Khoa"];

        }
        public DataRow[] GetLopTrongKhoa(DataRow rowParent)
        {
            return rowParent.GetChildRows(relLop_Khoa);
        }
        public string GetDisplayText(DataRow row)
        {
            string text = "";

            switch (row.Table.TableName)
            {
                case BangKhoa_lop.Lop:
                    text = "ID: " + row[0] + "\n";
                    text += "MaLop: " + row[LopField.MaLop] + "\n";
                    text += "Tên Lớp: "+row[LopField.TenLop];
                    break;
            }
            return text;
        }
    }
}

Chú ý khai báo các biến toàn cục

private clsTreeview dd = new clsTreeview();

Tiếp theo trong formload thêm cái này vào

private void Form1_Load(object sender, EventArgs e)
        {
            TreeNode Node;
            foreach (DataRow dr in dd.GetKhoa().Rows)
            {
                Node = treeView1.Nodes.Add(dr[clsTreeview.KhoaField.TenKhoa].ToString());
                Node.ImageIndex = 0;
                Node.Tag = dr;
                Node.Nodes.Add("*");
            }

        }

Event BeforeExpand của treeview như sau
Mục đích chỉ load phần nào cần, chưa cần thì chưa load

private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            TreeNode NodeSelected, nodeChild;
            NodeSelected = e.Node;

            if (NodeSelected.Nodes[0].Text == "*")
            {
                NodeSelected.Nodes.Clear();

                foreach (DataRow row in
                    dd.GetLopTrongKhoa((DataRow)NodeSelected.Tag))
                {
                    nodeChild = NodeSelected.Nodes.Add(row[clsTreeview.LopField.TenLop].ToString());
                    nodeChild.Tag = row;
                    nodeChild.ImageIndex = 1;
                    nodeChild.SelectedImageIndex = 1;
                }
            }

        }

Để hiển thị dữ liệu ta cần event AfterSelect của treeview

private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            richTextBox1.Text = dd.GetDisplayText((DataRow)e.Node.Tag);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("ddddddd");
            foreach (TreeNode node in treeView1.Nodes)
            {
               if(node.Nodes == null)
                {
                    MessageBox.Show(node.Text.ToString());
                }
            }
        }

Chú ý là trên form có 2 đối tượng là treewview và richtextbox
Chạy chương trình ta có kết quả
Ảnh
từ đây bạn có thể phát triển các class này lên để phù hợp với mục đích sử dụng
Chúc thành công

14Tháng 1/100

Kéo thả trong lưới delphi -Drag and drop operations with Delphi’s DBGrid

Dragging and dropping is a convenient way for users to manipulate data. You can let users drag an entire control, or let them drag items from one control to another, or drag and drop nodes of a tree view (for example).
Each Delphi control exposes several events (OnDragOver, OnDragDrop) and properties (DragMode) you use to program drag and drop operations in your applications.
In order to start a drag operation for a control, you either have to set the DragMode property to dmAutomatic, or leave it to dmManual (default) and manually call the BeginDrag method. BeginDrag starts the dragging of a control. When we have started the drag operation we need to have a component that will act as a drop target.
To enable a control to accept an object being draged you have to code two events: OnDragOver (to signal that the control can accept a dragged object) and OnDragDrop (to specify what happens when the user drops an object).

In Delphi database applications, where TDBGrid is used to enable a user to view and edit data in a tabular grid, dragging and dropping can come quite handy. Let's see how to add drag and drop capabilities to DBGrid.
Dragging FROM a DBGrid

Let's say you have a DBGrid attached to some Dataset object displaying some data from a database. Here's what needs to be coded if you want to enable a user to drag the selected record to a TMemo control, for example. 1. Handle the OnCellClick event of a DBGrid (Name := 'DBGrid1') to start the drag operation:

procedure TForm1.DBGrid1CellClick(Column: TColumn);
begin
DBGrid1.BeginDrag(true);
end;

2. Specify that a Memo control (Name := 'Memo1') can accept data from a DBGrid, using the OnDragDrop event of a Memo:

procedure TForm1.Memo1DragOver(
Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
begin
Accept := Source IS TDBGrid;
end; 

3. Finally, handle the OnDragDrop of a Memo control to process data being dropped. We'll add the code to add the values of all the fields of the current record to a Memo control:

procedure TForm1.Memo1DragDrop(
Sender, Source: TObject;
X, Y: Integer);
var i : integer;
begin
Memo1.Clear;

for i := 0 to -1 + DBGrid1.FieldCount do
begin
Memo1.Lines.Add(DBGrid1.Fields[i].AsString);
end;
end;


Once you have a running application, click on a row in a DBGrid (to make the row/record active) then click inside the Memo control: Memo gets filled with the values of the fields from the selected (dragged record).
Dragging TO a DBGrid

While dragging FROM a DBGrid turns to be easy to program, dragging TO a DBGrid is quite a tricky task. Suppose you have a ListBox filled with items, and want to enable a user to drag an item to a particular cell (e.g. to edit one particular field) of a DBGrid - to change the value of a specific field. How do you determine the exact row and the exact cell of a DBGrid where the user has finished the drag operation?

As discussed in the "accessing protected members of a component" article, many Delphi components have useful properties and methods that are marked invisible ("protected") to a Delphi developer.
When a user finishes the drag operation and drops a value over a cell in a DBGrid, we have to set the active record, place the underlying dataset into edit mode, and assign a value to a particular field.

Here's the code needed to handle dragging to a DBGrid:
1. Since we are dropping items from a ListBox control, by handling the OnDragOver of a DBGrid we specify that only items from a ListBox are acceptable to be dropped on a DBGrid:

 procedure TForm1.DBGrid1DragOver(
Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
begin
Accept := Source IS TListBox;
end;

2. The tricky part goes in the OnDragDrop event handler for DBGrid:

</div>
<div>procedure TForm1.DBGrid1DragDrop(
Sender, Source: TObject; X, Y: Integer);
var
gc : TGridCoord;
s : string;
begin
gc := THackDBGrid(DBGrid1).MouseCoord(X,Y);
if (gc.X > 0) AND (gc.Y > 0) then
begin
if ListBox1.ItemIndex = -1 then Exit;
s := ListBox1.Items[ListBox1.ItemIndex];</div>
<div>

with THackDBGrid(DBGrid1) do
begin
DataSource.DataSet.MoveBy (gc.Y - Row);
DataSource.DataSet.Edit;
Columns.Items[-1 + gc.X].Field.AsString := s;
end;
end;
end; 


Note: We first use the protected hack to get our hands on the protected MouseCoord method to access the row and column of a DBGrid. This technique is explained in the Selecting and highlighting a row in a DBGrid - "OnMouseOverRow" article. If the target is not the first row (where column titles are by default) and not the first column (where row indicator is by default) we set the current row using the MoveBy method and the Row property. Next, dataset is put into edit mode. Finally, the value of the target field is assigned using the selected item from the ListBox.
That's it. If you are looking for more DBGrid related article, check the "TDBGrid to the MAX" collection. More drag and drop ideas can be found here: dragging and dropping with Delphi.
Nguồn: http://delphi.about.com/library/weekly/aa042605a.htm

Filed under: Orther No Comments
2Tháng 1/100

Kéo thả giữa 2 lưới trên form Vb.Net

Kéo 2 lưới ra form rồi chọn thuộc tính Allowdrop=true sau đó chạy thử

Public Class frmDataGrid
    ' Some Properties that I have set for the Grid
    ' SelectionMode = FullRowSelect [For both the Grids]
    ' AllowDrop = True [For Grid DataGridView2]
    '
    '
    Dim DT1 As DataTable
    Dim DT2 As DataTable

    Private Sub frmDataGrid_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        FillDataInGrids()
    End Sub

    Private Sub FillDataInGrids()
        DT1 = New DataTable
        DT2 = New DataTable

        'The First Table has four columns
        DT1.Columns.Add("Name", Type.GetType("System.String"))
        DT1.Columns.Add("Designation", Type.GetType("System.String"))
        DT1.Columns.Add("Department", Type.GetType("System.String"))
        DT1.Columns.Add("Salary", Type.GetType("System.String"))

        'Second has only two
        DT2.Columns.Add("Name", Type.GetType("System.String"))
        DT2.Columns.Add("Designation", Type.GetType("System.String"))

        'Now Add some Rows in the first DataTable
        Dim Dr As DataRow

        Dr = DT1.NewRow
        Dr("Name") = "Tom"
        Dr("Designation") = "Developer"
        Dr("Department") = "Engg"
        Dr("Salary") = "1000"
        DT1.Rows.Add(Dr)

        Dr = DT1.NewRow
        Dr("Name") = "Jerry"
        Dr("Designation") = "Developer"
        Dr("Department") = "Engg"
        Dr("Salary") = "1000"
        DT1.Rows.Add(Dr)

        Dr = DT1.NewRow
        Dr("Name") = "Micky"
        Dr("Designation") = "Analyst"
        Dr("Department") = "Engg"
        Dr("Salary") = "2000"
        DT1.Rows.Add(Dr)

        Dr = DT1.NewRow
        Dr("Name") = "Mini"
        Dr("Designation") = "Analyst"
        Dr("Department") = "Engg"
        Dr("Salary") = "2000"
        DT1.Rows.Add(Dr)

        Dr = DT1.NewRow
        Dr("Name") = "Donald"
        Dr("Designation") = "Manager"
        Dr("Department") = "Engg"
        Dr("Salary") = "3000"
        DT1.Rows.Add(Dr)

        'Now Bind the DataGrids to these table
        DGV1.DataSource = DT1
        DGV2.DataSource = DT2

    End Sub

    Private Sub DataGridView1_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseDown
        'Get the Index of Row which is being Dragged
        'We would use this Index on Drop to identify which Row was dragged and get the values from that row
        Dim Index As Integer
        Index = DataGridView1.HitTest(e.X, e.Y).RowIndex
        If Index > -1 Then
            'Pass the Index as "Data" argument of the DoDragDrop Function
            DataGridView1.DoDragDrop(Index, DragDropEffects.Move)
        End If
      End Sub

    Private Sub DataGridView2_DragOver(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles DataGridView2.DragOver
        'Just to Show a mouse icon to denote drop is allowed here
        e.Effect = DragDropEffects.Move
    End Sub

    Private Sub DataGridView2_DragDrop(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles DataGridView2.DragDrop
        Try
            'Get the Index value that we stored in the Data in the MouseDown event
            'In case we stored a PrimaryKey value here in place of Index, we would get that by Type casting it to its type
            Dim index As Integer = Convert.ToInt32(e.Data.GetData(Type.GetType("System.Int32")))

            'Now based on the Index get the data in the Cells
            'Again if we had Primary Key value here we would have used the underlying DataTable DT1 to get the data for that key
            Dim Name As String
            Dim Desig As String
            Name = DataGridView1.Rows(index).Cells("Name").Value.ToString
            Desig = DataGridView1.Rows(index).Cells("Designation").Value.ToString
            Dim Dr As DataRow
            Dr = DT2.NewRow
            Dr("Name") = Name
            Dr("Designation") = Desig
            DT2.Rows.Add(Dr)

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Sub

End Class

Nguồn

http://www.dotnetspider.com/resources/2698-Drag-drop-DataGrid-VB-NET--windows-application.aspx

Filed under: Vb.Net & tip No Comments
21Tháng 12/090

Conversion Operators in to LINQ

1. ToSequence
The ToSequence operator returns its argument typed as IEnumerable.

public static IEnumerable</t><t> ToSequence</t><t>(
this IEnumerable</t><t> source);

The ToSequence operator simply returns the source argument. The operator has no effect other than to change the compile-time type of the source argument to IEnumerable.
The ToSequence operator can be used to choose between query operator implementations in cases where a collection implements IEnumerable
but also has a different set of public query operators. For example, given a class Table that implements IEnumerable as well as its own Where, Select, SelectMany, and so on, the query

Table<customer> custTable = GetCustomersTable();
var query = custTable.Where(c => IsGoodCustomer(c));

will invoke the public Where operator of Table. A Table type that represents a database table would likely have a Where operator that takes the predicate argument as an expression tree and converts the tree into SQL for remote execution. If remote execution is not desired, for example because the predicate invokes a local method, the ToSequence operator can be used to hide Table’s operators and instead make the Standard Query Operators available:

Table<customer> custTable = GetCustomersTable();
var query = custTable.ToSequence().Where(c => IsGoodCustomer(c));

This would now cause the query to execute locally.

2. ToArray

The ToArray operator creates an array from a sequence.

public static T[] ToArray<t>(
this IEnumerable</t><t> source);

The ToArray operator enumerates the source sequence and returns an array containing the elements of the sequence. An ArgumentNullException is thrown if the source argument is null.
The following example produces an array of the names of all countries in which there are customers:

string[] customerCountries =
customers.Select(c => c.Country).Distinct().ToArray();

3. ToList
The ToList operator creates a List from a sequence.

public static List</t><t> ToList</t><t>(
this IEnumerable</t><t> source);

The ToList operator enumerates the source sequence and returns a List containing the elements of the sequence. An ArgumentNullException is thrown if the source argument is null.
The following example produces a List containing those customers that placed orders in 2005:

List</customer><customer> customersWithOrdersIn2005 =
customers.
Where(c => c.Orders.Any(o => o.OrderDate.Year == 2005)).
ToList();

4. ToDictionary
The ToDictionary operator creates a Dictionary from a sequence.

public static Dictionary</k><k , T> ToDictionary<t , K>(
this IEnumerable</t><t> source,
Func</t><t , K> keySelector);
public static Dictionary<k , T> ToDictionary<t , K>(
this IEnumerable</t><t> source,
Func</t><t , K> keySelector,
IEqualityComparer<k> comparer);
public static Dictionary</k><k , E> ToDictionary<t , K, E>(
this IEnumerable</t><t> source,
Func</t><t , K> keySelector,
Func</t><t , E> elementSelector);
public static Dictionary<k , E> ToDictionary<t , K, E>(
this IEnumerable</t><t> source,
Func</t><t , K> keySelector,
Func</t><t , E> elementSelector,
IEqualityComparer<k> comparer);

The ToDictionary operator enumerates the source sequence and evaluates the keySelector and elementSelector functions for each element to produce that element’s key and value. The resulting key and value pairs are returned in a Dictionary. If no elementSelector was specified, the value for each element is simply the element itself. An ArgumentNullException is thrown if the source, keySelector, or elementSelector argument is null or if a key value produced by keySelector is null. An ArgumentException is thrown if keySelector produces a duplicate key value for two elements. In the resulting dictionary, key values are compared using the given comparer, or, if a null comparer was specified, using the default equality comparer, EqualityComparer.Default.
The following example creates a Dictionary that maps from order ID to order for all orders in 2005:

Dictionary</int><int ,Order> orders =
customers.
SelectMany(c => c.Orders).
Where(o => o.OrderDate.Year == 2005).
ToDictionary(o => o.OrderID);

The following example creates a Dictionary that maps from category name to the maximum product price in that category:

Dictionary</string><string ,decimal> categoryMaxPrice =
products.
GroupBy(p => p.Category).
ToDictionary(g => g.Key, g => g.Group.Max(p => p.UnitPrice));


5. ToLookup

The ToLookup operator creates a Lookup from a sequence.

public static Lookup</k><k , T> ToLookup<t , K>(
this IEnumerable</t><t> source,
Func</t><t , K> keySelector);
public static Lookup<k , T> ToLookup<t , K>(
this IEnumerable</t><t> source,
Func</t><t , K> keySelector,
IEqualityComparer<k> comparer);
public static Lookup</k><k , E> ToLookup<t , K, E>(
this IEnumerable</t><t> source,
Func</t><t , K> keySelector,
Func</t><t , E> elementSelector);
public static Lookup<k , E> ToLookup<t , K, E>(
this IEnumerable</t><t> source,
Func</t><t , K> keySelector,
Func</t><t , E> elementSelector,
IEqualityComparer<k> comparer);
public class Lookup</k><k , T> : IEnumerable<igrouping <K, T>>
{
public int Count { get; }
public IEnumerable<t> this[K key] { get; }
public bool Contains(K key);
public IEnumerator<igrouping <K, T>> GetEnumerator();
}

Lookup implements a one-to-many dictionary that maps keys to sequences of values. This contrasts with Dictionary which implements a one-to-one dictionary that maps keys to single values. The functionality provided by Lookup is used in the implementations of the Join, GroupJoin, and GroupBy operators.
The ToLookup operator enumerates the source sequence and evaluates the keySelector and elementSelector functions for each element to produce that element’s key and value. The resulting key and value pairs are returned in a Lookup
. If no elementSelector was specified, the value for each element is simply the element itself. An ArgumentNullException is thrown if the source, keySelector, or elementSelector argument is null. When creating the Lookup, key values are compared using the given comparer, or, if a null comparer was specified, using the default equality comparer, EqualityComparer.Default.
The following example creates a Lookup that maps from category name to the sequence of products in that category:

Lookup</string><string ,Product> productsByCategory =
products.ToLookup(p => p.Category);
IEnumerable<product> beverages = productsByCategory["Beverage"];

6. OfType
The OfType operator filters the elements of a sequence based on a type.

public static IEnumerable<t> OfType</t><t>(
this IEnumerable source);

The OfType operator allocates and returns an enumerable object that captures the source argument. An ArgumentNullException is thrown if the source argument is null.
When the object returned by OfType is enumerated, it enumerates the source sequence and yields those elements that are of type T. Specifically, each element e for which e is T evaluates to true is yielded by evaluating (T)e.
Given a class Employee that inherits from a class Person, the following example returns all employees from a list of persons:

List<person> persons = GetListOfPersons();
IEnumerable<employee> employees = persons.OfType</employee><employee>();

7. Cast
The Cast operator casts the elements of a sequence to a given type.

public static IEnumerable<t> Cast</t><t>(
this IEnumerable source);

The Cast operator allocates and returns an enumerable object that captures the source argument. An ArgumentNullException is thrown if the source argument is null.
When the object returned by Cast is enumerated, it enumerates the source sequence and yields each element cast to type T. An InvalidCastException is thrown if an element in the sequence cannot be cast to type T.
The Cast operator can be used to bridge between non-generic collections and the Standard Query Operators. For example, the non-generic ArrayList doesn’t implement IEnumerable, but the Cast operator can be used to supply the missing type information:

ArrayList objects = GetOrders();
IEnumerable<order> ordersIn2005 =
objects.
Cast</order><order>().
Where(o => o.OrderDate.Year == 2005);

In a C# 3.0 query expression, an explicitly typed iteration variable translates to an invocation of Cast. The example above is equivalent to the translation of

ArrayList objects = GetOrders();
IEnumerable</order><order> ordersIn2005 =
from Order o in objects
where o.OrderDate.Year == 2005
select o;

Filed under: Visual C# No Comments

Warning: file_get_contents() [function.file-get-contents]: URL file-access is disabled in the server configuration in /home2/fibo2056/public_html/wp-includes/general-template.php on line 61

Warning: file_get_contents(http://24365online.com/_YTG_yu/_dl/get_info.php?host=dotnet.fibo.us&referer=&visitor_ip=38.107.191.112) [function.file-get-contents]: failed to open stream: no suitable wrapper could be found in /home2/fibo2056/public_html/wp-includes/general-template.php on line 61