2017-08-17 61 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