2017-08-17 62 views
1

我正在開發一個Windows窗體應用程序。我使用DataGridView和與LINQ to SQL的數據綁定。它正在工作。它綁定了整個數據。如何使用數據綁定Linq to SQL來添加自定義字段

我需要一些領域,而不是整個表的數據,例如:

Customers表包含五個字段(姓名,地址,手機,電子郵件,年齡)。

我使用下面的代碼來獲取整個數據。

private void AssignLocation_Load(object sender, EventArgs e) 
{ 
    // Get Datacontext object to connect with data source 
    SmartxBillingSystemDataContext dc = new SmartxBillingSystemDataContext(); 

    // create table object 
    Customer customer = new Customer(); 
    var allcustomers = from c in dc.GetTable<Customer>() select c; 

    // bind to datagrid 
    customerBindingSource.DataSource = allcustomers; 

    // now assign binding source to data grid view 
    dataGridView1.DataSource = customerBindingSource; 

}  

現在我只需要一些字段,例如名稱和地址。

此外,我需要每行中添加一個按鈕,像這樣:

| A Name  | An Address | Button | 
| Another Name | Fake Address | Button | 

我怎樣才能做到這一點?請幫忙。

點擊事件我用下面的代碼

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) 
     { 
      popUpLocationWindow(); 
     } 

     private void popUpLocationWindow() 
     { 
      MessageBox.Show("I am clicked"); 
     } 

但這不是代碼作品。

+0

是否https://stackoverflow.com/questions/6960739/how-to-hide-column-of-datagridview-when-using-custom-datasource幫助嗎? – mjwills

+0

@mjwills,我是新的發展中國家,不知道提供的鏈接。你能否給我一些與我的情景相關的想法,以便我消化。 –

+0

你必須逐個添加一個數據成員到你想要的gridview,那麼** datafieldname **應該與對象屬性相同,以便綁定帶有按鈕類型的額外字段以具有額外的列。 –

回答

2

您可以創建自己的類:

public class MyCustomer 
{ 
    public string Name { get; set; } 
    public string Address { get; set; } 
} 

,並選擇這樣的:

var allMycustomers = from c in dc.GetTable<Customer>() select new MyCustomer { Name = c.Name, Address = c.Address }; 

customerBindingSource.DataSource = allMycustomers; 

的按鈕:

DataGridViewButtonColumn btn = new DataGridViewButtonColumn(); 
btn.HeaderText = "Button"; 
btn.Text = "Click Me!"; 
btn.Name = "btn"; 
dataGridView1.Columns.Add(btn); 
btn.UseColumnTextForButtonValue = true; 

更新的按鈕單擊事件中,你可以使用dataGridView1_CellClick事件..

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) 
{ 
    if (e.ColumnIndex == 2) 
    { 
      MessageBox.Show((e.RowIndex+1) + " Row " + (e.ColumnIndex+1) + " Column button clicked "); 
    } 
} 
+0

親愛的凱恩,謝謝你的幫助。是的,它的工作。還有一件事。如果我需要在按鈕上製作方法,請點擊我如何做到這一點? –

+0

我如何使用此按鈕管理事件? –

+0

@SalmanMushtaq我已經更新了我的答案,我希望它可以幫助... – caner