2017年2月17日 星期五

Linq Join 方式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// linq 正規 Join 方式
DataTable dt = (from l in db.Log
                    join u in db.User on l.InsertUserId equals u.Id into lu
                from j1 in lu.DefaultIfEmpty()
                    join i in db.Item on l.ItemId equals i.Id into li
                from j2 in li.DefaultIfEmpty()
                join it in db.ItemType on j2.ItemTypeId equals it.Id
                select new
                {
                    Id = l.Id,
                    日期 = l.Date,
                    項目 = it.ItemTypeName + "-" + j2.ItemName,
                    價格 = l.Price,
                    人員 = j1.UserName,
                }
).ToDataTable();

// linq 非正規 Join 方式
DataTable dt = (
    from l in db.Log
    from u in db.User
    from i in db.Item
    from it in db.ItemType
    where 1 == 1
    && l.InsertUserId == u.Id
    && l.ItemId == i.Id
    && i.ItemTypeId == it.Id
    && (i.ItemName.Contains(Query) || it.ItemTypeName.Contains(Query))
    select new
    {
        Id = l.Id,
        日期 = l.Date,
        項目 = it.ItemTypeName + "-" + i.ItemName,
        價格 = l.Price,
        人員 = u.UserName,
    }
).ToDataTable();

EventHandler 自訂事件

UserControl1.cs
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public partial class UserControl1 : UserControl
{
    /// <summary>
    /// 建立事件處理
    /// </summary>
    new public event EventHandler TextChanged;
        
    /// <summary>
    /// 事件處理函數
    /// </summary>
    protected void OnTextChanged()
    {
        // 如果有建立事件監聽,則Invoke
        TextChanged?.Invoke(this.textBox1, new EventArgs());
    }
    public UserControl1()
    {
        InitializeComponent();
    }

    /// <summary>
    /// 使用者控制項 的 TextBox 預設 TextChanged 事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        OnTextChanged();
    }
}


Form1.cs
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // 針對使用者控制項新增自訂的 TextChanged 事件
        this.userControl11.TextChanged += UserControl11_TextChanged;
    }

    /// <summary>
    /// 使用者控制項新增自訂的 TextChanged 事件處理函數
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void UserControl11_TextChanged(object sender, EventArgs e)
    {
        if (sender is TextBox)
        {
            TextBox tb = sender as TextBox;
            label1.Text = tb.Text;
        }
    }
}